Multiplayer agent harness for work.
Add a per-user option to open the web UI on a new chat (#2012)
Joshua France981daeb81ec1
diff --git a/plugins/web-ui/src/settings.ts b/plugins/web-ui/src/settings.tsindex 36c8593f6..ae1df7956 100644--- a/plugins/web-ui/src/settings.ts+++ b/plugins/web-ui/src/settings.ts@@ -1,7 +1,7 @@import "./onboarding-welcome";import "./slack-account";import { openModelConnectManager, type StatusResponse } from "./model-connect";-import { api, withBase } from "./core-bridge";+import { api, fetchUiState, putUiState, withBase } from "./core-bridge";import { html, nothing, render, type TemplateResult } from "lit";import { Download, ExternalLink, LogOut, Monitor, Moon, ShieldUser, Sun, type IconNode } from "lucide";import { icon } from "./ui";@@ -230,6 +230,70 @@ function themeRow(): TemplateResult {`;}+const OPEN_NEW_CHAT_KEY = "open-new-chat";+let openNewChat = false;+let openNewChatTouched = false;++export async function loadOpenNewChat(timeoutMs = 2000): Promise<boolean> {+ const fetched = fetchUiState(OPEN_NEW_CHAT_KEY).then(+ (rec) => {+ if (!openNewChatTouched) {+ openNewChat = rec.value === true;+ drawSettings();+ }+ return openNewChat;+ },+ () => null,+ );+ let timer = 0;+ const value = await Promise.race([+ fetched,+ new Promise<null>((resolve) => {+ timer = window.setTimeout(() => resolve(null), timeoutMs);+ }),+ ]);+ window.clearTimeout(timer);+ return value ?? false;+}++function setOpenNewChat(value: boolean): void {+ openNewChatTouched = true;+ openNewChat = value;+ drawSettings();+ void putUiState(OPEN_NEW_CHAT_KEY, value, Date.now()).catch(() => void 0);+}++const OPEN_OPTIONS: Array<{ newChat: boolean; label: string }> = [+ { newChat: false, label: "Last session" },+ { newChat: true, label: "New chat" },+];++function openBehaviorRow(): TemplateResult {+ return html`+ <div class="settings-row">+ <div class="settings-row-copy">+ <div class="settings-row-title">When QM opens</div>+ <div class="settings-row-note">Reopen the conversations you had open last time, or start on a new chat.</div>+ </div>+ <div class="settings-choice" role="radiogroup" aria-label="When QM opens">+ ${OPEN_OPTIONS.map(+ (option) => html`+ <button+ class="settings-choice-option ${openNewChat === option.newChat ? "selected" : ""}"+ type="button"+ role="radio"+ aria-checked=${openNewChat === option.newChat ? "true" : "false"}+ @click=${() => setOpenNewChat(option.newChat)}+ >+ <span>${option.label}</span>+ </button>+ `,+ )}+ </div>+ </div>+ `;+}+const SURFACE_OPTIONS: Array<{ webOnly: boolean; label: string }> = [{ webOnly: false, label: "All conversations" },{ webOnly: true, label: "Web only" },@@ -425,8 +489,8 @@ function settingsPane(): TemplateResult {<h1 class="pane-title">Settings</h1></div><div class="settings-group">- ${aiAccountsRow()} ${themeRow()} ${sidebarSurfaceRow()} ${can("admin") ? adminRow() : nothing} ${desktopRow()}- ${accountRow()}+ ${aiAccountsRow()} ${themeRow()} ${openBehaviorRow()} ${sidebarSurfaceRow()}+ ${can("admin") ? adminRow() : nothing} ${desktopRow()} ${accountRow()}<div class="settings-row settings-slack-account"><qm-slack-account .user=${`${appState.me?.org}:${appState.me?.user}`}></qm-slack-account></div>diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex 625e10830..b93a15270 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -105,7 +105,7 @@ import {} from "./inbox";import { openSkillById, renderSkills, resetActiveSkill, routeSkillsHistory } from "./skills";import { watchAppAnnotations } from "./app-annotations";-import { applyTheme, renderSettings, watchSystemTheme } from "./settings";+import { applyTheme, renderSettings, loadOpenNewChat, watchSystemTheme } from "./settings";import { contextsState, ensureContexts, renderContexts, resetContextsState, resolveProjectScope } from "./contexts";import { appState, can, canView, isView, type AuthMode, type Me, type View } from "./shell-state";import { trapDialogFocus } from "./dialog-focus";@@ -1088,6 +1088,7 @@ export async function boot(): Promise<void> {const approvalsPrefetch = linkedId ? fetchSessionApprovals(linkedId) : null;const runtimeConfigFetch = fetchRuntimeConfig();const remoteSplitFetch = fetchRemoteSplit();+ const openNewChatFetch = loadOpenNewChat();let r: Response;try {@@ -1135,8 +1136,9 @@ export async function boot(): Promise<void> {const connectedProvider = params.get("status") === "connected" ? params.get("connector") : null;if (connectedProvider) markConnectorConnected(connectedProvider);const viewIntent = isView(wanted) && canView(wanted) && wanted !== "chats";- loadPersistedSplit();- if (!wantedSession && wanted !== "app-edit" && prefill === null) {+ const restoreLast = viewIntent || !(await openNewChatFetch);+ if (restoreLast) loadPersistedSplit();+ if (restoreLast && !wantedSession && wanted !== "app-edit" && prefill === null) {const restore = adoptRemoteSplit(remoteSplitFetch).then(async () => {if (viewIntent && restoredCanvasNeedsSessionList()) await sessions;});@@ -1148,7 +1150,7 @@ export async function boot(): Promise<void> {}const bareEntry = !viewIntent && !wantedSession && wanted !== "app-edit" && !connectedProvider;- if (bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas(true);+ if (restoreLast && bareEntry && !restoredCanvasNeedsSessionList()) mountRestoredCanvas(true);if (wantedSession && !viewIntent && wanted !== "app-edit") {const transcript = entriesPrefetch ?? loadLinkedTranscript(wantedSession);@@ -1218,7 +1220,7 @@ export async function boot(): Promise<void> {const recent = [...sessionsState.list].sort((a, b) => activityOf(b) - activityOf(a))[0]!;exitSplitIfActive();await openSession(recent);- } else if (!mountRestoredCanvas() && !mainConversation().state.threadRef) {+ } else if (!(restoreLast && mountRestoredCanvas()) && !mainConversation().state.threadRef) {mainConversation().newChat();}}diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.tsindex 8a3b03444..2019bd485 100644--- a/plugins/web-ui/test/deep-link-boot-fixture.ts+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts@@ -45,6 +45,7 @@ interface HarnessOptions {connectionReturn?: boolean;slackReturn?: "success" | "expired" | "cancelled" | "wrong-account";returnWidget?: string;+ openNewChat?: boolean;}export const SESSION = {@@ -151,6 +152,9 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {upgradeAvailable: false,});}+ if (path.startsWith("/api/ui-state?key=open-new-chat")) {+ return Response.json({ value: opts.openNewChat ?? null, updatedAt: opts.openNewChat ? 1 : 0 });+ }if (path.startsWith("/api/ui-state")) {if (opts.holdRemoteSplit) await remoteSplitHeld;return Response.json({ value: opts.remoteCanvas ?? null, updatedAt: opts.remoteCanvas ? 1 : 0 });diff --git a/plugins/web-ui/test/open-to-new-chat.test.ts b/plugins/web-ui/test/open-to-new-chat.test.tsnew file mode 100644index 000000000..cc5785922--- /dev/null+++ b/plugins/web-ui/test/open-to-new-chat.test.ts@@ -0,0 +1,61 @@+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");++test("opening the app restores the last session unless the person opted into a new chat", () => {+ const shell = read("shell.ts");+ const boot = shell.slice(shell.indexOf("const remoteSplitFetch = fetchRemoteSplit();"));+ assert.match(boot, /const restoreLast = viewIntent \|\| !\(await openNewChatFetch\);/);+ assert.match(boot, /if \(restoreLast\) loadPersistedSplit\(\);/, "the saved layout is only adopted when restoring");+ assert.match(+ boot,+ /if \(restoreLast && bareEntry && !restoredCanvasNeedsSessionList\(\)\) mountRestoredCanvas\(true\);/,+ );+ assert.match(+ boot,+ /\} else if \(!\(restoreLast && mountRestoredCanvas\(\)\) && !mainConversation\(\)\.state\.threadRef\) \{\s*mainConversation\(\)\.newChat\(\);/,+ );+ assert.doesNotMatch(boot, /^ {2}loadPersistedSplit\(\);$/m, "no unconditional layout restore on open");+});++test("the open setting is stored per user and defaults to the last session", () => {+ const settings = read("settings.ts");+ assert.match(settings, /openNewChat = rec\.value === true;/);+ assert.match(settings, /putUiState\(OPEN_NEW_CHAT_KEY/);+ assert.doesNotMatch(settings, /localStorage\.\w+\(OPEN_NEW_CHAT_KEY/);+ assert.match(settings, /\$\{openBehaviorRow\(\)\}/);+ assert.match(settings, /\{ newChat: false, label: "Last session" \}/);+});++test("opting into a new chat skips the saved multiview layout on a bare visit", async () => {+ const { harness } = await import("./deep-link-boot-fixture.ts");+ const h = await harness({ path: "/", savedCanvas: true, openNewChat: true });+ try {+ const saved = localStorage.getItem("web-ui:split-canvas:v1");+ h.releaseSessions();+ await h.boot();+ await new Promise((resolve) => setTimeout(resolve, 200));+ assert.equal(localStorage.getItem("web-ui:split-canvas:v1"), saved, "the saved layout survives for a later opt-in");+ assert.equal(document.querySelectorAll(".split-pane-content").length, 0);+ assert.doesNotMatch(h.visibleConversation().state.threadRef ?? "", /old-a|old-b/);+ assert.doesNotMatch(h.mainText(), /old-a|old-b/);+ } finally {+ await h.close();+ }+});++test("by default the saved multiview layout reopens", async () => {+ const { harness } = await import("./deep-link-boot-fixture.ts");+ const h = await harness({ path: "/", savedCanvas: true });+ try {+ h.releaseSessions();+ await h.boot();+ for (let i = 0; i < 200 && document.querySelectorAll(".split-pane-content").length < 2; i++)+ await new Promise((resolve) => setTimeout(resolve, 10));+ assert.equal(document.querySelectorAll(".split-pane-content").length, 2);+ } finally {+ await h.close();+ }+});diff --git a/plugins/web-ui/test/split-canvas-entry.test.ts b/plugins/web-ui/test/split-canvas-entry.test.tsindex 1d48673b8..ae97c7692 100644--- a/plugins/web-ui/test/split-canvas-entry.test.ts+++ b/plugins/web-ui/test/split-canvas-entry.test.ts@@ -120,7 +120,9 @@ 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(true);");+ const early = boot.indexOf(+ "if (restoreLast && 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");@@ -132,7 +134,7 @@ test("boot mounts a restored canvas before it awaits the session list", () => {assert.match(boot.slice(listAwait),- /\} else if \(!mountRestoredCanvas\(\) && !mainConversation\(\)\.state\.threadRef\) \{/,+ /\} else if \(!\(restoreLast && mountRestoredCanvas\(\)\) && !mainConversation\(\)\.state\.threadRef\) \{/,);const mount = fn(split, "mountRestoredCanvas");assert.match(mount, /if \(isPhone\(\) \|\| \(restoreOnly && !splitState\.active\)\) return false;/);@@ -143,7 +145,10 @@ test("boot's fallback never replaces a chat the user mounted during the wait", (const boot = shell.match(/export async function boot\(\): Promise<void> \{[\s\S]*?\n\}/)?.[0] ?? "";const listAwait = boot.lastIndexOf("await sessions;");const tail = boot.slice(listAwait);- assert.match(tail, /\} else if \(!mountRestoredCanvas\(\) && !mainConversation\(\)\.state\.threadRef\) \{/);+ assert.match(+ tail,+ /\} else if \(!\(restoreLast && mountRestoredCanvas\(\)\) && !mainConversation\(\)\.state\.threadRef\) \{/,+ );const guard = tail.indexOf("!mainConversation().state.threadRef");const mint = tail.indexOf("newChat();", guard);assert.ok(guard > 0 && mint > guard, "the guard must gate the mint, not follow it");