Multiplayer agent harness for work.
Multi-chat management: pane tabs, session multi-select, and richer session navigation (#697)
Joshua Franceb36e5a653957
diff --git a/plugins/web-ui/src/deep-link.ts b/plugins/web-ui/src/deep-link.tsindex 336510b76..10dfd279c 100644--- a/plugins/web-ui/src/deep-link.ts+++ b/plugins/web-ui/src/deep-link.ts@@ -17,7 +17,7 @@ export function deepLinkPath(}if (view !== "chats") return `${b}/${encodeURIComponent(view)}${itemId ? `/${encodeURIComponent(itemId)}` : ""}`;if (itemId) throw new Error("the chats view is addressed by session, not by item id");- return `${b}/${sessionId ? `?session=${encodeURIComponent(sessionId)}` : ""}`;+ return sessionId ? `${b}/s/${encodeURIComponent(sessionId)}` : `${b}/`;}function decodeSegment(seg: string): string | null {@@ -44,18 +44,30 @@ export function parseDeepLink(if (pathView === "projects") {projectItem = projectKind ? decodeSegment(segments[2] ?? "") : decodeSegment(segments[1] ?? "");}- const requestedView = params.get("view") ?? (pathView === "projects" ? "contexts" : pathView);+ const sessionSeg = pathView === "s" ? decodeSegment(segments[1] ?? "") : null;+ let fallbackView = pathView;+ if (pathView === "projects") fallbackView = "contexts";+ else if (pathView === "s") fallbackView = "chats";+ const requestedView = params.get("view") ?? fallbackView;const view = requestedView === "connectors" ? "keychain" : requestedView;return {view,- session: params.get("session"),- item:- pathView === "projects" && projectKind && projectItem- ? `${projectKind}:${projectItem}`- : (projectItem ?? decodeSegment(segments[1] ?? "")),+ session: sessionSeg ?? params.get("session"),+ item: itemFor(pathView, projectKind, projectItem, segments),};}+function itemFor(+ pathView: string | null,+ projectKind: string | null,+ projectItem: string | null,+ segments: string[],+): string | null {+ if (pathView === "s") return null;+ if (pathView === "projects" && projectKind && projectItem) return `${projectKind}:${projectItem}`;+ return projectItem ?? decodeSegment(segments[1] ?? "");+}+export function sessionLink(origin: string, base: string, sessionId: string): string {return `${origin}${deepLinkPath(base, "chats", sessionId)}`;}diff --git a/plugins/web-ui/src/document-title.ts b/plugins/web-ui/src/document-title.tsnew file mode 100644index 000000000..e725f3c39--- /dev/null+++ b/plugins/web-ui/src/document-title.ts@@ -0,0 +1,46 @@+import type { View } from "./shell-state";++interface TitledSession {+ id: string;+ threadRef: string;+}++interface ActiveConversation {+ openingKey: string | null;+ sessionId: string | null;+ threadRef: string | null;+}++export const PRODUCT_TITLE = "QM · Web";++const VIEW_TITLES: Record<View, string> = {+ chats: "Chats",+ contexts: "Projects",+ webhooks: "Webhooks",+ crons: "Crons",+ files: "Files",+ keychain: "Keychain",+ deploys: "Apps",+ memory: "Memory",+ skills: "Skills",+};++export function documentTitle(view?: View, conversationTitle?: string | null, conversationOpen = false): string {+ const title =+ view === "chats" && conversationOpen ? conversationTitle?.trim() || "New chat" : view && VIEW_TITLES[view];+ return title ? `${title} · ${PRODUCT_TITLE}` : PRODUCT_TITLE;+}++export function updateDocumentTitle(view?: View, conversationTitle?: string | null, conversationOpen = false): void {+ document.title = documentTitle(view, conversationTitle, conversationOpen);+}++export function activeSessionForDocumentTitle<T extends TitledSession>(+ sessions: T[],+ active: ActiveConversation,+): T | undefined {+ if (active.openingKey) return sessions.find((session) => session.id === active.openingKey);+ return sessions.find(+ (session) => session.id === active.sessionId || (!active.sessionId && session.threadRef === active.threadRef),+ );+}diff --git a/plugins/web-ui/src/main.ts b/plugins/web-ui/src/main.tsindex 6aa30383b..b76ffaa3f 100644--- a/plugins/web-ui/src/main.ts+++ b/plugins/web-ui/src/main.ts@@ -4,7 +4,13 @@ import { bootSafely } from "./shell";import { registerChatSearchHotkey } from "./search";import { closeFormMenus } from "./ui";import { allConversations } from "./conversations";-import { closeOpenSessionMenu, renderList, sessionsState } from "./sessions";+import {+ clearSessionSelection,+ closeOpenSessionMenu,+ closeSessionSelectionColor,+ renderList,+ sessionsState,+} from "./sessions";import { closeDeployMenu } from "./deploys";function closeComposerMenus(keepOpenWithin: Element | null): boolean {@@ -27,6 +33,7 @@ document.addEventListener("click", (e) => {sessionsState.openMenuId = null;renderList();}+ if (!target?.closest(".multi-select-color")) closeSessionSelectionColor();closeDeployMenu(target);});@@ -34,6 +41,7 @@ document.addEventListener("keydown", (e) => {if (e.key !== "Escape") return;closeComposerMenus(null);closeOpenSessionMenu();+ clearSessionSelection();closeDeployMenu(null, true);closeFormMenus();});diff --git a/plugins/web-ui/src/session-select.ts b/plugins/web-ui/src/session-select.tsnew file mode 100644index 000000000..20277be01--- /dev/null+++ b/plugins/web-ui/src/session-select.ts@@ -0,0 +1,41 @@+export interface SessionSelection {+ ids: ReadonlySet<string>;+ anchor: string | null;+ shiftRange: ReadonlySet<string>;+}++export function emptySelection(): SessionSelection {+ return { ids: new Set(), anchor: null, shiftRange: new Set() };+}++export function selectionClick(+ state: SessionSelection,+ order: readonly string[],+ id: string,+ mods: { shift: boolean; toggle: boolean },+): SessionSelection {+ if (mods.shift) {+ const anchor = state.anchor ?? id;+ const a = order.indexOf(anchor);+ const b = order.indexOf(id);+ const shiftRange = new Set(a === -1 || b === -1 ? [id] : order.slice(Math.min(a, b), Math.max(a, b) + 1));+ const ids = new Set(state.ids);+ for (const rangeId of state.shiftRange) ids.delete(rangeId);+ for (const rangeId of shiftRange) ids.add(rangeId);+ return { ids, anchor, shiftRange };+ }+ if (mods.toggle) {+ const ids = new Set(state.ids);+ if (ids.has(id)) ids.delete(id);+ else ids.add(id);+ return { ids, anchor: id, shiftRange: new Set() };+ }+ return { ids: new Set(), anchor: id, shiftRange: new Set() };+}++export function pruneSelection(state: SessionSelection, visible: ReadonlySet<string>): SessionSelection {+ if ([...state.ids].every((id) => visible.has(id))) return state;+ const ids = new Set([...state.ids].filter((id) => visible.has(id)));+ const shiftRange = new Set([...state.shiftRange].filter((id) => visible.has(id)));+ return { ids, anchor: state.anchor, shiftRange };+}diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.tsindex ce7fc36d3..aff81e43d 100644--- a/plugins/web-ui/src/sessions.ts+++ b/plugins/web-ui/src/sessions.ts@@ -4,6 +4,7 @@ import { ref } from "lit/directives/ref.js";import { repeat } from "lit/directives/repeat.js";import {Archive,+ Ban,Binoculars,ArchiveRestore,ChevronDown,@@ -15,6 +16,7 @@ import {Hash,Link,Lock,+ Palette,Pencil,Pin,PinOff,@@ -73,7 +75,14 @@ import {} from "./contexts";import { groupDmLabel, groupDmText } from "./group-dm-label";import { transcriptModel } from "./model-options";-import { appState, closeSidebarOnNarrowView, renderSidebarTop, showMainEmpty, syncUrlFromState } from "./shell";+import {+ appState,+ closeSidebarOnNarrowView,+ renderSidebarTop,+ showMainEmpty,+ syncDocumentTitle,+ syncUrlFromState,+} from "./shell";import { allConversations, mainConversation } from "./conversations";import type { Conversation } from "./conv-types";import {@@ -90,6 +99,7 @@ import {splitState,} from "./split";import { liveTurnThreadRef } from "./working-dot";+import { emptySelection, pruneSelection, selectionClick, type SessionSelection } from "./session-select";export const sessionsState = {list: [] as CoreSession[],@@ -101,6 +111,41 @@ export const sessionsState = {collapsedProjectScopes: new Set<string>(),};+let selection: SessionSelection = emptySelection();+type SessionPatch = { title?: string | null; archived?: boolean; pinned?: boolean; color?: string | null };+const sessionPatchTails = new Map<string, Promise<void>>();+const sessionPatchVersions = new Map<string, number>();+let sessionPatchGeneration = 0;+let sessionPatchEpoch = 0;++export function clearSessionSelection(): boolean {+ if (!selection.ids.size && !selection.anchor) return false;+ selection = emptySelection();+ selectColorOpen = false;+ redrawSelection();+ return true;+}++export function hasSessionSelection(): boolean {+ return selection.ids.size > 0;+}++let selectColorOpen = false;++function redrawSelection(): void {+ renderList();+ renderSidebarTop();+}++function visibleRowOrder(): string[] {+ const el = appState.listEl;+ if (!el) return [];+ return [...el.querySelectorAll<HTMLElement>("[data-session-id]")]+ .filter((row) => !row.closest("[hidden]"))+ .map((n) => n.dataset.sessionId ?? "")+ .filter(Boolean);+}+const WEB_ONLY_KEY = "web-ui:web-only";sessionsState.webOnly = ((): boolean => {try {@@ -126,6 +171,12 @@ let chatsPageSurface: "all" | "web" | "slack" = "all";let chatsPageHost: HTMLElement | null = null;export function resetSessionsState(): void {+ selection = emptySelection();+ selectColorOpen = false;+ sessionPatchGeneration++;+ sessionPatchEpoch++;+ sessionPatchTails.clear();+ sessionPatchVersions.clear();sessionsState.list = [];sessionsState.loaded = false;sessionsState.openMenuId = null;@@ -260,6 +311,7 @@ function visibleSessions(): CoreSession[] {}export function renderList(): void {+ syncDocumentTitle();if (!appState.listEl) return;const visible = visibleSessions();const active = visible.filter((s) => !s.archived);@@ -307,6 +359,9 @@ export function renderList(): void {`,appState.listEl,);+ const beforePrune = selection.ids.size;+ selection = pruneSelection(selection, new Set(visibleRowOrder()));+ if (selection.ids.size !== beforePrune) renderSidebarTop();if (sessionsState.openMenuId) {requestAnimationFrame(() => placeSessionMenu(appState.listEl?.querySelector(".session-menu-popover") ?? undefined));}@@ -787,13 +842,15 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {s.awaitingInput ? "waiting for your reply" : null,readOnly ? "read-only" : null,s.pinned ? "pinned" : null,+ selection.ids.has(s.id) ? "selected" : null,relTime(activityOf(s)),].filter(Boolean).join(", ");return html`<div- class="session-row ${active ? "active" : ""} ${menuOpen ? "menu-open" : ""} ${readOnly ? "read-only" : ""} ${refreshingTitle ? "title-refreshing" : ""} ${working ? "working" : ""} ${s.awaitingInput ? "awaiting-input" : ""} ${projectChild ? "project-child" : ""} ${s.color ? "colored" : ""}"+ data-session-id=${saved ? s.id : nothing}+ class="session-row ${active ? "active" : ""} ${saved && selection.ids.has(s.id) ? "selected" : ""} ${menuOpen ? "menu-open" : ""} ${readOnly ? "read-only" : ""} ${refreshingTitle ? "title-refreshing" : ""} ${working ? "working" : ""} ${s.awaitingInput ? "awaiting-input" : ""} ${projectChild ? "project-child" : ""} ${s.color ? "colored" : ""}"style=${s.color ? `--session-color:${s.color}` : nothing}><a@@ -801,14 +858,41 @@ function sessionRow(s: CoreSession, projectChild = false): TemplateResult {href=${saved ? deepLinkPath(UI_BASE, "chats", s.id) : nothing}aria-busy=${refreshingTitle ? "true" : "false"}aria-label=${ariaLabel}+ aria-keyshortcuts="Space Shift+Space Control+Space Meta+Space"+ title="Press Space to select"draggable=${saved ? "true" : "false"}@dragstart=${(e: DragEvent) => onSessionDragStart(e, s)}@dragend=${() => endSessionDrag()}+ @mousedown=${(e: MouseEvent) => {+ if (saved && e.shiftKey) e.preventDefault();+ }}@click=${(e: MouseEvent) => {+ if (saved && e.button === 0 && (e.shiftKey || e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ selection = selectionClick(selection, visibleRowOrder(), s.id, {+ shift: e.shiftKey,+ toggle: e.metaKey || e.ctrlKey,+ });+ redrawSelection();+ return;+ }if (saved && !isPlainLeftClick(e)) return;e.preventDefault();+ const hadSelection = selection.ids.size > 0;+ selection = { ids: new Set(), anchor: saved ? s.id : null, shiftRange: new Set() };+ selectColorOpen = false;+ if (hadSelection) redrawSelection();void openSession(s);}}+ @keydown=${(e: KeyboardEvent) => {+ if (!saved || e.key !== " ") return;+ e.preventDefault();+ selection = selectionClick(selection, visibleRowOrder(), s.id, {+ shift: e.shiftKey,+ toggle: !e.shiftKey || e.metaKey || e.ctrlKey,+ });+ redrawSelection();+ }}@dblclick=${(e: Event) => {if (!saved) return;e.preventDefault();@@ -1071,6 +1155,139 @@ async function commitRename(s: CoreSession): Promise<void> {await persistSessionPatch(s.id, { title: desired });}+/** Archive a session by id — closes any surface showing it and updates the Recents list immediately. */+export function archiveSessionById(sessionId: string): void {+ const s = sessionsState.list.find((x) => x.id === sessionId);+ if (s && !s.archived) {+ setArchived(s, true);+ return;+ }+ closeSessionSurfaces(sessionId);+ if (!s) void persistSessionPatch(sessionId, { archived: true });+}++export function sessionSelectionBar(): TemplateResult | null {+ const n = selection.ids.size;+ if (!n) return null;+ const rows = sessionsState.list.filter((s) => selection.ids.has(s.id));+ const allArchived = rows.length > 0 && rows.every((s) => s.archived);+ const allPinned = rows.length > 0 && rows.every((s) => s.pinned);+ return html`+ <div+ class="section-label recents-label multi-select-bar"+ role="toolbar"+ aria-label=${`${n} conversations selected`}+ >+ <span class="multi-select-summary">+ <button+ class="icon-btn"+ type="button"+ title="Clear selection (Esc)"+ aria-label="Clear selection"+ @click=${() => clearSessionSelection()}+ >+ ${icon(X, 14)}+ </button>+ <span class="multi-select-count">${n} selected</span>+ </span>+ <span class="multi-select-actions">+ <button+ class="icon-btn"+ type="button"+ title=${allPinned ? "Unpin selected" : "Pin selected"}+ aria-label=${allPinned ? "Unpin selected conversations" : "Pin selected conversations"}+ @click=${() => void bulkPatch({ pinned: !allPinned })}+ >+ ${allPinned ? icon(PinOff, 14) : icon(Pin, 14)}+ </button>+ <span class="multi-select-color">+ <button+ class="icon-btn"+ type="button"+ title="Color selected"+ aria-label="Color selected conversations"+ aria-haspopup="true"+ aria-expanded=${selectColorOpen ? "true" : "false"}+ @click=${(e: Event) => {+ e.stopPropagation();+ selectColorOpen = !selectColorOpen;+ renderSidebarTop();+ }}+ >+ ${icon(Palette, 14)}+ </button>+ </span>+ <button+ class="icon-btn"+ type="button"+ title=${allArchived ? "Unarchive selected" : "Archive selected"}+ aria-label=${allArchived ? "Unarchive selected conversations" : "Archive selected conversations"}+ @click=${() => void bulkPatch({ archived: !allArchived })}+ >+ ${allArchived ? icon(ArchiveRestore, 14) : icon(Archive, 14)}+ </button>+ </span>+ ${selectColorOpen ? colorPopover() : nothing}+ </div>+ `;+}++export function closeSessionSelectionColor(): boolean {+ if (!selectColorOpen) return false;+ selectColorOpen = false;+ renderSidebarTop();+ return true;+}++function colorPopover(): TemplateResult {+ return html`+ <div+ class="session-menu-popover multi-select-color-popover"+ role="menu"+ @click=${(e: Event) => e.stopPropagation()}+ >+ <div class="session-menu-colors" role="group" aria-label="Color selected conversations">+ ${SESSION_COLORS.map(+ (c) => html`+ <button+ class="color-swatch"+ type="button"+ style=${`--swatch:${c}`}+ title=${`Color selected ${c}`}+ aria-label=${`Color selected conversations ${c}`}+ @click=${() => void bulkPatch({ color: c })}+ ></button>+ `,+ )}+ <button+ class="color-swatch clear"+ type="button"+ title="Clear color"+ aria-label="Clear color on selected conversations"+ @click=${() => void bulkPatch({ color: null })}+ >+ ${icon(Ban, 10)}+ </button>+ </div>+ </div>+ `;+}++async function bulkPatch(patch: SessionPatch): Promise<void> {+ const generation = sessionPatchGeneration;+ const ids = [...selection.ids];+ selectColorOpen = false;+ if (patch.archived !== undefined) selection = emptySelection();+ if (patch.archived) for (const id of ids) closeSessionSurfaces(id);+ sessionsState.list = sessionsState.list.map((s) => (ids.includes(s.id) ? { ...s, ...patch } : s));+ redrawSelection();+ const patches = ids.map((id) => queueSessionPatch(id, patch));+ const results = await Promise.allSettled(patches);+ if (sessionPatchGeneration === generation && results.some((r) => r.status === "rejected"))+ await refreshSessions({ silent: true, patchEpoch: sessionPatchEpoch });+ redrawSelection();+}+function setArchived(s: CoreSession, archived: boolean): void {sessionsState.openMenuId = null;if (archived && s.id) closeSessionSurfaces(s.id);@@ -1131,21 +1348,51 @@ async function refreshSessionTitle(s: CoreSession): Promise<void> {}}-async function persistSessionPatch(- id: string,- patch: { title?: string | null; archived?: boolean; pinned?: boolean; color?: string | null },-): Promise<void> {+async function persistSessionPatch(id: string, patch: SessionPatch): Promise<void> {+ const generation = sessionPatchGeneration;sessionsState.list = sessionsState.list.map((s) => (s.id === id ? { ...s, ...patch } : s));renderList();+ const request = queueSessionPatch(id, patch);try {- const { session } = await updateSession(id, patch);- applyResolvedSession(session);+ await request;renderList();} catch {- await refreshSessions({ silent: true });+ if (sessionPatchGeneration === generation) await refreshSessions({ silent: true, patchEpoch: sessionPatchEpoch });}}+function queueSessionPatch(id: string, patch: SessionPatch): Promise<CoreSession> {+ sessionPatchEpoch++;+ const version = (sessionPatchVersions.get(id) ?? 0) + 1;+ const generation = sessionPatchGeneration;+ sessionPatchVersions.set(id, version);+ const prior = sessionPatchTails.get(id) ?? Promise.resolve();+ const request = prior+ .catch(() => undefined)+ .then(async () => {+ const { session } = await updateSession(id, patch);+ if (sessionPatchGeneration === generation && sessionPatchVersions.get(id) === version)+ applyResolvedSession(session);+ return session;+ });+ sessionPatchTails.set(+ id,+ request.then(+ () => undefined,+ () => undefined,+ ),+ );+ void request.then(+ () => {+ if (sessionPatchGeneration === generation) sessionPatchEpoch++;+ },+ () => {+ if (sessionPatchGeneration === generation) sessionPatchEpoch++;+ },+ );+ return request;+}+let listSettled: (() => void) | null = null;const listReady = new Promise<void>((resolve) => (listSettled = resolve));@@ -1153,11 +1400,25 @@ export function sessionsReady(): Promise<void> {return sessionsState.loaded ? Promise.resolve() : listReady;}-export async function refreshSessions(- opts: { showLoading?: boolean; silent?: boolean; refreshContexts?: boolean } = {},+let latestSessionsRefresh: Promise<boolean> | null = null;++export function refreshSessions(+ opts: { showLoading?: boolean; silent?: boolean; refreshContexts?: boolean; patchEpoch?: number } = {},+): Promise<boolean> {+ const run: Promise<boolean> = runSessionsRefresh(opts, () =>+ latestSessionsRefresh === run ? null : latestSessionsRefresh,+ );+ latestSessionsRefresh = run;+ return run;+}++async function runSessionsRefresh(+ opts: { showLoading?: boolean; silent?: boolean; refreshContexts?: boolean; patchEpoch?: number },+ newerRun: () => Promise<boolean> | null,): Promise<boolean> {loadRecentContexts(opts.refreshContexts === true);const seq = ++sessionRefreshSeq;+ const patchEpoch = opts.patchEpoch ?? sessionPatchEpoch;if (opts.showLoading) {sessionsLoading = true;sessionsNotice = "";@@ -1165,19 +1426,20 @@ export async function refreshSessions(}try {const r = await api<{ sessions: CoreSession[] }>("/api/sessions");- if (seq !== sessionRefreshSeq) return false;+ if (seq !== sessionRefreshSeq) return sessionsState.loaded || ((await newerRun()) ?? false);+ if (patchEpoch !== sessionPatchEpoch) return false;sessionsState.list = reconcileSessions(r.sessions ?? [], sessionsState.list);sessionsState.loaded = true;sessionsNotice = "";return true;} catch (e) {- if (seq !== sessionRefreshSeq) return false;+ if (seq !== sessionRefreshSeq) return sessionsState.loaded || ((await newerRun()) ?? false);if (!opts.silent) sessionsNotice = errMessage(e, "Failed to load conversations.");return false;} finally {- listSettled?.();- listSettled = null;if (seq === sessionRefreshSeq) {+ listSettled?.();+ listSettled = null;sessionsLoading = false;renderList();}diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 3f62bd199..d2aa7580b 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -6706,6 +6706,7 @@ h3.ambient-field-label {}.dockview-theme-qm .dv-tabs-and-actions-container {+ position: relative;box-sizing: border-box;padding: 4px 6px 4px 10px;gap: 8px;@@ -6768,6 +6769,12 @@ h3.ambient-field-label {display: none;}+/* …but archive has no group-level counterpart (the header's X closes the pane, it doesn't+ archive), so a lone tab keeps its archive button. */+.dockview-theme-qm .dv-single-tab .split-tab-archive {+ display: inline-flex;+}+/* Multi-tab groups (tabbing is new capability the old canvas lacked): segmented chips inthe app's own control idiom — the active tab is the standard raised card (page bg, 1pxborder, tiny shadow, 34px like .icon-btn), inactive tabs are muted text with the shared@@ -6883,6 +6890,12 @@ h3.ambient-field-label {min-width 0.12s ease;}+/* When the archive button is present it takes the auto margin; the close button that+ follows sits snug beside it instead of splitting the leftover space. */+.split-tab-archive + .split-tab-close {+ margin-left: 2px;+}+.dv-tab:not(.dv-active-tab):not(:hover):not(:focus-within) .split-tab-close {width: 0;min-width: 0;@@ -7093,11 +7106,38 @@ h3.ambient-field-label {color: var(--foreground);}+/* A native tab drag lights every pane up as a valid target from drag start;+ dockview's own dropzone still handles the precise edge choice on hover. */+.split-canvas.tab-dragging .dv-groupview {+ box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--primary) 55%, var(--border));+ background: color-mix(in srgb, var(--primary) 6%, transparent);+}+.split-canvas.session-dragging .dv-tabs-and-actions-container {box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--primary) 55%, var(--border));background: color-mix(in srgb, var(--primary) 6%, transparent);}+/* The strip's own drop target: the highlight above is only paint. */+.strip-zones {+ position: absolute;+ inset: 0;+ z-index: 6;+}++.strip-zones .split-zone {+ inset: 0;+ margin: 2px;+ border-color: transparent;+ background: transparent;+ font-size: 11.5px;+}++.strip-zones .split-zone.over {+ border-color: color-mix(in srgb, var(--primary) 55%, var(--border));+ background: color-mix(in srgb, var(--primary) 14%, transparent);+}+.zone-top {left: 25%;right: 25%;@@ -7558,3 +7598,69 @@ h3.ambient-field-label {.chat-search-failed {color: var(--destructive, #b42318);}++.session-row.selected .session {+ background: color-mix(in srgb, var(--primary, #d99a21) 16%, transparent);+}+.session-row.selected .session:hover,+.session-row.selected.active .session {+ background: color-mix(in srgb, var(--primary, #d99a21) 24%, transparent);+}+.session-row .session {+ user-select: none;+}+.section-label.multi-select-bar {+ position: relative;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 6px;+ text-transform: none;+ letter-spacing: normal;+ overflow: visible;+}+.multi-select-count {+ font-size: 12px;+ font-weight: 600;+ color: var(--muted-foreground);+ white-space: nowrap;+}+.multi-select-summary {+ display: flex;+ align-items: center;+ gap: 4px;+ min-width: 0;+}+.multi-select-color {+ position: relative;+ display: inline-flex;+}+.multi-select-color-popover {+ position: absolute;+ top: calc(100% + 4px);+ right: 0;+ z-index: 30;+ min-width: 0;+ padding: 6px;+ border-radius: 10px;+}+.multi-select-color-popover .session-menu-colors {+ gap: 6px;+ margin: 0;+ padding: 2px;+ border: 0;+}+.multi-select-color-popover .color-swatch {+ width: 16px;+ height: 16px;+}+.multi-select-actions {+ display: flex;+ align-items: center;+ gap: 0;+}+.multi-select-bar .icon-btn {+ width: 22px;+ height: 22px;+ border-radius: 6px;+}diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex 4af07a20f..2f288e39e 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -41,6 +41,7 @@ import {canvasToast,drawCanvas,exitSplitIfActive,+ focusedPaneSession,loadPersistedSplit,mountRestoredCanvas,openBlankInFocusedPane,@@ -56,8 +57,10 @@ import {refreshSessions,renderList,resetSessionsState,+ sessionTitle,sessionsState,toggleWebOnly,+ sessionSelectionBar,} from "./sessions";import { openCronById, renderCronsPage, resetActiveCron, routeCronsHistory } from "./crons";import { openWebhookById, renderWebhooksPage, resetActiveWebhook, routeWebhooksHistory } from "./webhooks";@@ -72,6 +75,7 @@ import { renderSkills } from "./skills";import { contextsState, ensureContexts, renderContexts, resetContextsState, resolveProjectScope } from "./contexts";import { appState, can, isView, type AuthMode, type Me, type View } from "./shell-state";import { trapDialogFocus } from "./dialog-focus";+import { activeSessionForDocumentTitle, updateDocumentTitle } from "./document-title";export { appState, can, type Me, type View } from "./shell-state";let authMode: AuthMode = "portal";@@ -206,6 +210,7 @@ export async function signOut(): Promise<void> {resetContextsState();resetKeychainState();mainConversation().composer.resetComposer();+ updateDocumentTitle();if (!portal) {renderAuthGate({ kind: "dev" });return;@@ -483,6 +488,7 @@ export function mountShell(): void {}export function renderSidebarTop(): void {+ syncDocumentTitle();if (!appState.topEl) return;const navRow = (v: View, glyph: IconNode, label: string) =>html`<a@@ -543,41 +549,64 @@ export function renderSidebarTop(): void {`,)}</nav>- ${html`- <div class="section-label recents-label">- <span>Sessions</span>- <button- class="chat-search-open"- type="button"- aria-label="Search your chats"- @click=${() => {- hideTooltip();- openChatSearch();- }}- @mouseenter=${(e: Event) => showTooltip(e.currentTarget as Element, `Search your chats · ${SEARCH_HOTKEY_LABEL}`)}- @mouseleave=${(e: Event) => hideTooltip(e.currentTarget as Element)}- @focus=${(e: Event) => showTooltip(e.currentTarget as Element, `Search your chats · ${SEARCH_HOTKEY_LABEL}`)}- @blur=${(e: Event) => hideTooltip(e.currentTarget as Element)}- >- ${icon(Search, 13)}- </button>- <button- class="web-only-toggle ${sessionsState.webOnly ? "on" : ""}"- type="button"- role="switch"- aria-checked=${sessionsState.webOnly ? "true" : "false"}- title=${sessionsState.webOnly ? "Showing web chats only" : "Hide non-web conversations"}- @click=${toggleWebOnly}- >- <span>Web only</span><span class="mini-switch"><span class="mini-knob"></span></span>- </button>- </div>- `}+ ${+ sessionSelectionBar() ??+ html`+ <div class="section-label recents-label">+ <span>Sessions</span>+ <button+ class="chat-search-open"+ type="button"+ aria-label="Search your chats"+ @click=${() => {+ hideTooltip();+ openChatSearch();+ }}+ @mouseenter=${(e: Event) => showTooltip(e.currentTarget as Element, `Search your chats · ${SEARCH_HOTKEY_LABEL}`)}+ @mouseleave=${(e: Event) => hideTooltip(e.currentTarget as Element)}+ @focus=${(e: Event) => showTooltip(e.currentTarget as Element, `Search your chats · ${SEARCH_HOTKEY_LABEL}`)}+ @blur=${(e: Event) => hideTooltip(e.currentTarget as Element)}+ >+ ${icon(Search, 13)}+ </button>+ <button+ class="web-only-toggle ${sessionsState.webOnly ? "on" : ""}"+ type="button"+ role="switch"+ aria-checked=${sessionsState.webOnly ? "true" : "false"}+ title=${sessionsState.webOnly ? "Showing web chats only" : "Hide non-web conversations"}+ @click=${toggleWebOnly}+ >+ <span>Web only</span><span class="mini-switch"><span class="mini-knob"></span></span>+ </button>+ </div>+ `+ }`,appState.topEl,);}+export function syncDocumentTitle(): void {+ if (!appState.me) {+ updateDocumentTitle();+ return;+ }+ const state = mainConversation().state;+ const active = splitState.active+ ? focusedPaneSession()+ : activeSessionForDocumentTitle(sessionsState.list, {+ openingKey: sessionsState.openingKey,+ sessionId: state.sessionId,+ threadRef: state.threadRef,+ });+ updateDocumentTitle(+ appState.currentView,+ active ? sessionTitle(active) : null,+ Boolean(active || (!splitState.active && state.threadRef)),+ );+}+function onNavClick(e: Event): void {const target = e.target as Element | null;const row = target?.closest<HTMLAnchorElement>(".navrow[data-view]");diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.tsindex 4a94cdc34..2ddd52d19 100644--- a/plugins/web-ui/src/split.ts+++ b/plugins/web-ui/src/split.ts@@ -1,6 +1,7 @@import { html, nothing, render, type TemplateResult } from "lit";import { ref } from "lit/directives/ref.js";import {+ Archive,Binoculars,Box,Brain,@@ -48,7 +49,7 @@ import { icon } from "./ui";import { contextsState, scopeTitle } from "./contexts";import type { DensityTier } from "./density";import { appState } from "./shell-state";-import { renderSidebarTop, switchView } from "./shell";+import { renderSidebarTop, switchView, syncDocumentTitle } from "./shell";import { sleep } from "./chat";import {createConversation,@@ -65,12 +66,12 @@ import {renderList,sessionsState,sessionTitle,+ archiveSessionById,syncWorkingPulse,} from "./sessions";import { conversationBackground, type RowIndicators } from "./session-list";import { setScopedSession, type SessionTool } from "./session-scope";-import type { CoreSession } from "./core-bridge";-import { fetchUiState, putUiState } from "./core-bridge";+import { fetchTranscript, fetchUiState, putUiState, TAIL_TURNS, type CoreSession } from "./core-bridge";export const splitState = {active: false,@@ -97,6 +98,7 @@ let pendingSeed: PendingSeed | null = null;const paneContents = new Map<string, PaneContent>();const paneTabs = new Set<PaneTab>();const groupActions = new Set<GroupActions>();+const stripDrops = new Set<StripDrop>();let sessionDrag: { sessionId: string; threadRef: string } | null = null;let toastMsg = "";let toastTimer: number | null = null;@@ -170,6 +172,7 @@ function buildDock(): DockviewApi {createComponent: () => new PaneContent(),createTabComponent: () => new PaneTab(),createRightHeaderActionComponent: () => new GroupActions(),+ createPrefixHeaderActionComponent: () => new StripDrop(),singleTabMode: "fullwidth",disableFloatingGroups: true,});@@ -184,17 +187,11 @@ function buildDock(): DockviewApi {}};api.onWillDrop(holdTileCap);- api.onUnhandledDragOver((e) => {- if (sessionDrag && (e.target === "tab" || e.target === "header_space")) e.accept();- });- api.onDidDrop((e) => {- const drag = sessionDrag;- endSessionDrag();- const anchor = e.group?.activePanel ?? e.group?.panels[0];- if (!drag || !anchor || focusExistingPane(drag.sessionId)) return;- const at = e.panel ? e.group?.panels.indexOf(e.panel) : undefined;- tabIntoPane(anchor.id, { sessionId: drag.sessionId, threadRef: drag.threadRef }, at === -1 ? undefined : at);- });+ // A native tab/group drag gets the same courtesy as a sidebar session drag: every+ // pane advertises itself as a drop target from the moment the drag starts, instead+ // of waiting to be discovered by hover (dockview only paints its dropzone on dragover).+ api.onWillDragPanel(() => beginTabDragHint());+ api.onWillDragGroup(() => beginTabDragHint());const guarded = new WeakSet<IDockviewGroupPanel>();api.onDidLayoutChange(() => {host.classList.toggle("one-pane", api.panels.length === 1);@@ -208,6 +205,7 @@ function buildDock(): DockviewApi {});api.onDidActivePanelChange((e) => {splitState.focusedId = e.panel?.id ?? null;+ syncDocumentTitle();});api.onDidMaximizedGroupChange(() => {for (const a of groupActions) a.draw();@@ -241,6 +239,7 @@ function disposeDock(): void {paneContents.clear();paneTabs.clear();groupActions.clear();+ stripDrops.clear();toastEl = null;}@@ -272,6 +271,7 @@ function ensureCanvas(): boolean {}ensureDeliveryStream();splitState.focusedId = dockApi.activePanel?.id ?? dockApi.panels[0]?.id ?? null;+ syncDocumentTitle();headerSignature = computeHeaderSignature();return true;}@@ -281,7 +281,6 @@ function addPane(position?: {referencePanel: string;direction: "left" | "right" | "above" | "below" | "within";- index?: number;},): IDockviewPanel {return dockApi!.addPanel({@@ -333,6 +332,7 @@ export function exitSplitIfActive(): void {if (dockApi) lastLayout = dockApi.toJSON();splitState.active = false;splitState.focusedId = null;+ syncDocumentTitle();persist();disposeDock();canvasHost = null;@@ -502,13 +502,9 @@ function splitPane(paneId: string, edge: SplitEdge, params: PaneParams): void {persist();}-function tabIntoPane(paneId: string, params: PaneParams, index?: number): boolean {+function tabIntoPane(paneId: string, params: PaneParams): boolean {if (!dockApi || !roomForAnotherPane()) return false;- const fresh = addPane(params, {- referencePanel: paneId,- direction: "within",- ...(index === undefined ? {} : { index }),- });+ const fresh = addPane(params, { referencePanel: paneId, direction: "within" });fresh.api.setActive();persist();return true;@@ -601,18 +597,39 @@ export function beginSessionDrag(s: CoreSession): void {refreshSessionDrag();}+// A strip drop joins the session to that group as a tab — offered only when it would+// really add one (not already on the canvas, below the pane ceiling).+function stripJoinable(drag = sessionDrag): boolean {+ return Boolean(drag && !paneShowing(drag.sessionId) && (dockApi?.panels.length ?? 0) < MAX_PANES);+}+function refreshSessionDrag(): void {- const drag = sessionDrag;- if (!drag) return;- const addsTab = !paneShowing(drag.sessionId) && (dockApi?.panels.length ?? 0) < MAX_PANES;- canvasHost?.classList.toggle("session-dragging", addsTab);+ if (!sessionDrag) return;+ canvasHost?.classList.toggle("session-dragging", stripJoinable());+ drawStripDrops();syncAllZones();}+function drawStripDrops(): void {+ for (const s of stripDrops) s.draw();+}++function beginTabDragHint(): void {+ canvasHost?.classList.add("tab-dragging");+ const end = (): void => {+ canvasHost?.classList.remove("tab-dragging");+ document.removeEventListener("dragend", end, true);+ document.removeEventListener("drop", end, true);+ };+ document.addEventListener("dragend", end, true);+ document.addEventListener("drop", end, true);+}+export function endSessionDrag(): void {if (!sessionDrag) return;sessionDrag = null;canvasHost?.classList.remove("session-dragging");+ drawStripDrops();if (splitState.active) syncAllZones();}@@ -702,6 +719,7 @@ function refreshHeaders(): void {headerSignature = computeHeaderSignature();for (const t of paneTabs) t.draw();for (const c of paneContents.values()) c.syncTitle();+ syncDocumentTitle();}function paneSession(panel: IDockviewPanel): CoreSession | undefined {@@ -709,6 +727,12 @@ function paneSession(panel: IDockviewPanel): CoreSession | undefined {return sessionId ? sessionsState.list.find((s) => s.id === sessionId) : undefined;}+export function focusedPaneSession(): CoreSession | undefined {+ if (!splitState.active || !dockApi) return undefined;+ const panel = (splitState.focusedId && dockApi.getPanel(splitState.focusedId)) || dockApi.activePanel;+ return panel ? paneSession(panel) : undefined;+}+function paneTitle(panel: IDockviewPanel): string {const session = paneSession(panel);if (session) return sessionTitle(session);@@ -866,10 +890,19 @@ class PaneContent implements IContentRenderer {session = sessionsState.list.find((s) => s.id === wanted);}if (!session) {- this.conversation.mountReadOnly(- { id: wanted, threadRef: threadRef ?? "", scopeId: "", title: "" } as CoreSession,- [],- );+ const page = await fetchTranscript(wanted, { tailTurns: TAIL_TURNS }).catch(() => null);+ if (this.disposed) return;+ session = page?.session;+ if (!session) {+ this.conversation.mountReadOnly(+ { id: wanted, threadRef: threadRef ?? "", scopeId: "", title: "" } as CoreSession,+ [],+ );+ return;+ }+ await openSessionInto(this.conversation, session, Promise.resolve(page));+ if (this.disposed) return;+ refreshHeaders();return;}if (background) {@@ -934,6 +967,7 @@ class PaneTab implements ITabRenderer {const working = paneIsWorking(panel);const awaiting = paneAwaitsInput(panel);const background = paneBackground(panel);+ const sessionId = panelParams(panel).sessionId;this.element.title = crumb ? `${crumb} / ${title}` : title;render(html`@@ -958,6 +992,23 @@ class PaneTab implements ITabRenderer {: nothing}<span class="split-pane-title-text">${title}</span>+ ${+ this.inStrip && sessionId+ ? html`<button+ class="icon-btn subtle split-tab-close split-tab-archive"+ type="button"+ title="Archive session"+ aria-label="Archive session"+ @pointerdown=${(e: Event) => e.stopPropagation()}+ @click=${(e: Event) => {+ e.stopPropagation();+ archiveSessionById(sessionId);+ }}+ >+ ${icon(Archive, 13)}+ </button>`+ : nothing+ }${this.inStrip? html`<button@@ -984,6 +1035,46 @@ class PaneTab implements ITabRenderer {}}+// The strip highlight needs a target behind it: with full-width single tabs dockview's+// header space is zero-width and a tab only accepts its outer reorder edges, so an+// external session drag has nothing real to land on. Dockview owns this element's+// lifecycle, so the zone is mounted and torn down with its group.+class StripDrop implements IHeaderActionsRenderer {+ readonly element: HTMLElement;+ private group: IDockviewGroupPanel | null = null;++ constructor() {+ this.element = document.createElement("div");+ this.element.className = "split-zones strip-zones";+ }++ init(props: IGroupHeaderProps): void {+ this.group = props.group;+ stripDrops.add(this);+ this.draw();+ }++ draw(): void {+ const group = this.group;+ render(+ group && stripJoinable()+ ? zoneTpl("center", "Open as tab", () => {+ const drag = sessionDrag;+ endSessionDrag();+ const anchor = group.activePanel ?? group.panels[0];+ if (!drag || !anchor || focusExistingPane(drag.sessionId)) return;+ tabIntoPane(anchor.id, { sessionId: drag.sessionId, threadRef: drag.threadRef });+ })+ : nothing,+ this.element,+ );+ }++ dispose(): void {+ stripDrops.delete(this);+ }+}+class GroupActions implements IHeaderActionsRenderer {readonly element: HTMLElement;private props: IGroupHeaderProps | null = null;diff --git a/plugins/web-ui/test/deep-link.test.ts b/plugins/web-ui/test/deep-link.test.tsindex f056629ac..a58c91ba7 100644--- a/plugins/web-ui/test/deep-link.test.ts+++ b/plugins/web-ui/test/deep-link.test.ts@@ -2,8 +2,18 @@ import { test } from "node:test";import assert from "node:assert/strict";import { deepLinkPath, parseDeepLink, sessionLink } from "../src/deep-link.ts";-test("chats view with an active session is addressed by /?session=", () => {- assert.equal(deepLinkPath("", "chats", "abc-123"), "/?session=abc-123");+test("chats view with an active session is addressed by /s/<id>", () => {+ assert.equal(deepLinkPath("", "chats", "abc-123"), "/s/abc-123");+});++test("a uuid session round-trips through /s/<uuid>", () => {+ const uuid = "fd8f1b46-4445-4912-8871-9b9f8690107f";+ assert.equal(deepLinkPath("", "chats", uuid), `/s/${uuid}`);+ assert.deepEqual(parseDeepLink("", `/s/${uuid}`, ""), { view: "chats", session: uuid, item: null });+});++test("legacy ?session= links still parse", () => {+ assert.deepEqual(parseDeepLink("", "/", "?session=s1"), { view: null, session: "s1", item: null });});test("chats view with no session yields the bare root", () => {@@ -23,11 +33,11 @@ test("the contexts view carries its open scope", () => {test("a non-root base is prefixed, with or without its trailing slash", () => {assert.equal(deepLinkPath("/web-ui/", "webhooks", null), "/web-ui/webhooks");assert.equal(deepLinkPath("/web-ui/", "crons", null), "/web-ui/crons");- assert.equal(deepLinkPath("/web-ui", "chats", "s1"), "/web-ui/?session=s1");+ assert.equal(deepLinkPath("/web-ui", "chats", "s1"), "/web-ui/s/s1");});test("session ids are URI-encoded", () => {- assert.equal(deepLinkPath("", "chats", "a b&c"), "/?session=a%20b%26c");+ assert.equal(deepLinkPath("", "chats", "a b&c"), "/s/a%20b%26c");});test("parseDeepLink reads the view from the path", () => {@@ -94,6 +104,6 @@ test("only the first two path segments are addressed", () => {});test("sessionLink builds an absolute link under the serving base", () => {- assert.equal(sessionLink("https://portal.example", "/web-ui/", "s1"), "https://portal.example/web-ui/?session=s1");- assert.equal(sessionLink("http://localhost:8096", "", "s1"), "http://localhost:8096/?session=s1");+ assert.equal(sessionLink("https://portal.example", "/web-ui/", "s1"), "https://portal.example/web-ui/s/s1");+ assert.equal(sessionLink("http://localhost:8096", "", "s1"), "http://localhost:8096/s/s1");});diff --git a/plugins/web-ui/test/document-title.test.ts b/plugins/web-ui/test/document-title.test.tsnew file mode 100644index 000000000..1cbf9ec97--- /dev/null+++ b/plugins/web-ui/test/document-title.test.ts@@ -0,0 +1,119 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { JSDOM } from "jsdom";+import { createServer } from "vite";+import { activeSessionForDocumentTitle, documentTitle, PRODUCT_TITLE } from "../src/document-title.ts";++const index = readFileSync(new URL("../index.html", import.meta.url), "utf8");++test("page titles retain the static product title", () => {+ assert.ok(index.includes(`<title>${PRODUCT_TITLE}</title>`));+ assert.equal(documentTitle("chats", "Quarterly planning", true), `Quarterly planning · ${PRODUCT_TITLE}`);+ assert.equal(documentTitle(), PRODUCT_TITLE);+});++test("chat and non-chat views have useful fallbacks", () => {+ assert.equal(documentTitle("chats"), `Chats · ${PRODUCT_TITLE}`);+ assert.equal(documentTitle("chats", null, true), `New chat · ${PRODUCT_TITLE}`);+ assert.equal(documentTitle("contexts"), `Projects · ${PRODUCT_TITLE}`);+ assert.equal(documentTitle("files"), `Files · ${PRODUCT_TITLE}`);+ assert.equal(documentTitle("keychain"), `Keychain · ${PRODUCT_TITLE}`);+});++test("active session selection follows conversation switches and title updates", () => {+ const sessions = [+ { id: "old", threadRef: "old-thread", title: "Old title" },+ { id: "new", threadRef: "new-thread", title: "New title" },+ ];+ const current: { openingKey: string | null; sessionId: string | null; threadRef: string | null } = {+ openingKey: null,+ sessionId: "old",+ threadRef: "old-thread",+ };++ assert.equal(activeSessionForDocumentTitle(sessions, current)?.title, "Old title");+ current.openingKey = "new";+ assert.equal(activeSessionForDocumentTitle(sessions, current)?.title, "New title");+ sessions[1].title = "Server-generated title";+ assert.equal(activeSessionForDocumentTitle(sessions, current)?.title, "Server-generated title");+ current.openingKey = null;+ current.sessionId = "new";+ assert.equal(activeSessionForDocumentTitle(sessions, current)?.title, "Server-generated title");+});++test("document title follows session switches, split-pane focus, and sign-out", async () => {+ const dom = new JSDOM('<!doctype html><div id="app"></div>', { url: "http://localhost/web-ui/" });+ const globals = {+ window: dom.window,+ document: dom.window.document,+ location: dom.window.location,+ history: dom.window.history,+ localStorage: dom.window.localStorage,+ navigator: dom.window.navigator,+ HTMLElement: dom.window.HTMLElement,+ Element: dom.window.Element,+ Node: dom.window.Node,+ Event: dom.window.Event,+ PointerEvent: dom.window.PointerEvent,+ MouseEvent: dom.window.MouseEvent,+ customElements: dom.window.customElements,+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),+ requestAnimationFrame: (callback: FrameRequestCallback) => setTimeout(() => callback(Date.now()), 0),+ cancelAnimationFrame: clearTimeout,+ ResizeObserver: class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ fetch: globalThis.fetch,+ };+ const descriptors = new Map<string, PropertyDescriptor | undefined>();+ for (const [key, value] of Object.entries(globals)) {+ descriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });+ }+ Object.defineProperty(dom.window, "matchMedia", {+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),+ });+ const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });+ try {+ const { appState, signOut, syncDocumentTitle } = await vite.ssrLoadModule("/src/shell.ts");+ const { mainConversation } = await vite.ssrLoadModule("/src/conversations.ts");+ const { sessionsState } = await vite.ssrLoadModule("/src/sessions.ts");+ const { openBackgroundInCanvas, splitInterceptsOpen } = 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];+ appState.me = { user: "tester", org: "test" };+ appState.currentView = "chats";+ appState.mainEl = document.createElement("main");+ document.body.append(appState.mainEl);+ mainConversation().state.sessionId = "old";+ mainConversation().state.threadRef = "web:old";+ syncDocumentTitle();+ assert.equal(document.title, `Old title · ${PRODUCT_TITLE}`);+ mainConversation().state.sessionId = "new";+ mainConversation().state.threadRef = "web:new";+ syncDocumentTitle();+ assert.equal(document.title, `New title · ${PRODUCT_TITLE}`);++ assert.equal(openBackgroundInCanvas(oldSession), true);+ assert.equal(splitInterceptsOpen(newSession), true);+ assert.equal(document.title, `New title · ${PRODUCT_TITLE}`);+ assert.equal(splitInterceptsOpen(oldSession), true);+ assert.equal(document.title, `Old title · ${PRODUCT_TITLE}`);++ globalThis.fetch = async () => new Response(null, { status: 204 });+ await signOut();+ assert.equal(document.title, PRODUCT_TITLE);+ await new Promise((resolve) => setTimeout(resolve, 250));+ } finally {+ await vite.close();+ dom.window.close();+ for (const [key, descriptor] of descriptors) {+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);+ else delete (globalThis as Record<string, unknown>)[key];+ }+ }+});diff --git a/plugins/web-ui/test/session-select.test.ts b/plugins/web-ui/test/session-select.test.tsnew file mode 100644index 000000000..612ce69ca--- /dev/null+++ b/plugins/web-ui/test/session-select.test.ts@@ -0,0 +1,62 @@+import assert from "node:assert/strict";+import test from "node:test";+import { emptySelection, pruneSelection, selectionClick } from "../src/session-select.ts";++const order = ["a", "b", "c", "d", "e"];++test("plain click sets the anchor and clears selection", () => {+ const s = selectionClick(emptySelection(), order, "b", { shift: false, toggle: false });+ assert.deepEqual([...s.ids], []);+ assert.equal(s.anchor, "b");+});++test("shift-click selects the range from the anchor", () => {+ let s = selectionClick(emptySelection(), order, "b", { shift: false, toggle: false });+ s = selectionClick(s, order, "d", { shift: true, toggle: false });+ assert.deepEqual([...s.ids].sort(), ["b", "c", "d"]);+ assert.equal(s.anchor, "b");+});++test("a second shift-click replaces the previous range", () => {+ let s = selectionClick(emptySelection(), order, "b", { shift: false, toggle: false });+ s = selectionClick(s, order, "e", { shift: true, toggle: false });+ s = selectionClick(s, order, "c", { shift: true, toggle: false });+ assert.deepEqual([...s.ids].sort(), ["b", "c"]);+});++test("shift range works upward from the anchor", () => {+ let s = selectionClick(emptySelection(), order, "d", { shift: false, toggle: false });+ s = selectionClick(s, order, "a", { shift: true, toggle: false });+ assert.deepEqual([...s.ids].sort(), ["a", "b", "c", "d"]);+});++test("cmd-click toggles a row and moves the anchor", () => {+ let s = selectionClick(emptySelection(), order, "a", { shift: false, toggle: true });+ s = selectionClick(s, order, "d", { shift: false, toggle: true });+ assert.deepEqual([...s.ids].sort(), ["a", "d"]);+ assert.equal(s.anchor, "d");+ s = selectionClick(s, order, "a", { shift: false, toggle: true });+ assert.deepEqual([...s.ids], ["d"]);+});++test("shift after cmd keeps the cmd-added rows (Finder behavior)", () => {+ let s = selectionClick(emptySelection(), order, "a", { shift: false, toggle: true });+ s = selectionClick(s, order, "c", { shift: false, toggle: true });+ s = selectionClick(s, order, "e", { shift: true, toggle: false });+ assert.deepEqual([...s.ids].sort(), ["a", "c", "d", "e"]);+ s = selectionClick(s, order, "d", { shift: true, toggle: false });+ assert.deepEqual([...s.ids].sort(), ["a", "c", "d"]);+});++test("shift-click with no anchor selects only the clicked row", () => {+ const s = selectionClick(emptySelection(), order, "c", { shift: true, toggle: false });+ assert.deepEqual([...s.ids], ["c"]);+ assert.equal(s.anchor, "c");+});++test("prune drops rows no longer visible", () => {+ let s = selectionClick(emptySelection(), order, "a", { shift: false, toggle: true });+ s = selectionClick(s, order, "b", { shift: false, toggle: true });+ const pruned = pruneSelection(s, new Set(["b", "c"]));+ assert.deepEqual([...pruned.ids], ["b"]);+});diff --git a/plugins/web-ui/test/sessions-refresh-race.test.ts b/plugins/web-ui/test/sessions-refresh-race.test.tsnew file mode 100644index 000000000..6ac9afc10--- /dev/null+++ b/plugins/web-ui/test/sessions-refresh-race.test.ts@@ -0,0 +1,115 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { JSDOM } from "jsdom";+import { createServer } from "vite";+test("superseded session refreshes observe the winning refresh's list", async () => {+ const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main>', {+ url: "http://localhost/web-ui/",+ });+ Object.defineProperty(dom.window, "matchMedia", {+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),+ });+ const globals = {+ window: dom.window,+ document: dom.window.document,+ location: dom.window.location,+ history: dom.window.history,+ localStorage: dom.window.localStorage,+ navigator: dom.window.navigator,+ HTMLElement: dom.window.HTMLElement,+ customElements: dom.window.customElements,+ Node: dom.window.Node,+ Event: dom.window.Event,+ requestAnimationFrame: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),+ cancelAnimationFrame: clearTimeout,+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),+ };+ for (const [key, value] of Object.entries(globals))+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });++ const sessionA = {+ id: "sess-a",+ threadRef: "web:alice:aaa",+ scopeId: "personal:alice",+ title: "Optimize QM webapp",+ };+ const pending: Array<(r: Response) => void> = [];+ globalThis.fetch = async (input) => {+ const path = String(input);+ if (path === "/api/sessions") return new Promise<Response>((resolve) => pending.push(resolve));+ if (path === "/api/contexts") return Response.json({ contexts: [] });+ throw new Error(`Unexpected request: ${path}`);+ };++ const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });+ try {+ const { appState } = await vite.ssrLoadModule("/src/shell-state.ts");+ const { sessionsState, sessionsReady, refreshSessions } = await vite.ssrLoadModule("/src/sessions.ts");+ appState.me = { user: "alice", org: "acme" };+ const boot = refreshSessions({ silent: true });+ const pane1 = (async () => {+ const refreshed = await refreshSessions({ silent: true });+ return { refreshed, found: sessionsState.list.some((s: { id: string }) => s.id === sessionA.id) };+ })();+ const pane2 = refreshSessions({ silent: true });++ let ready = false;+ const readiness = sessionsReady().then(() => {+ ready = true;+ });++ assert.equal(pending.length, 3, "three /api/sessions requests in flight");+ const body = () => Response.json({ sessions: [sessionA] });+ pending[0]!(body());+ pending[1]!(body());+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.equal(ready, false, "sessionsReady() must wait for a winning refresh");+ pending[2]!(body());+ assert.equal(await pane2, true, "the winning refresh reports success");+ assert.equal(await boot, true, "a superseded refresh resolves with the winner's outcome");+ const p1 = await pane1;+ assert.equal(p1.refreshed, true);+ assert.equal(p1.found, true, "a superseded awaiter sees the session — no empty read-only stub");+ await readiness;+ assert.ok(sessionsState.list.some((s: { id: string }) => s.id === sessionA.id));+ } finally {+ await vite.close();+ }+});++test("a failed lone refresh still settles sessionsReady and reports the error path", async () => {+ const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main>', {+ url: "http://localhost/web-ui/",+ });+ Object.defineProperty(dom.window, "matchMedia", {+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),+ });+ for (const [key, value] of Object.entries({+ window: dom.window,+ document: dom.window.document,+ location: dom.window.location,+ history: dom.window.history,+ localStorage: dom.window.localStorage,+ navigator: dom.window.navigator,+ HTMLElement: dom.window.HTMLElement,+ customElements: dom.window.customElements,+ Node: dom.window.Node,+ Event: dom.window.Event,+ requestAnimationFrame: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),+ cancelAnimationFrame: clearTimeout,+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),+ }))+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });+ globalThis.fetch = async (input) => {+ if (String(input) === "/api/contexts") return Response.json({ contexts: [] });+ throw new Error("network down");+ };+ const vite = await createServer({ server: { middlewareMode: true, hmr: false }, appType: "custom" });+ try {+ const { sessionsReady, refreshSessions } = await vite.ssrLoadModule("/src/sessions.ts");+ assert.equal(await refreshSessions({ silent: true }), false);+ await sessionsReady();+ } finally {+ await vite.close();+ }+});diff --git a/plugins/web-ui/test/split-canvas-entry.test.ts b/plugins/web-ui/test/split-canvas-entry.test.tsindex 183a549cd..b25769aa7 100644--- a/plugins/web-ui/test/split-canvas-entry.test.ts+++ b/plugins/web-ui/test/split-canvas-entry.test.ts@@ -60,31 +60,17 @@ test("a pane is an element in this document — never a second copy of the app",});test("a conversation dropped on a pane's tab strip joins that pane — and only there", () => {- const accept = split.match(/api\.onUnhandledDragOver\(\(e\) => \{[\s\S]*?\n {2}\}\);/)?.[0] ?? "";- assert.ok(accept, "onUnhandledDragOver not wired");- assert.match(accept, /sessionDrag && \(e\.target === "tab" \|\| e\.target === "header_space"\)/);- assert.doesNotMatch(accept, /"content"|"edge"/);-- const drop = split.match(/api\.onDidDrop\(\(e\) => \{[\s\S]*?\n {2}\}\);/)?.[0] ?? "";- assert.ok(drop, "onDidDrop not wired");- assert.match(drop, /tabIntoPane\(anchor\.id, \{ sessionId: drag\.sessionId, threadRef: drag\.threadRef \}/);- assert.match(drop, /focusExistingPane\(drag\.sessionId\)/, "a conversation already on screen is focused, not cloned");- assert.match(drop, /endSessionDrag\(\);/, "the zone overlays must come down with the drag");-- assert.match(accept, /if \(sessionDrag/, "only a live session drag may be accepted");-});--test("a strip drop lands where a dragged pane header would, not merely at the end", () => {- const drop = fn(split, "buildDock");- assert.match(drop, /e\.panel \? e\.group\?\.panels\.indexOf\(e\.panel\) : undefined/);- assert.match(drop, /tabIntoPane\([\s\S]{0,120}at === -1 \? undefined : at\)/);-- const into = fn(split, "tabIntoPane");- assert.match(into, /index\?: number/, "tabIntoPane must accept an insertion index");- assert.match(into, /direction: "within"/);- assert.match(into, /index === undefined \? \{\} : \{ index \}/, "and forward it to addPane");- const add = fn(split, "addPane");- assert.match(add, /index\?: number/, "addPane must pass dockview its own position.index");+ const strip = split.match(/^class StripDrop[\s\S]*?\n\}/m)?.[0] ?? "";+ assert.ok(strip, "StripDrop not wired");+ assert.match(split, /createPrefixHeaderActionComponent: \(\) => new StripDrop\(\)/);+ assert.match(strip, /tabIntoPane\(anchor\.id, \{ sessionId: drag\.sessionId, threadRef: drag\.threadRef \}\)/);+ assert.match(+ strip,+ /focusExistingPane\(drag\.sessionId\)/,+ "a conversation already on screen is focused, not cloned",+ );+ assert.match(strip, /endSessionDrag\(\);/, "the zone overlays must come down with the drag");+ assert.match(strip, /stripJoinable\(\)/, "only a live session drag that would really add a tab");});test("the pane body no longer offers a tab zone", () => {diff --git a/plugins/web-ui/test/split-drop-legitimacy.test.ts b/plugins/web-ui/test/split-drop-legitimacy.test.tsindex db9a558ad..bdc682e65 100644--- a/plugins/web-ui/test/split-drop-legitimacy.test.ts+++ b/plugins/web-ui/test/split-drop-legitimacy.test.ts@@ -20,14 +20,14 @@ test("a pane only offers the drops that will really happen", () => {});test("the tab strips light up as targets from the moment the drag starts", () => {- const refresh = split.match(/^function refreshSessionDrag\([\s\S]*?\n\}/m)?.[0] ?? "";- assert.ok(refresh, "refreshSessionDrag not found");+ const joinable = split.match(/^function stripJoinable\([\s\S]*?\n\}/m)?.[0] ?? "";+ assert.ok(joinable, "stripJoinable not found");assert.match(- refresh,+ joinable,/!paneShowing\(drag\.sessionId\) && \(dockApi\?\.panels\.length \?\? 0\) < MAX_PANES/,"but only when a strip drop would really add a tab",);- assert.match(refresh, /classList\.toggle\("session-dragging", addsTab\)/);+ assert.match(split, /classList\.toggle\("session-dragging", stripJoinable\(\)\)/);assert.match(split, /classList\.remove\("session-dragging"\)/);assert.match(css, /\.split-canvas\.session-dragging \.dv-tabs-and-actions-container \{/);});@@ -46,3 +46,27 @@ test("session drags always target the canvas — there is no single-view handoffassert.match(begin, /refreshSessionDrag\(\);/);assert.doesNotMatch(split, /showSingleDropOverlay|currentChatParams|activateCanvas/);});++test("the highlighted strip is a real drop target, not just a glow", () => {+ const strip = split.match(/^class StripDrop[\s\S]*?\n\}/m)?.[0] ?? "";+ assert.ok(strip, "StripDrop not found");+ assert.match(split, /createPrefixHeaderActionComponent: \(\) => new StripDrop\(\)/, "dockview owns its lifecycle");+ assert.match(strip, /zoneTpl\("center", "Open as tab"/, "the strip offers an explicit join target");+ assert.match(strip, /tabIntoPane\(anchor\.id/, "dropping on the strip really adds a tab");+ assert.match(strip, /stripJoinable\(\)/, "and only when that drop would really add a tab");+ const end = split.match(/^export function endSessionDrag\([\s\S]*?\n\}/m)?.[0] ?? "";+ assert.match(end, /drawStripDrops\(\)/, "zones vanish when the drag ends");+ assert.match(css, /\.strip-zones \{/, "the overlay is styled");+});++test("native tab drags advertise every pane as a target from drag start", () => {+ assert.match(split, /api\.onWillDragPanel\(\(\) => beginTabDragHint\(\)\);/);+ assert.match(split, /api\.onWillDragGroup\(\(\) => beginTabDragHint\(\)\);/);+ const hint = split.match(/^function beginTabDragHint\([\s\S]*?\n\}/m)?.[0] ?? "";+ assert.ok(hint, "beginTabDragHint not found");+ assert.match(hint, /classList\.add\("tab-dragging"\)/);+ assert.match(hint, /classList\.remove\("tab-dragging"\)/, "the hint clears when the drag ends");+ assert.match(hint, /addEventListener\("dragend"/, "cleared on dragend");+ assert.match(hint, /addEventListener\("drop"/, "and on drop");+ assert.match(css, /\.split-canvas\.tab-dragging \.dv-groupview \{/, "the target styling exists");+});diff --git a/plugins/web-ui/test/split-layout.test.ts b/plugins/web-ui/test/split-layout.test.tsindex 6f30ac70e..0c5d674d4 100644--- a/plugins/web-ui/test/split-layout.test.ts+++ b/plugins/web-ui/test/split-layout.test.ts@@ -41,8 +41,8 @@ test("v1PaneSeeds normalizes non-string ids to null", () => {test("a conversation can be dropped onto a pane's tab strip to become a tab", () => {const splitTs = readFileSync(new URL("../src/split.ts", import.meta.url), "utf8");- assert.match(splitTs, /e\.target === "tab" \|\| e\.target === "header_space"/, "no strip drop target");- assert.match(splitTs, /api\.onDidDrop\(\(e\) => \{[\s\S]*?tabIntoPane\(/, "the strip drop must join the pane");+ assert.match(splitTs, /class StripDrop implements IHeaderActionsRenderer/, "no strip drop target");+ assert.match(splitTs, /^class StripDrop[\s\S]*?tabIntoPane\(/m, "the strip drop must join the pane");const edges = new Set([...splitTs.matchAll(/zoneTpl\("([a-z]+)"/g)].map((m) => m[1]));assert.deepEqual(edges,diff --git a/plugins/web-ui/test/tab-archive-button.test.ts b/plugins/web-ui/test/tab-archive-button.test.tsnew file mode 100644index 000000000..dd3dd53c5--- /dev/null+++ b/plugins/web-ui/test/tab-archive-button.test.ts@@ -0,0 +1,52 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++const read = (f: string): string => readFileSync(new URL(`../src/${f}`, import.meta.url), "utf8");+const split = read("split.ts");+const sessions = read("sessions.ts");++const fn = (src: string, name: string): string => {+ const body = src.match(new RegExp(`^(?:export )?(?:async )?function ${name}\\([\\s\\S]*?\\n\\}`, "m"))?.[0] ?? "";+ assert.ok(body, `${name} not found`);+ return body;+};++test("a tab offers an archive button beside close, for real sessions only", () => {+ const btn = split.match(/this\.inStrip && sessionId[\s\S]*?split-tab-archive[\s\S]*?<\/button>`/)?.[0] ?? "";+ assert.ok(btn, "archive button must render only in the tab strip and only when the pane shows a session");+ assert.match(btn, /archiveSessionById\(sessionId\)/, "click archives the pane's session");+ assert.match(btn, /e\.stopPropagation\(\)/, "click must not also activate the tab");+ assert.match(+ btn,+ /@pointerdown=\$\{\(e: Event\) => e\.stopPropagation\(\)\}/,+ "pointerdown must not activate an inactive tab before the archive click lands",+ );+ assert.ok(+ split.indexOf("split-tab-archive") < split.indexOf('title="Close pane"'),+ "archive sits before (next to) the close button",+ );+});++test("archiveSessionById routes through setArchived so surfaces close and Recents updates at once", () => {+ const body = fn(sessions, "archiveSessionById");+ assert.match(body, /sessionsState\.list\.find/, "resolves the session from the live list");+ assert.match(body, /if \(s && !s\.archived\)/, "idempotent — never double-archives a listed session");+ assert.match(body, /setArchived\(s, true\);/, "reuses the one archive path (optimistic list patch + surface close)");+ assert.match(body, /closeSessionSurfaces\(sessionId\);/, "still closes the pane when the list can't help");+ assert.match(+ body,+ /if \(!s\) void persistSessionPatch\(sessionId, \{ archived: true \}\);/,+ "archives by id when the session is not in the list yet",+ );+});++test("a lone tab keeps its archive button even though its close yields to the group header", () => {+ const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");+ const hide = css.indexOf(".dv-single-tab .split-tab-close");+ const keep = css.indexOf(".dv-single-tab .split-tab-archive");+ assert.ok(hide !== -1 && keep !== -1, "both single-tab rules exist");+ assert.ok(keep > hide, "the archive exemption must come after (and defeat) the hide rule");+ const rule = css.slice(keep, css.indexOf("}", keep));+ assert.match(rule, /display: inline-flex/);+});