Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

fix: unify new chat placement across entry points

Joshua France11d809bd96cd
diff --git a/plugins/web-ui/src/contexts.ts b/plugins/web-ui/src/contexts.ts
index a35293ff7..06455c4bf 100644
--- a/plugins/web-ui/src/contexts.ts
+++ b/plugins/web-ui/src/contexts.ts
@@ -29,7 +29,7 @@ import { UI_BASE } from "./deep-link";
import { errMessage } from "../../chassis/src/errors";
import { actionSnippet, closeFormMenus, fieldSelect, formatBytes, icon, initials, relTime, toggleFormMenu } from "./ui";
import { appState, replacePanePreservingFocus, switchView, syncUrlFromState } from "./shell";
-import { mainConversation } from "./conversations";
+import { startNewChat } from "./sessions";
import { groupDmTitle, openSession, refreshSessions, sessionsState, slackLogo, surfaceOf } from "./sessions";
import { activityOf } from "./session-list";
import type { WebhookView } from "./webhooks";
@@ -1463,7 +1463,7 @@ function selectContext(scopeId: string | null): void {
}
function startChatIn(c: CoreContext): void {
- mainConversation().newChat(c.kind === "personal" ? undefined : { scopeId: c.scopeId, name: c.name });
+ startNewChat(c.kind === "personal" ? null : c.scopeId, c.name);
}
async function openFromContext(s: CoreSession): Promise<void> {
diff --git a/plugins/web-ui/src/crons.ts b/plugins/web-ui/src/crons.ts
index 3bd78c3ba..1061ae5ee 100644
--- a/plugins/web-ui/src/crons.ts
+++ b/plugins/web-ui/src/crons.ts
@@ -7,7 +7,7 @@ import { listBackLink, listPageTpl } from "./list-page";
import { contextsState, ensureContexts, scopeChip } from "./contexts";
import { scopedSession, scopedViewTopbar } from "./session-scope";
import { appState } from "./shell";
-import { mainConversation } from "./conversations";
+import { startNewChat } from "./sessions";
import { deepLinkPath, isPlainLeftClick, UI_BASE } from "./deep-link";
import {
cronNextFire,
@@ -755,9 +755,8 @@ async function saveCronEdit(event: SubmitEvent, c: CronView): Promise<void> {
function editCronWithAgent(c: CronView): void {
cronDialog = null;
- const conv = mainConversation();
- conv.newChat();
- void conv.state.agent?.prompt(
+ const conv = startNewChat();
+ void conv?.state.agent?.prompt(
userSendMessage(
`Help me edit cron ${c.id} ("${cronTitle(c)}"). Its current schedule is ${cronScheduleSummary(c)}. Ask what I want changed, then update its task, schedule, timezone, destination, or run mode as requested.`,
),
@@ -845,9 +844,8 @@ function onCreateCron(e: Event): void {
if (errSlot) errSlot.textContent = "Describe the cron you want.";
return;
}
- const conv = mainConversation();
- conv.newChat();
- void conv.state.agent?.prompt(
+ const conv = startNewChat();
+ void conv?.state.agent?.prompt(
userSendMessage(
`Set up a cron for me: ${text}\n\n(Sent from the web UI's New-cron pane: create it now with your scheduling API, use a calendar schedule with timezone for daily/weekly/monthly timing, give it a 2-5 word title naming what the cron is for and distinctive in a list, like "Gmail unread digest" or "GitLab CI watch", not the command and not a generic word, and confirm what you created.)`,
),
diff --git a/plugins/web-ui/src/search.ts b/plugins/web-ui/src/search.ts
index de8def7b0..eeb565c14 100644
--- a/plugins/web-ui/src/search.ts
+++ b/plugins/web-ui/src/search.ts
@@ -8,7 +8,7 @@
import { html, nothing, render, type TemplateResult } from "lit";
import { CornerDownLeft, Search } from "lucide";
import { api, userSendMessage, type CoreSession } from "./core-bridge";
-import { mainConversation } from "./conversations";
+import { startNewChat } from "./sessions";
import { recencyGroup } from "./session-list";
import { searchGroup } from "./search-group";
import { slackWireToPlain, stripSlackDirectives } from "./slack-text";
@@ -205,9 +205,8 @@ function askQm(): void {
const q = searchState.query.trim();
if (!q) return;
closeChatSearch();
- const conv = mainConversation();
- conv.newChat();
- void conv.state.agent?.prompt(
+ const conv = startNewChat();
+ void conv?.state.agent?.prompt(
userSendMessage(
`Find my previous session based on the following search query, give me a link when you've identified it: ${q}`,
),
diff --git a/plugins/web-ui/src/sessions.ts b/plugins/web-ui/src/sessions.ts
index 534bd01ba..5211957c3 100644
--- a/plugins/web-ui/src/sessions.ts
+++ b/plugins/web-ui/src/sessions.ts
@@ -87,7 +87,7 @@ import {
import { allConversations, isLiveConversation, mainConversation } from "./conversations";
import type { Conversation } from "./conv-types";
import {
- addBlankPane,
+ startNewChatInCanvas,
beginSessionDrag,
endPaneDrag,
notifyPanesChanged,
@@ -453,11 +453,18 @@ function toggleRecentProject(scopeId: string): void {
renderList();
}
-export function startNewChat(scopeId: string | null, name: string | null): void {
+export function startNewChat(
+ scopeId: string | null = null,
+ name: string | null = null,
+ threadRef?: string,
+): Conversation | null {
closeSidebarOnNarrowView();
if (scopeId) sessionsState.collapsedProjectScopes.delete(scopeId);
- if (addBlankPane(scopeId ?? undefined)) return;
- addPendingSession(mainConversation().newChat(scopeId ? { scopeId, name } : undefined), scopeId, name);
+ if (splitState.active) return startNewChatInCanvas(scopeId ?? undefined, threadRef);
+ const conv = mainConversation();
+ if (threadRef) conv.mountContinuable(threadRef, null, scopeId, [], name);
+ else addPendingSession(conv.newChat(scopeId ? { scopeId, name } : undefined), scopeId, name);
+ return conv;
}
export function startNewChatInLastScope(): void {
@@ -564,7 +571,7 @@ export function drawChatsPage(): void {
chatsPageScope = s;
drawChatsPage();
},
- action: { label: "New chat", onClick: () => mainConversation().newChat() },
+ action: { label: "New chat", onClick: () => startNewChat() },
search: {
value: chatsPageQuery,
placeholder: "Search chats…",
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index d24a8e4ef..38c705c89 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -71,6 +71,7 @@ import {
sessionSelectionBar,
revealSessionSurface,
startNewChatInLastScope,
+ startNewChat,
} from "./sessions";
import { openCronById, renderCronsPage, resetActiveCron, routeCronsHistory } from "./crons";
import { renderLoopsPage, resetActiveLoop } from "./loops";
@@ -919,7 +920,7 @@ function openAppEditChat(slug: string): void {
return;
}
if (!storedDraft(threadRef)) saveDraft(threadRef, `Update my deployed app "${slug}": `);
- mainConversation().mountContinuable(threadRef, null, null, []);
+ startNewChat(null, null, threadRef);
renderList();
}
diff --git a/plugins/web-ui/src/split.ts b/plugins/web-ui/src/split.ts
index e680d3ea4..39095d3e5 100644
--- a/plugins/web-ui/src/split.ts
+++ b/plugins/web-ui/src/split.ts
@@ -344,17 +344,6 @@ function seedFromV1(api: DockviewApi, seeds: PaneSeed[]): void {
persist();
}
-function largestGroupPanel(api: DockviewApi): { panel: IDockviewPanel; wide: boolean } | null {
- let best: { panel: IDockviewPanel; area: number; wide: boolean } | null = null;
- for (const group of api.groups) {
- const r = group.element.getBoundingClientRect();
- const panel = group.activePanel ?? group.panels[0];
- if (!panel) continue;
- if (!best || r.width * r.height > best.area) best = { panel, area: r.width * r.height, wide: r.width >= r.height };
- }
- return best && { panel: best.panel, wide: best.wide };
-}
-
export function activateCanvas(first: PaneParams, second: PaneParams, edge: SplitEdge): void {
if (isPhone()) return;
mainConversation().teardown();
@@ -623,16 +612,24 @@ function tabIntoPane(paneId: string, params: PaneParams, index?: number): boolea
return true;
}
-export function addBlankPane(scopeId?: string): boolean {
- if (!splitState.active || !dockApi) return false;
+export function startNewChatInCanvas(scopeId?: string, threadRef?: string): Conversation | null {
+ if (!splitState.active || !dockApi) return null;
if (appState.currentView !== "chats") switchView("chats");
- if (!ensureCanvas() || !dockApi) return false;
- const at = largestGroupPanel(dockApi);
- if (!at) return false;
- const capped = dockApi.groups.length >= MAX_TILES;
- const target = (capped ? dockApi.activePanel : null) ?? at.panel;
- splitPane(target.id, at.wide ? "right" : "bottom", scopeId ? { scopeId } : {});
- return true;
+ if (!ensureCanvas() || !dockApi) return null;
+ const target = dockApi.activePanel ?? dockApi.panels[0];
+ if (!target) return null;
+ const replace = dockApi.panels.length === 1 || dockApi.panels.length >= MAX_PANES;
+ const tile = !replace && dockApi.groups.length > 1 && dockApi.groups.length < MAX_TILES;
+ const { width, height } = target.group.element.getBoundingClientRect();
+ const direction = width >= height ? "right" : "below";
+ const fresh = addPane(
+ { ...(scopeId ? { scopeId } : {}), ...(threadRef ? { threadRef } : {}) },
+ { referencePanel: target.id, direction: tile ? direction : "within" },
+ );
+ if (replace) dockApi.removePanel(target);
+ fresh.api.setActive();
+ persist();
+ return paneContents.get(fresh.id)?.conversation ?? null;
}
function paneSplitWithBlank(panel: IDockviewPanel): void {
@@ -1084,6 +1081,10 @@ class PaneContent implements IContentRenderer {
const wanted =
sessionId ?? (threadRef ? (sessionsState.list.find((s) => s.threadRef === threadRef)?.id ?? null) : null);
if (!wanted) {
+ if (threadRef) {
+ conversation.mountContinuable(threadRef, null, scopeId ?? null, []);
+ return;
+ }
const context = scopeId ? contextsState.list.find((c) => c.scopeId === scopeId) : undefined;
conversation.newChat(context ? { scopeId: context.scopeId, name: context.name ?? null } : undefined);
return;
diff --git a/plugins/web-ui/test/new-chat-placement.test.ts b/plugins/web-ui/test/new-chat-placement.test.ts
new file mode 100644
index 000000000..79e8943a1
--- /dev/null
+++ b/plugins/web-ui/test/new-chat-placement.test.ts
@@ -0,0 +1,200 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { JSDOM } from "jsdom";
+import { createServer } from "vite";
+
+interface Canvas {
+ panes: () => number;
+ tiles: () => number;
+ newChat: () => boolean;
+ seededChat: (threadRef?: string) => { state: { threadRef: string | null; agent: unknown } } | null;
+ split: () => void;
+ switchAway: () => void;
+}
+
+async function withCanvas(run: (canvas: Canvas) => void | Promise<void>, stacked = false): Promise<void> {
+ 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: async () =>
+ Response.json({
+ approvedHarnesses: ["pi"],
+ modelsByHarness: { pi: [] },
+ modelCatalog: {},
+ fastModeModelIds: [],
+ interactiveFastMode: false,
+ effective: { harnessId: "pi", modelId: "" },
+ sessions: [],
+ items: [],
+ }),
+ };
+ 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 } = await vite.ssrLoadModule("/src/shell.ts");
+ const split = await vite.ssrLoadModule("/src/split.ts");
+ const sessions = await vite.ssrLoadModule("/src/sessions.ts");
+ appState.me = { user: "tester", org: "test" };
+ appState.currentView = "chats";
+ appState.mainEl = document.createElement("main");
+ document.body.append(appState.mainEl);
+ assert.ok(sessions.startNewChat());
+ if (stacked) {
+ localStorage.setItem(
+ "web-ui:split-canvas:v1",
+ JSON.stringify({
+ v: 2,
+ active: true,
+ layout: {
+ grid: {
+ root: {
+ type: "branch",
+ data: [
+ {
+ type: "leaf",
+ data: {
+ views: ["a", "b"],
+ activeView: "a",
+ id: "stack",
+ },
+ },
+ ],
+ },
+ width: 1000,
+ height: 800,
+ orientation: "HORIZONTAL",
+ },
+ panels: Object.fromEntries(
+ ["a", "b"].map((id) => [
+ id,
+ {
+ id,
+ contentComponent: "pane",
+ tabComponent: "pane",
+ params: {},
+ title: "New session",
+ },
+ ]),
+ ),
+ activeGroup: "stack",
+ },
+ }),
+ );
+ split.loadPersistedSplit();
+ assert.equal(split.mountRestoredCanvas(), true);
+ }
+ await run({
+ panes: () => document.querySelectorAll(".dv-tab").length,
+ tiles: () => document.querySelectorAll(".dv-groupview").length,
+ newChat: () => sessions.startNewChat() !== null,
+ seededChat: (threadRef) => sessions.startNewChat(null, null, threadRef),
+ split: () => split.activateCanvas({}, {}, "right"),
+ switchAway: () => {
+ appState.currentView = "crons";
+ appState.mainEl.replaceChildren();
+ },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ } 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];
+ }
+ }
+}
+
+test("New chat replaces one pane, then joins the arrangement the viewer built", async () => {
+ await withCanvas((canvas) => {
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [0, 0]);
+
+ assert.equal(canvas.newChat(), true);
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [0, 0], "one session: New chat replaces it");
+
+ canvas.split();
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [2, 2]);
+
+ assert.equal(canvas.newChat(), true);
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [3, 3], "split screen: New chat adds a window");
+
+ assert.equal(canvas.newChat(), true);
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [4, 4]);
+
+ assert.equal(canvas.newChat(), true);
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [5, 4], "at the window limit: New chat adds a tab");
+ });
+});
+
+test("a seeded New chat hands back the conversation in the pane it just placed", async () => {
+ await withCanvas((canvas) => {
+ const first = canvas.seededChat();
+ 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");
+
+ canvas.split();
+ const second = canvas.seededChat();
+ assert.ok(second);
+ assert.notEqual(second.state.threadRef, first.state.threadRef, "each one is its own conversation");
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [3, 3], "split screen: it adds a window, same as the button");
+ });
+});
+
+test("seeded chats return from another view without losing the grid or supplied thread", async () => {
+ await withCanvas((canvas) => {
+ canvas.split();
+ canvas.switchAway();
+ const thread = "web:tester:app-edit:example";
+ const conv = canvas.seededChat(thread);
+ assert.ok(conv?.state.agent);
+ assert.equal(conv?.state.threadRef, thread);
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [3, 3]);
+ });
+});
+
+test("new chat replaces the focused conversation at capacity without dropping the grid", async () => {
+ await withCanvas((canvas) => {
+ canvas.split();
+ for (let i = 2; i < 12; i++) assert.equal(canvas.newChat(), true);
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [12, 4]);
+ assert.ok(canvas.seededChat()?.state.agent);
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [12, 4]);
+ });
+});
+
+test("a restored tab-only arrangement gains a tab, not a tile", async () => {
+ await withCanvas((canvas) => {
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [2, 1]);
+ assert.ok(canvas.seededChat()?.state.agent);
+ assert.deepEqual([canvas.panes(), canvas.tiles()], [3, 1]);
+ }, true);
+});
diff --git a/plugins/web-ui/test/responsive-source.test.ts b/plugins/web-ui/test/responsive-source.test.ts
index a8aa843a9..4233249f2 100644
--- a/plugins/web-ui/test/responsive-source.test.ts
+++ b/plugins/web-ui/test/responsive-source.test.ts
@@ -19,7 +19,7 @@ test("mobile shell follows the visual viewport and device safe areas", () => {
test("mobile sidebar is modal, dismissible, and sized for touch", () => {
assert.match(shell, /actionRow\(ICON\.newChat[\s\S]{0,200}startNewChatInLastScope\(\);/);
- assert.match(sessions, /export function startNewChat\([\s\S]{0,120}closeSidebarOnNarrowView\(\);/);
+ assert.match(sessions, /export function startNewChat\([^)]*\)[^{]*\{\s*closeSidebarOnNarrowView\(\);/);
assert.match(shell, /class="sidebar-scrim"[^>]+aria-label="Close sidebar"[^>]+@click=\$\{toggleSidebar\}/);
assert.match(shell, /main\.inert = modal/);
assert.match(
diff --git a/plugins/web-ui/test/split-canvas-entry.test.ts b/plugins/web-ui/test/split-canvas-entry.test.ts
index ab10779f5..b2b2b82a4 100644
--- a/plugins/web-ui/test/split-canvas-entry.test.ts
+++ b/plugins/web-ui/test/split-canvas-entry.test.ts
@@ -18,32 +18,24 @@ const fn = (src: string, name: string): string => {
return body;
};
-test("no new-chat affordance can cost the user their canvas", () => {
- assert.match(split, /export function addBlankPane\(scopeId\?: string\): boolean \{/);
- const add = fn(split, "addBlankPane");
- assert.match(add, /if \(!splitState\.active \|\| !dockApi\) return false;/, "no canvas ⇒ the caller must fall back");
- assert.match(add, /return true;\n\}$/, "having split, the canvas owns the click");
- assert.doesNotMatch(add.slice(add.indexOf("splitPane(")), /return false/, "a full canvas must not fall through");
-
- assert.match(shell, /startNewChatInLastScope\(\);/, "the sidebar routes its click through the shared starter");
- assert.doesNotMatch(shell, /addBlankPane/, "and never mounts a chat behind the canvas' back");
+test("every new-chat affordance follows the shared placement rule", () => {
+ const placed = fn(split, "startNewChatInCanvas");
+ assert.match(placed, /dockApi\.panels\.length >= MAX_PANES/);
+ assert.match(placed, /dockApi\.removePanel\(target\)/);
+ assert.match(placed, /dockApi\.groups\.length > 1 && dockApi\.groups\.length < MAX_TILES/);
const start = fn(sessions, "startNewChat");
- const claimed = start.indexOf("addBlankPane(scopeId ?? undefined)");
- assert.ok(claimed > 0, "every new-chat affordance must offer the click to the canvas");
- assert.match(
- start.slice(claimed),
- /^addBlankPane\(scopeId \?\? undefined\)\) return;/m,
- "and bail out when it takes it",
- );
- assert.ok(
- start.indexOf("addPendingSession(mainConversation().newChat(") > claimed,
- "only then may it mount a single chat",
- );
- assert.match(fn(sessions, "startProjectChat"), /startNewChat\(scopeId, name\);/, "the project + shares that path");
- assert.match(fn(sessions, "startNewChatInLastScope"), /startNewChat\(/, "so does the sidebar's Create New Chat");
-
- assert.match(fn(split, "exitSplitIfActive"), /splitState\.active = false;/);
- assert.doesNotMatch(fn(split, "exitSplitIfActive"), /removeItem|lastLayout = null/);
+ assert.match(start, /if \(splitState\.active\) return startNewChatInCanvas/);
+ assert.match(start, /addPendingSession\(conv\.newChat/);
+ assert.match(shell, /startNewChatInLastScope\(\);/);
+ assert.match(fn(sessions, "startProjectChat"), /startNewChat\(scopeId, name\);/);
+ assert.match(fn(sessions, "startNewChatInLastScope"), /startNewChat\(/);
+ assert.match(fn(shell, "openAppEditChat"), /startNewChat\(null, null, threadRef\)/);
+ for (const file of ["contexts.ts", "search.ts", "crons.ts"]) {
+ const source = read(file);
+ assert.doesNotMatch(source, /\.newChat\(/);
+ assert.match(source, /startNewChat\(/);
+ }
+ assert.match(sessions, /action: \{ label: "New chat", onClick: \(\) => startNewChat\(\) \}/);
});
test("a pane opened from a project's + starts its chat in that project", () => {