Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 79 additions & 6 deletions src/app/panel/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,11 @@ function ConnectBar({ daemon }: { daemon: UseDaemonResult }) {
const [urlInput, setUrlInput] = useState("")
const [tokenInput, setTokenInput] = useState("")
const [copied, setCopied] = useState(false)
const [shareOpen, setShareOpen] = useState(false)
// Opt-in — a copied link with the token embedded grants full access to
// whoever opens it (agentproto/ts#1398: a remote daemon in bearer mode
// requires this exact token on every route), so it defaults off.
const [includeToken, setIncludeToken] = useState(false)

const submit = () => {
if (!urlInput.trim()) return
Expand All @@ -450,12 +455,18 @@ function ConnectBar({ daemon }: { daemon: UseDaemonResult }) {
setTokenInput("")
}

// Shareable deep-link: the tunnel wss origin, no token (auth rides the
// trusted panel Origin). Opening it on another machine auto-connects.
// Shareable deep-link: the fragment form (`#daemon=&token=`) — fragments
// never reach a server (no Referer, no access/proxy log, no CDN cache
// key), unlike the legacy `?daemon=&token=` query-string form this panel
// still accepts for back-compat. The token is only embedded when
// `includeToken` is explicitly checked; without it, whoever opens the
// link still needs to paste the token in themselves via "connect ▾".
const shareLink = (): string => {
if (typeof window === "undefined" || !daemon.url) return ""
const wss = daemon.url.replace(/^http/, "ws")
return `${window.location.origin}/panel?daemon=${encodeURIComponent(wss)}`
const params = new URLSearchParams({ daemon: wss })
if (includeToken && daemon.token) params.set("token", daemon.token)
return `${window.location.origin}/panel#${params.toString()}`
}

const copyLink = async () => {
Expand All @@ -464,6 +475,7 @@ function ConnectBar({ daemon }: { daemon: UseDaemonResult }) {
try {
await navigator.clipboard.writeText(link)
setCopied(true)
setShareOpen(false)
setTimeout(() => setCopied(false), 1500)
} catch {
/* clipboard blocked — ignore */
Expand Down Expand Up @@ -535,9 +547,67 @@ function ConnectBar({ daemon }: { daemon: UseDaemonResult }) {
</span>
)}
{daemon.remote && (
<button style={btn} onClick={copyLink} title="Copy a shareable link to this daemon">
{copied ? "copied ✓" : "copy link"}
</button>
<div style={{ position: "relative" }}>
<button
style={btn}
onClick={() => setShareOpen(o => !o)}
title="Copy a shareable link to this daemon"
>
{copied ? "copied ✓" : shareOpen ? "close" : "copy link ▾"}
</button>
{shareOpen && (
<div
style={{
position: "absolute",
top: "calc(100% + 6px)",
right: 0,
zIndex: 20,
width: 260,
maxWidth: "calc(100vw - 32px)",
padding: 12,
border: "1px solid #333",
borderRadius: 8,
background: "#0e0e10",
boxShadow: "0 8px 24px rgba(0,0,0,0.5)",
display: "flex",
flexDirection: "column",
gap: 8,
}}
>
<label
style={{
display: "flex",
alignItems: "center",
gap: 6,
color: "#9ca3af",
fontSize: 10,
cursor: daemon.token ? "pointer" : "not-allowed",
}}
>
<input
type="checkbox"
checked={includeToken}
disabled={!daemon.token}
onChange={e => setIncludeToken(e.target.checked)}
/>
include access token
</label>
<div style={{ color: "#6b7280", fontSize: 9, lineHeight: 1.5 }}>
{daemon.token
? includeToken
? "Anyone with this link gets full access to this daemon — share it only with someone you trust."
: "Without the token, whoever opens this link must paste it in themselves via “connect”."
: "This connection has no token to embed."}
</div>
<button
style={{ ...btn, borderColor: "#22d3ee40", color: "#22d3ee" }}
onClick={() => void copyLink()}
>
copy
</button>
</div>
)}
</div>
)}
{daemon.remote && (
<button style={btn} onClick={daemon.disconnect} title="Disconnect and fall back to the local daemon">
Expand Down Expand Up @@ -863,13 +933,15 @@ export default function PanelPage() {
daemonUrl={daemon.url!}
sessionId={selected.id}
sessionStatus={selected.status}
token={daemon.token}
/>
) : (
<SessionEventsView
key={selected.id}
daemonUrl={daemon.url!}
sessionId={selected.id}
sessionStatus={selected.status}
token={daemon.token}
onNotSupported={handleEventsNotSupported}
/>
)
Expand All @@ -880,6 +952,7 @@ export default function PanelPage() {
daemonUrl={daemon.url!}
sessionId={selected.id}
sessionStatus={selected.status}
token={daemon.token}
/>
)}
{tab === "tty" && (
Expand Down
38 changes: 22 additions & 16 deletions src/components/SessionChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { toDisplayText } from "@/components/ToolBlocks"
import { daemonFetch } from "@/lib/use-daemon"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"

Expand Down Expand Up @@ -727,10 +728,12 @@ function PromptInput({
daemonUrl,
sessionId,
disabled,
token,
}: {
daemonUrl: string
sessionId: string
disabled: boolean
token?: string | null
}) {
const [value, setValue] = useState("")
const [sending, setSending] = useState(false)
Expand All @@ -742,10 +745,8 @@ function PromptInput({
setSending(true)
setErr(null)
try {
const res = await fetch(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/prompt`, {
const res = await daemonFetch(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/prompt`, token, {
method: "POST",
mode: "cors",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: trimmed }),
})
Expand All @@ -759,7 +760,7 @@ function PromptInput({
} finally {
setSending(false)
}
}, [value, sending, daemonUrl, sessionId])
}, [value, sending, daemonUrl, sessionId, token])

const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
Expand Down Expand Up @@ -836,9 +837,11 @@ interface Props {
daemonUrl: string
sessionId: string
sessionStatus: string
/** Bearer token for a remote/tunnel daemon connection; omitted for local. */
token?: string | null
}

export function SessionChatView({ daemonUrl, sessionId, sessionStatus }: Props) {
export function SessionChatView({ daemonUrl, sessionId, sessionStatus, token }: Props) {
const [transcript, setTranscript] = useState<ParsedContent | null>(null)
const [rawExport, setRawExport] = useState<ExportResponse | null>(null)
const [noTranscript, setNoTranscript] = useState(false)
Expand All @@ -858,15 +861,15 @@ export function SessionChatView({ daemonUrl, sessionId, sessionStatus }: Props)

const fetchTranscript = useCallback(async () => {
try {
let res = await fetch(
let res = await daemonFetch(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/export?format=json`,
{ mode: "cors", credentials: "include" }
token,
)
if (!res.ok && (res.status === 404 || res.status === 422)) {
// Retry with source=daemon
res = await fetch(
res = await daemonFetch(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/export?format=json&source=daemon`,
{ mode: "cors", credentials: "include" }
token,
)
}
if (!res.ok) {
Expand All @@ -891,7 +894,7 @@ export function SessionChatView({ daemonUrl, sessionId, sessionStatus }: Props)
setFetchErr(e instanceof Error ? e.message : String(e))
}
}
}, [daemonUrl, sessionId])
}, [daemonUrl, sessionId, token])

// Scroll to bottom when new messages arrive
useEffect(() => {
Expand Down Expand Up @@ -995,6 +998,7 @@ export function SessionChatView({ daemonUrl, sessionId, sessionStatus }: Props)
daemonUrl={daemonUrl}
sessionId={sessionId}
disabled={!isRunning}
token={token}
/>
)}
</div>
Expand Down Expand Up @@ -1212,9 +1216,11 @@ interface JsonViewProps {
daemonUrl: string
sessionId: string
sessionStatus: string
/** Bearer token for a remote/tunnel daemon connection; omitted for local. */
token?: string | null
}

export function SessionJsonView({ daemonUrl, sessionId, sessionStatus }: JsonViewProps) {
export function SessionJsonView({ daemonUrl, sessionId, sessionStatus, token }: JsonViewProps) {
const [data, setData] = useState<ExportResponse | null>(null)
const [noTranscript, setNoTranscript] = useState(false)
const [fetchErr, setFetchErr] = useState<string | null>(null)
Expand All @@ -1223,14 +1229,14 @@ export function SessionJsonView({ daemonUrl, sessionId, sessionStatus }: JsonVie

const fetchData = useCallback(async () => {
try {
let res = await fetch(
let res = await daemonFetch(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/export?format=json`,
{ mode: "cors", credentials: "include" }
token,
)
if (!res.ok && (res.status === 404 || res.status === 422)) {
res = await fetch(
res = await daemonFetch(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/export?format=json&source=daemon`,
{ mode: "cors", credentials: "include" }
token,
)
}
if (!res.ok) {
Expand All @@ -1247,7 +1253,7 @@ export function SessionJsonView({ daemonUrl, sessionId, sessionStatus }: JsonVie
} catch (e) {
setFetchErr(e instanceof Error ? e.message : String(e))
}
}, [daemonUrl, sessionId])
}, [daemonUrl, sessionId, token])

useEffect(() => {
setData(null)
Expand Down
27 changes: 20 additions & 7 deletions src/components/SessionEventsView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
type ToolResultEvent,
type UsageCost,
} from "@/lib/use-session-events"
import { daemonFetch } from "@/lib/use-daemon"
import { PlanList, ToolPairBlock, toDisplayText } from "@/components/ToolBlocks"

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -601,7 +602,17 @@ function RenderItemView({ item, groupExpanded, onGroupToggle }: RenderItemViewPr
// PromptInput (same as SessionChatView, duplicated to keep file self-contained)
// ---------------------------------------------------------------------------

function PromptInput({ daemonUrl, sessionId, disabled }: { daemonUrl: string; sessionId: string; disabled: boolean }) {
function PromptInput({
daemonUrl,
sessionId,
disabled,
token,
}: {
daemonUrl: string
sessionId: string
disabled: boolean
token?: string | null
}) {
const [value, setValue] = useState("")
const [sending, setSending] = useState(false)
const [err, setErr] = useState<string | null>(null)
Expand All @@ -612,8 +623,8 @@ function PromptInput({ daemonUrl, sessionId, disabled }: { daemonUrl: string; se
setSending(true)
setErr(null)
try {
const res = await fetch(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/prompt`, {
method: "POST", mode: "cors", credentials: "include",
const res = await daemonFetch(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/prompt`, token, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: trimmed }),
})
Expand All @@ -627,7 +638,7 @@ function PromptInput({ daemonUrl, sessionId, disabled }: { daemonUrl: string; se
} finally {
setSending(false)
}
}, [value, sending, daemonUrl, sessionId])
}, [value, sending, daemonUrl, sessionId, token])

const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void send() }
Expand Down Expand Up @@ -688,12 +699,14 @@ interface Props {
daemonUrl: string
sessionId: string
sessionStatus: string
/** Bearer token for a remote/tunnel daemon connection; omitted for local. */
token?: string | null
/** Called when the events endpoint 404s so the parent can fall back to export polling. */
onNotSupported: () => void
}

export function SessionEventsView({ daemonUrl, sessionId, sessionStatus, onNotSupported }: Props) {
const { events, notSupported, loading, error } = useSessionEvents(daemonUrl, sessionId, sessionStatus)
export function SessionEventsView({ daemonUrl, sessionId, sessionStatus, token, onNotSupported }: Props) {
const { events, notSupported, loading, error } = useSessionEvents(daemonUrl, sessionId, sessionStatus, token)
const scrollRef = useRef<HTMLDivElement | null>(null)
const isRunning = sessionStatus === "running"

Expand Down Expand Up @@ -757,7 +770,7 @@ export function SessionEventsView({ daemonUrl, sessionId, sessionStatus, onNotSu
</div>

{/* Prompt input */}
<PromptInput daemonUrl={daemonUrl} sessionId={sessionId} disabled={!isRunning} />
<PromptInput daemonUrl={daemonUrl} sessionId={sessionId} disabled={!isRunning} token={token} />
</div>
)
}
15 changes: 7 additions & 8 deletions src/components/SessionTerminal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type { Terminal as XTerminal } from "@xterm/xterm"
import type { FitAddon as FitAddonType } from "@xterm/addon-fit"
import "@xterm/xterm/css/xterm.css"
import { cn } from "@/lib/utils"
import { withToken } from "@/lib/use-daemon"

interface Props {
daemonUrl: string
Expand Down Expand Up @@ -146,9 +147,8 @@ function attachPty({
const cols = term.cols || 80
const rows = term.rows || 24
const qs = new URLSearchParams({ cols: String(cols), rows: String(rows) })
if (token) qs.set("token", token)
const sock = new WebSocket(
`${wsBase}/sessions/${encodeURIComponent(sessionId)}/pty?${qs}`
withToken(`${wsBase}/sessions/${encodeURIComponent(sessionId)}/pty?${qs}`, token)
)
ws = sock

Expand Down Expand Up @@ -233,13 +233,12 @@ function attachSse({
}): () => void {
const dim = "\x1b[2m", reset = "\x1b[0m"
term.writeln(`${dim}── attached to ${sessionId} (${daemonUrl}) ──${reset}`)
// The SSE stream is read-only and ungated, so a token isn't required — but
// an EventSource can't set an Authorization header, so we thread it via the
// query string (same `?token=` the WS path uses) to stay correct if a daemon
// ever gates the stream.
const streamQs = token ? `?token=${encodeURIComponent(token)}` : ""
// A remote daemon in bearer mode (agentproto/ts#1398) 401s this stream for
// any non-loopback request without the bearer — and an EventSource can't
// set an Authorization header, so it rides the query string instead (same
// `?token=` the WS path uses).
const src = new EventSource(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/stream${streamQs}`,
withToken(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/stream`, token),
{ withCredentials: true }
)
src.onmessage = ev => {
Expand Down
Loading
Loading