Multiplayer agent harness for work.
fix(web-ui): restore the shared desktop pane lifecycle (#1143)
Joshua Francecc35cfd49dce
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 339ec810a..bbfb60c0b 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -500,7 +500,6 @@ export function createChatSurface(scopeId: string | null,messages: ReturnType<typeof entriesToMessages>,): boolean {- if (ctx.pane) return false;if (proactiveOpenerStarted || sessionId !== null || scopeId !== null || messages.length > 0) return false;if (!sessionsState.loaded) return false;if (sessionsState.list.some((s) => s.id)) return false;diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.tsindex db1d3fcb5..3bb5b8918 100644--- a/plugins/web-ui/src/sessions.ts+++ b/plugins/web-ui/src/sessions.ts@@ -89,6 +89,9 @@ import { allConversations, isLiveConversation, mainConversation } from "./converimport type { Conversation } from "./conv-types";import {startNewChatInCanvas,+ mountRestoredCanvas,+ focusedPaneConversation,+ openBackgroundInCanvas,beginSessionDrag,endPaneDrag,notifyPanesChanged,@@ -462,7 +465,8 @@ export function startNewChat(): Conversation | null {closeSidebarOnNarrowView();if (scopeId) sessionsState.collapsedProjectScopes.delete(scopeId);- if (splitState.active) return startNewChatInCanvas(scopeId ?? undefined, threadRef);+ const pane = startNewChatInCanvas(scopeId ?? undefined, threadRef);+ if (pane) return pane;const conv = mainConversation();if (threadRef) conv.mountContinuable(threadRef, null, scopeId, [], name);else addPendingSession(conv.newChat(scopeId ? { scopeId, name } : undefined), scopeId, name);@@ -470,7 +474,7 @@ export function startNewChat(}export function startNewChatInLastScope(): void {- const mounted = mainConversation().state;+ const mounted = (focusedPaneConversation() ?? mainConversation()).state;const scopeId = mounted.scopeId ?? visibleSessions().find((s) => !s.archived)?.scopeId ?? null;startNewChat(scopeId, scopeId ? projectName(scopeId) : null);}@@ -688,6 +692,7 @@ function statusMarks(s: CoreSession): TemplateResult {function openBackgroundInspector(e: Event, s: CoreSession): void {e.stopPropagation();e.preventDefault();+ if (openBackgroundInCanvas(s)) return;mainConversation().requestBackgroundPanel(s.id || null, s.threadRef);void openSession(s);}@@ -1535,10 +1540,11 @@ export async function openSession(if (splitState.active) drawCanvas();syncUrlFromState(s.id || null);}- if (splitInterceptsOpen(s)) return;+ mountRestoredCanvas();+ const pane = splitInterceptsOpen(s);closeSidebarOnNarrowView();if (projectName(s.scopeId) && sessionsState.collapsedProjectScopes.delete(s.scopeId)) renderList();- return openSessionInto(mainConversation(), s, entriesPrefetch, approvalsPrefetch);+ return openSessionInto(pane ?? mainConversation(), s, entriesPrefetch, approvalsPrefetch, true);}export async function openSessionInto(@@ -1546,8 +1552,8 @@ export async function openSessionInto(s: CoreSession,entriesPrefetch?: Promise<TranscriptPage | null>,approvalsPrefetch?: Promise<{ approvals: PendingApproval[] } | null>,+ tracked = conv === mainConversation(),): Promise<void> {- const tracked = conv === mainConversation();if (!s.id) {if (conv.state.threadRef !== s.threadRef) {conv.mountContinuable(s.threadRef, null, s.scopeId || null, [], s.channelName ?? null);diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 6f94b1179..a53a01a70 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -7176,18 +7176,12 @@ h3.ambient-field-label {pointer-events: none;}-.split-zones-single {- position: absolute;- inset: 0;- z-index: 30;-}-.split-zone {position: absolute;display: flex;align-items: center;justify-content: center;- margin: 4px;+ margin: 0;border: 2px dashed color-mix(in srgb, var(--primary) 55%, var(--border));border-radius: var(--radius-md);background: color-mix(in srgb, var(--primary) 6%, transparent);@@ -7239,37 +7233,43 @@ h3.ambient-field-label {left: 25%;right: 25%;top: 0;- height: 24%;+ height: 25%;}.zone-bottom {left: 25%;right: 25%;bottom: 0;- height: 24%;+ height: 25%;}.zone-left {left: 0;top: 0;bottom: 0;- width: 24%;+ width: 25%;}.zone-right {right: 0;top: 0;bottom: 0;- width: 24%;+ width: 25%;}/* Joining a tab strip is offered on the strip itself now, so the inner box is one targetagain — the whole of it replaces what the pane is showing. */.zone-center {- left: 26%;- right: 26%;- top: 26%;- bottom: 26%;+ left: 25%;+ right: 25%;+ top: 25%;+ bottom: 25%;+}++.split-zones > .split-zone:only-child {+ inset: 0;+ width: auto;+ height: auto;}.split-toast {diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex 8295cd2f6..43c5851e0 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -685,7 +685,7 @@ export function switchView(v: View): void {resetActiveDetail(v);switch (v) {case "chats":- if (splitState.active) drawCanvas();+ if (mountRestoredCanvas()) drawCanvas();else void renderChatsPage();renderList();break;@@ -1014,7 +1014,7 @@ export async function boot(): Promise<void> {const viewIntent = isView(wanted) && canView(wanted) && wanted !== "chats";const bareEntry = !viewIntent && !wantedSession && wanted !== "app-edit" && !connectedProvider;- if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas();+ if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas(true);const sessions = refreshSessions({ showLoading: true });diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.tsindex 27219b53e..84144ced3 100644--- a/plugins/web-ui/src/split.ts+++ b/plugins/web-ui/src/split.ts@@ -66,7 +66,6 @@ import {openSession,openSessionInto,refreshSessions,- refreshSessionsOnOpen,sessionsReady,renderList,sessionsState,@@ -104,8 +103,6 @@ interface PaneParams {interface PaneDrag {params: PaneParams;existing(): IDockviewPanel | null;- openFull(): void;- splittableSingle(): boolean;}type PendingSeed = { kind: "v2"; layout: SerializedDockview } | { kind: "v1"; seeds: PaneSeed[] };@@ -120,7 +117,6 @@ const paneTabs = new Set<PaneTab>();const groupActions = new Set<GroupActions>();const stripDrops = new Set<StripDrop>();let paneDrag: PaneDrag | null = null;-let singleOverlay: HTMLElement | null = null;let toastMsg = "";let toastTimer: number | null = null;let headerSignature = "";@@ -274,7 +270,10 @@ function disposeDock(): void {function ensureCanvas(): boolean {if (!appState.mainEl) return false;- if (canvasHost && canvasHost.parentElement === appState.mainEl && dockApi) return true;+ if (canvasHost && dockApi) {+ if (canvasHost.parentElement !== appState.mainEl) appState.mainEl.replaceChildren(canvasHost);+ return true;+ }disposeDock();canvasHost = document.createElement("div");canvasHost.className = "split-canvas";@@ -345,23 +344,6 @@ function seedFromV1(api: DockviewApi, seeds: PaneSeed[]): void {persist();}-export function activateCanvas(first: PaneParams, second: PaneParams, edge: SplitEdge): void {- if (isPhone()) return;- mainConversation().teardown();- mainConversation().composer.resetComposer();- splitState.active = true;- lastLayout = null;- pendingSeed = null;- if (!ensureCanvas()) return;- const anchor = addPane(first);- const fresh = addPane(second, { referencePanel: anchor.id, direction: edgeToDirection(edge) });- fresh.api.setActive();- persist();- renderSidebarTop();- syncUrlFromState();- renderList();-}-function edgeToDirection(edge: SplitEdge): "left" | "right" | "above" | "below" {if (edge === "top") return "above";if (edge === "bottom") return "below";@@ -439,7 +421,7 @@ function adoptPersisted(raw: unknown): void {if (o.active !== true || !o.layout || typeof o.layout !== "object") return;const panels = (o.layout as { panels?: object }).panels;const n = panels && typeof panels === "object" ? Object.keys(panels).length : 0;- if (n < 2 || n > MAX_PANES || serializedTileCount(o.layout) > MAX_TILES) return;+ if (n < 1 || n > MAX_PANES || serializedTileCount(o.layout) > MAX_TILES) return;pendingSeed = { kind: "v2", layout: o.layout as SerializedDockview };splitState.active = true;return;@@ -487,17 +469,11 @@ export function restoredCanvasNeedsSessionList(): boolean {return layoutNeedsSessionList(pendingSeed.layout);}-export function mountRestoredCanvas(): boolean {- if (splitState.active && (dockApi?.panels.length ?? 0) > 0) return true;- if (!splitState.active || (!pendingSeed && !lastLayout)) return false;- if (!ensureCanvas()) {- splitState.active = false;- return false;- }- if ((dockApi?.panels.length ?? 0) === 0) {- exitSplitIfActive();- return false;- }+export function mountRestoredCanvas(restoreOnly = false): boolean {+ if (isPhone() || (restoreOnly && !splitState.active)) return false;+ splitState.active = true;+ if (!ensureCanvas() || !dockApi) return false;+ if (dockApi.panels.length === 0) addPane({});renderSidebarTop();renderList();return true;@@ -532,13 +508,15 @@ export function closeSessionSurfaces(sessionId: string): boolean {return true;}-export function splitInterceptsOpen(s: CoreSession): boolean {- if (!splitState.active || appState.currentView !== "chats" || !s.id) return false;+export function splitInterceptsOpen(s: CoreSession): Conversation | null {+ if (!splitState.active || appState.currentView !== "chats") return null;const target = splitState.focusedId ?? dockApi?.panels[0]?.id ?? "";- openTargetInPane(target, sessionTarget(s.id, s.threadRef));+ const panel = openTargetInPane(target, {+ ...sessionTarget(s.id, s.threadRef),+ params: { scopeId: s.scopeId },+ });renderList();- refreshSessionsOnOpen();- return true;+ return panel ? (paneContents.get(panel.id)?.conversation ?? null) : null;}export function openBackgroundInCanvas(s: CoreSession): boolean {@@ -561,7 +539,13 @@ export function openBackgroundInCanvas(s: CoreSession): boolean {}function sessionTarget(sessionId: string, threadRef: string): Pick<PaneDrag, "params" | "existing"> {- return { params: { sessionId, threadRef }, existing: () => paneShowing(sessionId) };+ return {+ params: sessionId ? { sessionId, threadRef } : { threadRef },+ existing: () =>+ sessionId+ ? paneShowing(sessionId)+ : (dockApi?.panels.find((p) => panelParams(p).threadRef === threadRef) ?? null),+ };}function focusExistingPane(existing: () => IDockviewPanel | null, exceptPaneId?: string): boolean {@@ -574,14 +558,20 @@ function focusExistingPane(existing: () => IDockviewPanel | null, exceptPaneId?:return true;}-function openTargetInPane(paneId: string, target: Pick<PaneDrag, "params" | "existing">): void {- if (!dockApi || focusExistingPane(target.existing, paneId)) return;+function openTargetInPane(paneId: string, target: Pick<PaneDrag, "params" | "existing">): IDockviewPanel | null {+ if (!dockApi) return null;+ const showing = target.existing();+ if (showing) {+ focusExistingPane(target.existing, paneId);+ return showing;+ }const panel = dockApi.getPanel(paneId);- if (!panel) return;+ if (!panel) return null;const fresh = addPane(target.params, { referencePanel: panel.id, direction: "within" });dockApi.removePanel(panel);fresh.api.setActive();persist();+ return fresh;}function roomForAnotherPane(): boolean {@@ -614,7 +604,7 @@ function tabIntoPane(paneId: string, params: PaneParams, index?: number): boolea}export function startNewChatInCanvas(scopeId?: string, threadRef?: string): Conversation | null {- if (!splitState.active || !dockApi) return null;+ if (!mountRestoredCanvas() || !dockApi) return null;if (appState.currentView !== "chats") switchView("chats");if (!ensureCanvas() || !dockApi) return null;const target = dockApi.activePanel ?? dockApi.panels[0];@@ -647,54 +637,11 @@ function closePanels(panels: IDockviewPanel[]): void {}function reconcileAfterClose(): void {- const rest = dockApi?.panels ?? [];- if (rest.length === 0) {- exitSplitIfActive();- mainConversation().newChat();- return;- }- if (rest.length === 1) {- const lone = rest[0]!;- const params = panelParams(lone);- if (params.sessionId || paneKindEntry(params)) {- void maximizePane(params);- } else {- exitSplitIfActive();- mainConversation().newChat();- }- return;- }+ if (!dockApi) return;+ if (dockApi.panels.length === 0) addPane({});persist();}-async function maximizePane(params: PaneParams): Promise<void> {- const entry = paneKindEntry(params);- if (entry) {- entry.kind.maximize(entry.id);- return;- }- if (!params.sessionId) {- canvasToast("Start the chat first, then open it full screen");- return;- }- const find = (): CoreSession | undefined => sessionsState.list.find((s) => s.id === params.sessionId);- let session = find();- if (!session) {- try {- await refreshSessions({ silent: true });- } catch {- void 0;- }- session = find();- if (!session) {- canvasToast("Still syncing this conversation. Try again in a moment");- return;- }- }- exitSplitIfActive();- void openSession(session);-}-function activatePanel(panel: IDockviewPanel): void {if (panel.group.activePanel === panel) panel.group.api.setActive();else panel.api.setActive();@@ -725,14 +672,7 @@ function drawToast(): void {export function beginSessionDrag(s: CoreSession): void {if (!s.id) return;const sessionId = s.id;- beginPaneDrag({- ...sessionTarget(sessionId, s.threadRef),- openFull: () => {- const session = sessionsState.list.find((x) => x.id === sessionId);- if (session) void openSession(session);- },- splittableSingle: () => mainConversation().state.sessionId !== sessionId,- });+ beginPaneDrag(sessionTarget(sessionId, s.threadRef));}export function beginPaneKindDrag(paramsKey: string, id: string): void {@@ -741,15 +681,12 @@ export function beginPaneKindDrag(paramsKey: string, id: string): void {beginPaneDrag({params: { [kind.paramsKey]: id },existing: () => dockApi?.panels.find((p) => panelParams(p)[kind.paramsKey] === id) ?? null,- openFull: () => kind.maximize(id),- splittableSingle: () => true,});}function beginPaneDrag(drag: PaneDrag): void {paneDrag = drag;if (splitState.active) refreshPaneDrag();- else showSingleDropOverlay();}function refreshPaneDrag(): void {@@ -773,7 +710,6 @@ function drawStripDrops(): void {export function endPaneDrag(): void {if (!paneDrag) return;paneDrag = null;- hideSingleDropOverlay();canvasHost?.classList.remove("session-dragging");drawStripDrops();if (splitState.active) syncAllZones();@@ -810,10 +746,6 @@ function splitZonesTpl(act: (edge: DropEdge) => () => void): TemplateResult {`;}-function zonesTpl(act: (edge: DropEdge) => () => void): TemplateResult {- return html`${zoneTpl("center", "Open here", act("center"))} ${splitZonesTpl(act)}`;-}-function paneZonesTpl(paneId: string): TemplateResult | typeof nothing {const drag = paneDrag;if (!dockApi || !drag) return nothing;@@ -827,7 +759,7 @@ function paneZonesTpl(paneId: string): TemplateResult | typeof nothing {: nothing;const act = paneZoneAct(paneId);const canSplit = dockApi.panels.length < MAX_PANES && dockApi.groups.length < MAX_TILES;- return html`${zoneTpl("center", "Open here", act("center"))} ${canSplit ? splitZonesTpl(act) : nothing}`;+ return html`${zoneTpl("center", "Replace pane", act("center"))} ${canSplit ? splitZonesTpl(act) : nothing}`;}function paneZoneAct(paneId: string): (edge: DropEdge) => () => void {@@ -844,42 +776,6 @@ function paneZoneAct(paneId: string): (edge: DropEdge) => () => void {};}-function currentChatParams(): PaneParams | null {- const conv = mainConversation();- const chatState = conv.state;- if (!chatState.host) return null;- if (chatState.sessionId)- return { sessionId: chatState.sessionId, ...(chatState.threadRef ? { threadRef: chatState.threadRef } : {}) };- const untouched =- !chatState.pendingSend && !conv.composer.state.draft.trim() && (chatState.agent?.state.messages.length ?? 0) === 0;- return untouched ? {} : null;-}--function showSingleDropOverlay(): void {- if (splitState.active || appState.currentView !== "chats" || !appState.mainEl || singleOverlay) return;- const drag = paneDrag;- if (!drag) return;- const act = (edge: DropEdge) => () => {- endPaneDrag();- const current = edge === "center" ? null : currentChatParams();- if (edge === "center" || !current || !drag.splittableSingle()) {- drag.openFull();- return;- }- activateCanvas(current, drag.params, edge);- };- const splittable = drag.splittableSingle() && currentChatParams() !== null;- singleOverlay = document.createElement("div");- singleOverlay.className = "split-zones split-zones-single";- render(splittable ? zonesTpl(act) : zoneTpl("center", "Open here", act("center")), singleOverlay);- appState.mainEl.appendChild(singleOverlay);-}--function hideSingleDropOverlay(): void {- singleOverlay?.remove();- singleOverlay = null;-}-export function drawCanvas(): void {if (!splitState.active || appState.currentView !== "chats" || !appState.mainEl) return;if (!ensureCanvas()) return;@@ -914,6 +810,11 @@ function paneSession(panel: IDockviewPanel): CoreSession | undefined {return sessionId ? sessionsState.list.find((s) => s.id === sessionId) : undefined;}+export function focusedPaneConversation(): Conversation | null {+ if (!splitState.active) return null;+ return paneContents.get(splitState.focusedId ?? "")?.conversation ?? null;+}+export function focusedPaneSession(): CoreSession | undefined {if (!splitState.active || !dockApi) return undefined;const panel = (splitState.focusedId && dockApi.getPanel(splitState.focusedId)) || dockApi.activePanel;@@ -1435,7 +1336,9 @@ class GroupActions implements IHeaderActionsRenderer {glyph: icon(Maximize2, 14),run: () => {const p = activePanel();- if (p) void maximizePane(panelParams(p));+ if (!p) return;+ if (p.api.isMaximized()) p.api.exitMaximized();+ else p.api.maximize();},},{@@ -1505,7 +1408,7 @@ function notePaneSession(paneId: string, sessionId: string | null, threadRef: stasync function settlePaneTitle(sessionId: string): Promise<void> {const titled = (): boolean => Boolean(sessionsState.list.find((s) => s.id === sessionId)?.title?.trim());- await settlePoll([0, 1200, 2400, 4000, 6000], titled);+ if (!titled()) await settlePoll([0, 1200, 2400, 4000, 6000], titled);}async function settlePoll(delays: number[], done: () => boolean): Promise<void> {diff --git a/plugins/web-ui/test/deep-link-boot.test.ts b/plugins/web-ui/test/deep-link-boot.test.tsindex f8fcec955..288cdd0c7 100644--- a/plugins/web-ui/test/deep-link-boot.test.ts+++ b/plugins/web-ui/test/deep-link-boot.test.ts@@ -12,7 +12,7 @@ interface Harness {boot: () => Promise<void>;appState: { currentView: string };sessionsState: { list: Array<{ id: string }>; loaded: boolean; openingKey: string | null };- mainConversation: () => { state: { sessionId: string | null; threadRef: string | null } };+ visibleConversation: () => { state: { sessionId: string | null; threadRef: string | null } };mainText: () => string;close: () => Promise<void>;}@@ -149,7 +149,11 @@ async function harness(opts: HarnessOptions): Promise<Harness> {boot: shell.boot as () => Promise<void>,appState: shell.appState as Harness["appState"],sessionsState: sessions.sessionsState as Harness["sessionsState"],- mainConversation: conversations.mainConversation as Harness["mainConversation"],+ visibleConversation: () =>+ conversations+ .allConversations()+ .find((conv: { state: { host: HTMLElement | null } }) => conv.state.host?.isConnected) ??+ conversations.mainConversation(),mainText: () => dom.window.document.querySelector(".main")?.textContent ?? "",close: async () => {releaseSessions();@@ -175,7 +179,7 @@ test("a share link paints its conversation from the transcript, without waitingtry {await h.boot();assert.equal(h.sessionsState.loaded, false, "the sidebar list must still be in flight");- assert.equal(h.mainConversation().state.sessionId, SESSION.id, "the linked chat is already mounted");+ assert.equal(h.visibleConversation().state.sessionId, SESSION.id, "the linked chat is already mounted");assert.deepEqual(h.sessionsState.list.map((s) => s.id),[SESSION.id],@@ -187,6 +191,11 @@ test("a share link paints its conversation from the transcript, without waiting1,"boot must not stampede the expensive list route",);+ assert.equal(+ h.requests.filter((p) => p === `/api/sessions/${SESSION.id}?tailTurns=25`).length,+ 1,+ "the pane reuses the prefetched transcript",+ );const transcript = h.requests.indexOf(`/api/sessions/${SESSION.id}?tailTurns=25`);assert.ok(transcript >= 0, "the transcript is fetched with the tail window");assert.ok(transcript < h.requests.indexOf("/me"), "and is in flight before /me is even asked");@@ -209,7 +218,7 @@ test("a share link whose transcript 404s falls back to the session list", asynch.releaseSessions();await booted;assert.equal(h.sessionsState.loaded, true, "the fallback waits for the list");- assert.equal(h.mainConversation().state.sessionId, null, "no conversation is mounted");+ assert.equal(h.visibleConversation().state.sessionId, null, "no conversation is mounted");assert.match(h.mainText(), /wasn't found, or you don't have access to it/);} finally {await h.close();@@ -227,7 +236,7 @@ test("a share link whose transcript fetch flakes still opens from the session liconst booted = h.boot();h.releaseSessions();await booted;- assert.equal(h.mainConversation().state.sessionId, SESSION.id);+ assert.equal(h.visibleConversation().state.sessionId, SESSION.id);} finally {await h.close();}@@ -253,7 +262,7 @@ test("a session list that wins the race keeps its own decorated rows", async ()true,"…nor strip the decorations only the list route computes",);- assert.equal(h.mainConversation().state.sessionId, SESSION.id);+ assert.equal(h.visibleConversation().state.sessionId, SESSION.id);} finally {await h.close();}@@ -266,7 +275,7 @@ test("a list that omits the open conversation does not drop its row", async () =await h.boot();h.releaseSessions();await h.sessionsReady();- assert.equal(h.mainConversation().state.sessionId, SESSION.id);+ assert.equal(h.visibleConversation().state.sessionId, SESSION.id);assert.ok(h.sessionsState.list.some((s) => s.id === SESSION.id),"the conversation the user is reading must keep its sidebar row",@@ -303,8 +312,8 @@ test("a bare entry still mints a new chat once the list lands", async () => {await booted;assert.equal(h.sessionsState.loaded, true);assert.equal(h.appState.currentView, "chats");- assert.equal(h.mainConversation().state.sessionId, null);- assert.ok(h.mainConversation().state.threadRef, "a fresh chat is mounted");+ assert.equal(h.visibleConversation().state.sessionId, null);+ assert.ok(h.visibleConversation().state.threadRef, "a fresh chat is mounted");} finally {await h.close();}diff --git a/plugins/web-ui/test/document-title.test.ts b/plugins/web-ui/test/document-title.test.tsindex f1a8b481a..a74bece14 100644--- a/plugins/web-ui/test/document-title.test.ts+++ b/plugins/web-ui/test/document-title.test.ts@@ -80,8 +80,8 @@ test("document title follows session switches, split-pane focus, and sign-out",try {const { appState, signOut, syncDocumentTitle } = await vite.ssrLoadModule("/src/shell.ts");const { mainConversation } = await vite.ssrLoadModule("/src/conversations.ts");- const { refreshSessions, sessionsState } = await vite.ssrLoadModule("/src/sessions.ts");- const { activateCanvas } = await vite.ssrLoadModule("/src/split.ts");+ const { openSession, refreshSessions, sessionsState } = await vite.ssrLoadModule("/src/sessions.ts");+ const { mountRestoredCanvas, beginSessionDrag } = await vite.ssrLoadModule("/src/split.ts");const oldSession = { id: "old", threadRef: "web:old", scopeId: "personal:tester", title: "Old title" };const newSession = { id: "new", threadRef: "web:new", scopeId: "personal:tester", title: "New title" };sessionsState.list = [oldSession, newSession];@@ -99,7 +99,26 @@ test("document title follows session switches, split-pane focus, and sign-out",syncDocumentTitle();assert.equal(document.title, `New title · ${PRODUCT_TITLE}`);- activateCanvas({ sessionId: "old", threadRef: "web:old" }, { sessionId: "new", threadRef: "web:new" }, "right");+ globalThis.fetch = async (input) => {+ const session = String(input).includes("/sessions/new") ? newSession : oldSession;+ return Response.json({+ scopeId: "personal:tester",+ approvedHarnesses: [],+ modelsByHarness: {},+ modelCatalog: {},+ effective: { harnessId: "pi", modelId: "" },+ session,+ entries: [],+ sessions: sessionsState.list,+ contexts: [],+ });+ };+ mountRestoredCanvas();+ await openSession(oldSession);+ beginSessionDrag(newSession);+ document+ .querySelector(".zone-right")!+ .dispatchEvent(new dom.window.Event("drop", { bubbles: true, cancelable: true }));assert.equal(document.title, `New title · ${PRODUCT_TITLE}`);await new Promise((resolve) => setTimeout(resolve, 0));diff --git a/plugins/web-ui/test/new-chat-placement.test.ts b/plugins/web-ui/test/new-chat-placement.test.tsindex 5f8a1bf98..3491d005c 100644--- a/plugins/web-ui/test/new-chat-placement.test.ts+++ b/plugins/web-ui/test/new-chat-placement.test.ts@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import test from "node:test";import { JSDOM } from "jsdom";import { createServer } from "vite";+import type { Conversation } from "../src/conv-types.ts";interface Canvas {panes: () => number;@@ -10,12 +11,17 @@ interface Canvas {tabCounts: () => number[];focusTile: (index: number) => void;splitTile: (index: number) => void;- seededChat: (threadRef?: string) => { state: { threadRef: string | null; agent: unknown } } | null;+ seededChat: (threadRef?: string) => Conversation | null;+ drag: () => void;+ closeTile: (index: number) => void;split: () => void;switchAway: () => void;}-async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stacked = false): Promise<void> {+async function withCanvas(+ run: (canvas: Canvas) => void | Promise<void>,+ stacked: boolean | "single" = false,+): Promise<void> {const dom = new JSDOM('<!doctype html><div id="app"></div>', { url: "http://localhost/web-ui/" });const globals = {window: dom.window,@@ -69,8 +75,8 @@ async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stackedappState.currentView = "chats";appState.mainEl = document.createElement("main");document.body.append(appState.mainEl);- assert.ok(sessions.startNewChat());if (stacked) {+ const ids = stacked === "single" ? ["a"] : ["a", "b"];localStorage.setItem("web-ui:split-canvas:v1",JSON.stringify({@@ -84,7 +90,7 @@ async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stacked{type: "leaf",data: {- views: ["a", "b"],+ views: ids,activeView: "a",id: "stack",},@@ -96,7 +102,7 @@ async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stackedorientation: "HORIZONTAL",},panels: Object.fromEntries(- ["a", "b"].map((id) => [+ ids.map((id) => [id,{id,@@ -114,6 +120,7 @@ async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stackedsplit.loadPersistedSplit();assert.equal(split.mountRestoredCanvas(), true);}+ if (!stacked) assert.ok(sessions.startNewChat());await run({panes: () => document.querySelectorAll(".dv-tab").length,tabCounts: () =>@@ -135,7 +142,15 @@ async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stackedtiles: () => document.querySelectorAll(".dv-groupview").length,newChat: () => sessions.startNewChat() !== null,seededChat: (threadRef) => sessions.startNewChat(null, null, threadRef),- split: () => split.activateCanvas({}, {}, "right"),+ split: () =>+ document.querySelector<HTMLButtonElement>('[aria-label="Split this pane with a new session"]')!.click(),+ drag: () => split.beginSessionDrag({ id: "second", threadRef: "web:tester:second" }),+ closeTile: (index) =>+ document+ .querySelectorAll(".dv-groupview")+ .item(index)!+ .querySelector<HTMLButtonElement>('[aria-label="Close pane"]')!+ .click(),switchAway: () => {appState.currentView = "crons";appState.mainEl.replaceChildren();@@ -154,10 +169,10 @@ async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stackedtest("New chat stops splitting after three tiles and adds tabs to the selected pane", async () => {await withCanvas((canvas) => {- assert.deepEqual([canvas.panes(), canvas.tiles()], [0, 0]);+ assert.deepEqual([canvas.panes(), canvas.tiles()], [1, 1]);assert.equal(canvas.newChat(), true);- assert.deepEqual([canvas.panes(), canvas.tiles()], [0, 0], "one session: New chat replaces it");+ assert.deepEqual([canvas.panes(), canvas.tiles()], [1, 1], "one session: New chat replaces it");canvas.split();assert.deepEqual([canvas.panes(), canvas.tiles()], [2, 2]);@@ -187,7 +202,7 @@ test("a seeded New chat hands back the conversation in the pane it just placed",assert.ok(first, "the canvas must return a live conversation to seed");assert.ok(first.state.threadRef, "…already mounted on its own new thread");assert.ok(first.state.agent, "…with an agent a caller can prompt");- assert.deepEqual([canvas.panes(), canvas.tiles()], [0, 0], "one session: it replaces that pane");+ assert.deepEqual([canvas.panes(), canvas.tiles()], [1, 1], "one session: it replaces that pane");canvas.split();const second = canvas.seededChat();@@ -226,3 +241,52 @@ test("a restored tab-only arrangement gains a tab, not a tile", async () => {assert.deepEqual([canvas.panes(), canvas.tiles()], [3, 1]);}, true);});++test("a drafted first pane survives splitting and closing its neighbor", async () => {+ await withCanvas((canvas) => {+ const first = canvas.seededChat()!;+ first.composer.state.draft = "Keep this unsent draft";+ const host = first.state.host;+ const agent = first.state.agent;+ const thread = first.state.threadRef;+ canvas.drag();+ assert.equal(document.querySelectorAll(".split-zone.zone-right").length, 1);+ canvas.split();+ assert.deepEqual([canvas.panes(), canvas.tiles()], [2, 2]);+ assert.equal(first.state.host, host);+ assert.equal(first.state.agent, agent);+ assert.equal(first.state.threadRef, thread);+ assert.equal(first.composer.state.draft, "Keep this unsent draft");+ canvas.closeTile(1);+ assert.deepEqual([canvas.panes(), canvas.tiles()], [1, 1]);+ assert.ok(host?.isConnected);+ assert.equal(first.state.agent, agent);+ assert.equal(first.composer.state.draft, "Keep this unsent draft");+ canvas.closeTile(0);+ assert.deepEqual([canvas.panes(), canvas.tiles()], [1, 1], "closing the last pane leaves a new chat");+ });+});++test("a saved one-pane layout restores as a splittable canvas", async () => {+ await withCanvas((canvas) => {+ assert.deepEqual([canvas.panes(), canvas.tiles()], [1, 1]);+ canvas.split();+ assert.deepEqual([canvas.panes(), canvas.tiles()], [2, 2]);+ }, "single");+});++test("splitting does not dispose a first turn waiting for its session ID", async () => {+ await withCanvas((canvas) => {+ const first = canvas.seededChat()!;+ first.state.pendingSend = "pending-test-send";+ const agent = first.state.agent!;+ canvas.drag();+ assert.ok(document.querySelector(".zone-right"));+ canvas.split();+ canvas.closeTile(1);+ assert.deepEqual([canvas.panes(), canvas.tiles()], [1, 1]);+ assert.equal(first.state.agent, agent);+ assert.equal(first.state.pendingSend, "pending-test-send");+ first.state.pendingSend = null;+ });+});diff --git a/plugins/web-ui/test/split-canvas-entry.test.ts b/plugins/web-ui/test/split-canvas-entry.test.tsindex 9644d245c..3ec408d80 100644--- a/plugins/web-ui/test/split-canvas-entry.test.ts+++ b/plugins/web-ui/test/split-canvas-entry.test.ts@@ -24,7 +24,7 @@ test("every new-chat affordance follows the shared placement rule", () => {assert.match(placed, /dockApi\.removePanel\(target\)/);assert.match(placed, /dockApi\.groups\.length === 2/);const start = fn(sessions, "startNewChat");- assert.match(start, /if \(splitState\.active\) return startNewChatInCanvas/);+ assert.match(start, /const pane = startNewChatInCanvas/);assert.match(start, /addPendingSession\(conv\.newChat/);assert.match(shell, /startNewChatInLastScope\(\);/);assert.match(fn(sessions, "startProjectChat"), /startNewChat\(scopeId, name\);/);@@ -95,14 +95,14 @@ test("a strip drop lands where a dragged pane header would, not merely at the entest("the pane body no longer offers a tab zone", () => {assert.doesNotMatch(layout, /"tab"/, "DropEdge must drop the zone that no longer exists");- const zones = fn(split, "zonesTpl") + fn(split, "splitZonesTpl");+ const zones = fn(split, "paneZonesTpl") + fn(split, "splitZonesTpl");assert.doesNotMatch(zones, /"tab"/);- assert.match(zones, /zoneTpl\("center", "Open here"/);+ assert.match(zones, /zoneTpl\("center", "Replace pane"/);for (const edge of ["left", "right", "top", "bottom"]) assert.match(zones, new RegExp(`zoneTpl\\("${edge}"`));assert.doesNotMatch(css, /\.zone-tab \{/);const center = css.match(/\.zone-center \{[^}]*\}/)?.[0] ?? "";- assert.match(center, /top: 26%;/);- assert.match(center, /bottom: 26%;/);+ assert.match(center, /top: 25%;/);+ assert.match(center, /bottom: 25%;/);assert.doesNotMatch(css, /\.split-zones-single \.zone-center/, "with one zone layout the exception is dead");});@@ -117,7 +117,7 @@ test("the tile cap only judges dockview's own panel drags", () => {test("boot mounts a restored canvas before it awaits the session list", () => {const boot = shell.match(/export async function boot\(\): Promise<void> \{[\s\S]*?\n\}/)?.[0] ?? "";assert.ok(boot, "boot not found");- const early = boot.indexOf("if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas();");+ const early = boot.indexOf("if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas(true);");const listStart = boot.indexOf("const sessions = refreshSessions({ showLoading: true });");const listAwait = boot.lastIndexOf("await sessions;");assert.ok(early > 0, "boot must offer the canvas its head start");@@ -131,7 +131,8 @@ test("boot mounts a restored canvas before it awaits the session list", () => {/\} else if \(!mountRestoredCanvas\(\) && !mainConversation\(\)\.state\.threadRef\) \{/,);const mount = fn(split, "mountRestoredCanvas");- assert.match(mount, /^ {2}if \(splitState\.active && \(dockApi\?\.panels\.length \?\? 0\) > 0\) return true;/m);+ assert.match(mount, /if \(isPhone\(\) \|\| \(restoreOnly && !splitState\.active\)\) return false;/);+ assert.match(mount, /if \(dockApi\.panels\.length === 0\) addPane\(\{\}\);/);});test("boot's fallback never replaces a chat the user mounted during the wait", () => {@@ -147,12 +148,8 @@ test("boot's fallback never replaces a chat the user mounted during the wait", (assert.match(fn(chat, "mountContinuable"), /chatState\.threadRef = threadRef;/);const reconcile = fn(split, "reconcileAfterClose");- assert.match(- reconcile,- /exitSplitIfActive\(\);\s*\n\s*mainConversation\(\)\.newChat\(\);/,- "a blank lone survivor mounts a new chat",- );- assert.match(reconcile, /void maximizePane\(params\);/, "a lone survivor with a session is maximized");+ assert.match(reconcile, /if \(dockApi\.panels\.length === 0\) addPane\(\{\}\);/);+ assert.doesNotMatch(reconcile, /exitSplitIfActive|maximizePane|mainConversation/);assert.match(fn(split, "exitSplitIfActive"), /splitState\.active = false;/);});diff --git a/plugins/web-ui/test/split-drop-legitimacy.test.ts b/plugins/web-ui/test/split-drop-legitimacy.test.tsindex 27bf58d41..2b0d226b9 100644--- a/plugins/web-ui/test/split-drop-legitimacy.test.ts+++ b/plugins/web-ui/test/split-drop-legitimacy.test.ts@@ -41,23 +41,9 @@ test("targets and highlights stay honest when the layout changes mid-drag", () =);});-test("the single-view overlay hides splits the drop cannot honor", () => {- const single = split.match(/^function showSingleDropOverlay\([\s\S]*?\n\}/m)?.[0] ?? "";- assert.ok(single, "showSingleDropOverlay not found");- assert.match(- single,- /currentChatParams\(\) !== null/,- "a dirty unsaved chat cannot seed a pane, so no split targets",- );- assert.match(single, /drag\.splittableSingle\(\)/, "a drag that cannot split falls back to opening full");- assert.match(single, /splittable \? zonesTpl\(act\) : zoneTpl\("center", "Open here", act\("center"\)\)/);- const sessionDrag = split.match(/^export function beginSessionDrag\([\s\S]*?\n\}/m)?.[0] ?? "";- assert.ok(sessionDrag, "beginSessionDrag not found");- assert.match(- sessionDrag,- /splittableSingle: \(\) => mainConversation\(\)\.state\.sessionId !== sessionId/,- "dropping the chat onto itself cannot split",- );+test("single-pane chats share the canvas drag path", () => {+ assert.doesNotMatch(split, /showSingleDropOverlay|currentChatParams|splittableSingle/);+ assert.match(split, /beginPaneDrag\(sessionTarget\(sessionId, s\.threadRef\)\);/);});test("every pane kind shares one legitimacy path", () => {@@ -88,3 +74,12 @@ test("the highlighted strip is a real drop target, not just a glow", () => {assert.match(end, /drawStripDrops\(\)/, "zones vanish when the drag ends");assert.match(css, /\.strip-zones \{/, "the overlay is styled");});++test("drop regions tile the content without pointer-dead margins", () => {+ const zone = css.match(/\.split-zone \{[^}]*\}/)?.[0] ?? "";+ assert.match(zone, /margin: 0;/);+ for (const edge of ["left", "right"]) {+ assert.match(css.match(new RegExp(`\\.zone-${edge} \\{[^}]*\\}`))?.[0] ?? "", /width: 25%;/);+ }+ assert.match(css, /\.split-zones > \.split-zone:only-child \{/);+});diff --git a/plugins/web-ui/test/split-tiles-and-titles.test.ts b/plugins/web-ui/test/split-tiles-and-titles.test.tsindex e25ed4326..20820cdf0 100644--- a/plugins/web-ui/test/split-tiles-and-titles.test.ts+++ b/plugins/web-ui/test/split-tiles-and-titles.test.ts@@ -25,7 +25,7 @@ test("the tile cap counts tiles and turns the overflow into a tab", () => {});test("a revived canvas is bounded by both caps and cannot blow the stack", () => {- assert.match(split, /if \(n < 2 \|\| n > MAX_PANES \|\| serializedTileCount\(o\.layout\) > MAX_TILES\) return;/);+ assert.match(split, /if \(n < 1 \|\| n > MAX_PANES \|\| serializedTileCount\(o\.layout\) > MAX_TILES\) return;/);const tiles = (...kids: object[]): object => ({ grid: { root: branch(...kids) } });assert.equal(serializedTileCount(tiles(leaf(["a", "b", "c"]), leaf(["d"]))), 2, "tabs are not tiles");