Multiplayer agent harness for work.
web-ui: open in-app session links in place instead of a new tab/window (#1793)
Regan Bell5b273aedf2d5
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex d2cdf917c..6510a1ad1 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -1292,7 +1292,8 @@ export function createChatSurface(else readonlyRedraw?.();}- function togglePins(): void {+ function togglePins(e: Event): void {+ if ((e.target as Element | null)?.closest("a")) return;chatState.pinsExpanded = !chatState.pinsExpanded;if (chatState.agent) drawActiveChat(chatState.agent);else readonlyRedraw?.();@@ -1301,9 +1302,7 @@ export function createChatSurface(function linkifiedText(text: string): TemplateResult {return html`${splitLinks(text).map((seg) =>seg.kind === "link"- ? html`<a href=${seg.href} target="_blank" rel="noreferrer noopener" @click=${(e: Event) => e.stopPropagation()}- >${seg.href}</a- >`+ ? html`<a href=${seg.href} target="_blank" rel="noreferrer noopener">${seg.href}</a>`: seg.text,)}`;}diff --git a/plugins/web-ui/src/deep-link.ts b/plugins/web-ui/src/deep-link.tsindex bfa28df74..13321e560 100644--- a/plugins/web-ui/src/deep-link.ts+++ b/plugins/web-ui/src/deep-link.ts@@ -1,3 +1,5 @@+import { messageLinkSeq } from "./message-link.ts";+export const UI_BASE = ((import.meta as unknown as { env?: { BASE_URL?: string } }).env?.BASE_URL ?? "/").replace(/\/$/,"",@@ -75,6 +77,25 @@ export function sessionLink(origin: string, base: string, sessionId: string, seqreturn `${origin}${deepLinkPath(base, "chats", sessionId)}${suffix}`;}+/** The session a same-app link points at (`/s/<id>`, optionally `?seq=N`), or null for anything else. */+export function sessionLinkTarget(+ href: string,+ origin: string,+ base: string,+): { session: string; seq: number | null } | null {+ let url: URL;+ try {+ url = new URL(href, origin);+ } catch {+ return null;+ }+ const b = base.replace(/\/$/, "");+ if (url.origin !== origin || (b && url.pathname !== b && !url.pathname.startsWith(`${b}/`))) return null;+ const linked = parseDeepLink(b, url.pathname, url.search);+ if (linked.view !== "chats" || !linked.session) return null;+ return { session: linked.session, seq: messageLinkSeq(url.search) };+}+/** True for an unmodified left click — the case an in-app link should handle itself (SPA nav). Modified clicks (cmd/ctrl/shift/alt, middle-click) fall through to the browser so "open in new tab" works. */export function isPlainLeftClick(e: MouseEvent): boolean {return !(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0);diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex 662de6059..90ddaaff8 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -40,6 +40,9 @@ import {TAIL_TURNS,webFetch,withBase,+ type CoreSession,+ type PendingApproval,+ type TranscriptPage,} from "./core-bridge";import { seedRuntimeConfig } from "./runtime-config-store";import { errMessage, swallow } from "../../chassis/src/errors";@@ -49,7 +52,7 @@ import { markConnectorConnected } from "./chat";import { clearSkillsCache, resyncModelSelection } from "./composer";import { allConversations, ensureDeliveryStream, mainConversation, onExitCanvas } from "./conversations";import { clearAllDrafts, newChatDraftKey, saveDraft, storedDraft } from "./drafts";-import { deepLinkPath, isPlainLeftClick, parseDeepLink, UI_BASE } from "./deep-link";+import { deepLinkPath, isPlainLeftClick, parseDeepLink, sessionLinkTarget, UI_BASE } from "./deep-link";import {adoptRemoteSplit,beginPaneKindDrag,@@ -1012,6 +1015,50 @@ export async function bootSafely(): Promise<void> {}}+async function showLinkedSession(+ linked: CoreSession,+ transcript: Promise<TranscriptPage | null>,+ seq: number | null,+ approvals?: Promise<{ approvals: PendingApproval[] } | null>,+): Promise<void> {+ if (!sessionsState.list.some((s) => s.id === linked.id)) sessionsState.list = [linked, ...sessionsState.list];+ revealSessionSurface(linked);+ await openSession(linked, transcript, approvals);+ if (seq !== null)+ requestAnimationFrame(() => {+ for (const conversation of allConversations())+ if (conversation.state.sessionId === linked.id) conversation.revealEntry(seq);+ });+}++// Session links nobody else handled (chat messages, markdown) switch the view instead of opening a new+// tab or desktop window. Modified clicks fall through, so cmd/ctrl-click still opens a new tab.+document.addEventListener("click", (e) => {+ if (!shellMounted || e.defaultPrevented || !isPlainLeftClick(e)) return;+ const anchor = e.composedPath().find((node): node is HTMLAnchorElement => node instanceof HTMLAnchorElement);+ if (!anchor?.href || anchor.hasAttribute("download")) return;+ const target = sessionLinkTarget(anchor.href, location.origin, UI_BASE);+ if (!target) return;+ e.preventDefault();+ const open = allConversations().find(+ (conversation) => conversation.state.sessionId === target.session && conversation.state.host?.isConnected,+ );+ if (open) {+ if (target.seq !== null) open.revealEntry(target.seq);+ return;+ }+ const transcript = loadMessageTranscript(+ (window) => fetchTranscript(target.session, window),+ target.seq,+ TAIL_TURNS,+ ).catch(() => null);+ void (async () => {+ const linked = sessionsState.list.find((s) => s.id === target.session) ?? (await transcript)?.session;+ if (linked) await showLinkedSession(linked, transcript, target.seq);+ else location.assign(anchor.href);+ })();+});+export async function boot(): Promise<void> {if (new URLSearchParams(location.search).get("themeOnly") === "1") return;captureConnectionReturn(location.href);@@ -1105,14 +1152,7 @@ export async function boot(): Promise<void> {const linked = (await transcript)?.session;if (linked) {exitSplitIfActive();- if (!sessionsState.list.some((s) => s.id === linked.id)) sessionsState.list = [linked, ...sessionsState.list];- revealSessionSurface(linked);- await openSession(linked, transcript, approvalsPrefetch ?? undefined);- if (wantedSeq !== null)- requestAnimationFrame(() => {- for (const conversation of allConversations())- if (conversation.state.sessionId === linked.id) conversation.revealEntry(wantedSeq);- });+ await showLinkedSession(linked, transcript, wantedSeq, approvalsPrefetch ?? undefined);return;}await sessions;diff --git a/plugins/web-ui/test/deep-link.test.ts b/plugins/web-ui/test/deep-link.test.tsindex ce9845bab..4d7e1f7c8 100644--- a/plugins/web-ui/test/deep-link.test.ts+++ b/plugins/web-ui/test/deep-link.test.ts@@ -1,6 +1,6 @@import { test } from "node:test";import assert from "node:assert/strict";-import { deepLinkPath, parseDeepLink, sessionLink } from "../src/deep-link.ts";+import { deepLinkPath, parseDeepLink, sessionLink, sessionLinkTarget } from "../src/deep-link.ts";test("chats view with an active session is addressed by /s/<id>", () => {assert.equal(deepLinkPath("", "chats", "abc-123"), "/s/abc-123");@@ -140,3 +140,21 @@ test("sent and pending email URLs use the same id route shape", () => {});}});++test("in-app session links resolve to the session and optional message seq", () => {+ const origin = "https://qm.example.com";+ assert.deepEqual(sessionLinkTarget(`${origin}/s/abc`, origin, ""), { session: "abc", seq: null });+ assert.deepEqual(sessionLinkTarget(`${origin}/s/abc?seq=12`, origin, ""), { session: "abc", seq: 12 });+ assert.deepEqual(sessionLinkTarget("/ui/s/abc", origin, "/ui"), { session: "abc", seq: null });+ assert.deepEqual(sessionLinkTarget(`${origin}/c/abc`, origin, ""), { session: "abc", seq: null });+ assert.deepEqual(sessionLinkTarget(`${origin}/s/abc?seq=abc`, origin, ""), { session: "abc", seq: null });+});++test("other links are not treated as session links", () => {+ const origin = "https://qm.example.com";+ assert.equal(sessionLinkTarget("https://elsewhere.example.com/s/abc", origin, ""), null);+ assert.equal(sessionLinkTarget(`${origin}/d/my-app/`, origin, ""), null);+ assert.equal(sessionLinkTarget(`${origin}/apps`, origin, ""), null);+ assert.equal(sessionLinkTarget(`${origin}/s/abc`, origin, "/ui"), null);+ assert.equal(sessionLinkTarget("not a url", "null", ""), null);+});diff --git a/plugins/web-ui/test/linkify.test.ts b/plugins/web-ui/test/linkify.test.tsindex b9121b8c2..931b7c473 100644--- a/plugins/web-ui/test/linkify.test.ts+++ b/plugins/web-ui/test/linkify.test.ts@@ -99,8 +99,11 @@ test("the collapsed peek is linkified and lives outside the toggle button", () =assert.match(chat, /class="pinned-strip-toggle"/);});-test("pin links stop propagation so a click follows the link instead of toggling", () => {- assert.match(chat, /@click=\$\{\(e: Event\) => e\.stopPropagation\(\)\}/);+test("clicking a pin link follows the link instead of toggling the strip", () => {+ assert.match(+ chat,+ /function togglePins\(e: Event\): void \{\s*if \(\(e\.target as Element \| null\)\?\.closest\("a"\)\) return;/,+ );});const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");