From a1dca45b5db3e476ddd4528737cc1c42e113a267 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:07:31 -0500 Subject: [PATCH] fix(web): New lead chat opens the new lead instead of sending you home New lead chat made the lead and opened it before this app had heard of the thread, so the thread page found no thread there and went home. It now opens it once the thread has arrived (waitForAppState, now shared with the two places that already waited for something the server made: a set-up project and a started thread). If it hasn't arrived in 10 seconds it says the lead was started instead of opening it into the same bounce. On an install with no default agent chosen it refused, although a new thread there runs on the composer's own fallback. It now takes the same agent a new thread would (fallbackNewThreadModelSelection: the composer's entry order, Codex first, its offline fallback while agents load), and no longer the project's stored model pin, which new threads ignore. The project list closes when its lead item is chosen. Also drops an unused import in leadChat.ts. --- apps/web/src/components/ChatView.logic.ts | 44 +------ .../components/ChatView.sidebar.browser.tsx | 110 ++++++++++++++++++ .../components/sidebar/ProjectScopeMenu.tsx | 2 + .../projectSetups/projectSetups.ts | 19 +-- apps/web/src/leadChat.ts | 47 +++++--- apps/web/src/newThreadDefaults.test.ts | 29 +++++ apps/web/src/newThreadDefaults.ts | 33 +++++- apps/web/src/store.ts | 29 +++++ 8 files changed, 244 insertions(+), 69 deletions(-) diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index f0f8ced0d..a84a3cfbb 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -47,7 +47,7 @@ import { } from "../types"; import { type ComposerAttachment, type DraftThreadState } from "../composerDraftStore"; import * as Schema from "effect/Schema"; -import { selectThreadByRef, useStore } from "../store"; +import { selectThreadByRef, waitForAppState } from "../store"; import { filterTerminalContextsWithText, stripInlineTerminalContextPlaceholders, @@ -2311,44 +2311,10 @@ export async function waitForStartedServerThread( threadRef: ScopedThreadRef, timeoutMs = 1_000, ): Promise { - const getThread = () => selectThreadByRef(useStore.getState(), threadRef); - const thread = getThread(); - - if (threadHasStarted(thread)) { - return true; - } - - return await new Promise((resolve) => { - let settled = false; - let timeoutId: ReturnType | null = null; - const finish = (result: boolean) => { - if (settled) { - return; - } - settled = true; - if (timeoutId !== null) { - globalThis.clearTimeout(timeoutId); - } - unsubscribe(); - resolve(result); - }; - - const unsubscribe = useStore.subscribe((state) => { - if (!threadHasStarted(selectThreadByRef(state, threadRef))) { - return; - } - finish(true); - }); - - if (threadHasStarted(getThread())) { - finish(true); - return; - } - - timeoutId = globalThis.setTimeout(() => { - finish(false); - }, timeoutMs); - }); + return await waitForAppState( + (state) => threadHasStarted(selectThreadByRef(state, threadRef)), + timeoutMs, + ); } export interface LocalDispatchSnapshot { diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index f622a6636..16b332f04 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -36,6 +36,7 @@ import { __setEnvironmentApiOverrideForTests, } from "../environmentApi"; import { getClientSettings, updateSettings } from "../hooks/useSettings"; +import { readAfterEachPaint } from "../lib/frameProbe.browser-harness"; import { isMacPlatform } from "../lib/utils"; import { useThreadSelectionStore } from "../threadSelectionStore"; import { useUiStateStore } from "../uiStateStore"; @@ -76,6 +77,8 @@ import { waitForURL, waitForComposerEditor, waitForServerConfigToApply, + withCodexModels, + sendShellThreadUpsert, mountChatView, fixture, clickProjectMenuItem, @@ -312,6 +315,113 @@ describe("ChatView (full app): sidebar", () => { } }); + // The server says it made the thread a moment before this app hears of it, + // as a real one does: "New lead chat" must open it once it is here, and + // stay there (the thread page goes home for a thread it does not know). + const startsALeadChatFromTheProjectMenu = async (defaultAgent: "chosen" | "none") => { + const capabilities = { repositoryIdentity: true, projectLead: true }; + const created: { threadId: ThreadId; model: string }[] = []; + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-new-lead-target" as MessageId, + targetText: "new lead target", + }), + configureFixture: (nextFixture) => { + withCodexModels(nextFixture); + // An old pin from when the project was made: new threads ignore it. + nextFixture.snapshot = { + ...nextFixture.snapshot, + projects: nextFixture.snapshot.projects.map((project) => ({ + ...project, + defaultModelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-4.1", + }, + })), + }; + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + environment: { ...nextFixture.serverConfig.environment, capabilities }, + settings: { + ...nextFixture.serverConfig.settings, + newThreadModelSelection: + defaultAgent === "chosen" + ? { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6-astra" } + : null, + }, + }; + nextFixture.welcome = { + ...nextFixture.welcome, + environment: { ...nextFixture.welcome.environment, capabilities }, + }; + }, + resolveRpc: (body) => { + if ( + body._tag !== ORCHESTRATION_WS_METHODS.dispatchCommand || + body.type !== "thread.create" + ) { + return undefined; + } + const threadId = body.threadId as ThreadId; + created.push({ threadId, model: (body.modelSelection as { model: string }).model }); + setTimeout(() => { + fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId); + sendShellThreadUpsert(threadId); + }, 400); + return { sequence: fixture.snapshot.snapshotSequence + 1 }; + }, + }); + const paths: string[] = []; + const stop = readAfterEachPaint(() => paths.push(mounted.router.state.location.pathname)); + try { + await page.getByTestId("inbox-scope-label").click(); + const projectItem = await waitForElement( + () => document.querySelector('[role="menuitemcheckbox"]:not(:first-child)'), + "The project list should name the project.", + ); + const rect = projectItem.getBoundingClientRect(); + projectItem.dispatchEvent( + new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: rect.left + 20, + clientY: rect.top + 8, + }), + ); + await page.getByRole("button", { name: "New lead chat", exact: true }).click(); + await vi.waitFor(() => expect(created).toHaveLength(1), { timeout: 5_000 }); + const leadPath = `/${LOCAL_ENVIRONMENT_ID}/${created[0]!.threadId}`; + await waitForURL( + mounted.router, + (pathname) => pathname === leadPath, + "New lead chat should open the new lead.", + ); + // Still there a while later, never sent home on the way. + await new Promise((resolve) => setTimeout(resolve, 600)); + stop(); + expect(mounted.router.state.location.pathname).toBe(leadPath); + expect(paths.indexOf(leadPath)).toBeGreaterThanOrEqual(0); + expect(paths.slice(paths.indexOf(leadPath))).not.toContain("/"); + // The project list closed behind it. + expect(document.querySelector('[role="menuitemcheckbox"]')).toBeNull(); + return created[0]!; + } finally { + stop(); + await mounted.cleanup(); + } + }; + + it("opens a new lead chat from the project menu once it has arrived, and stays there", async () => { + expect((await startsALeadChatFromTheProjectMenu("chosen")).model).toBe("gpt-6-astra"); + }); + + it("starts a lead chat with no default agent chosen, on the agent a new thread would get", async () => { + // Codex at the model a fresh draft's composer settles on, not the + // project's old pin. + expect((await startsALeadChatFromTheProjectMenu("none")).model).toBe("gpt-5.6-sol"); + }); + it("narrows the live list to rooms from the View button and marks it while it does", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/apps/web/src/components/sidebar/ProjectScopeMenu.tsx b/apps/web/src/components/sidebar/ProjectScopeMenu.tsx index df9fd92f4..cbea14746 100644 --- a/apps/web/src/components/sidebar/ProjectScopeMenu.tsx +++ b/apps/web/src/components/sidebar/ProjectScopeMenu.tsx @@ -509,6 +509,8 @@ export const ProjectScopeMenu = memo(function ProjectScopeMenu(props: ProjectSco const leadRef = projectLeadRef(useStore.getState(), member); const id = `lead:${member.physicalProjectKey}`; actionHandlers.set(id, async () => { + // It takes you to a thread: the project list closes behind it. + setMenuOpen(false); const target = leadRef ?? (await createLeadChat(member)); if (target !== null) { await navigate({ diff --git a/apps/web/src/environments/projectSetups/projectSetups.ts b/apps/web/src/environments/projectSetups/projectSetups.ts index 533781d98..eb3b34b0f 100644 --- a/apps/web/src/environments/projectSetups/projectSetups.ts +++ b/apps/web/src/environments/projectSetups/projectSetups.ts @@ -28,7 +28,7 @@ import { create } from "zustand"; import { newProjectSetupId } from "../../lib/utils"; import type { WsRpcClient } from "../../rpc/wsRpcClient"; -import { selectProjectByRef, useStore } from "../../store"; +import { selectProjectByRef, waitForAppState } from "../../store"; import { describeComputerLinkFailure } from "../links/computerLinks"; import { readPrimaryEnvironmentDescriptor, @@ -524,17 +524,8 @@ const PROJECT_ARRIVAL_TIMEOUT_MS = 15_000; * there; false if it hasn't come in time. */ export function waitForSetUpProject(ref: ScopedProjectRef): Promise { - if (selectProjectByRef(useStore.getState(), ref) !== undefined) return Promise.resolve(true); - return new Promise((resolve) => { - const timer = setTimeout(() => { - unsubscribe(); - resolve(false); - }, PROJECT_ARRIVAL_TIMEOUT_MS); - const unsubscribe = useStore.subscribe((state) => { - if (selectProjectByRef(state, ref) === undefined) return; - clearTimeout(timer); - unsubscribe(); - resolve(true); - }); - }); + return waitForAppState( + (state) => selectProjectByRef(state, ref) !== undefined, + PROJECT_ARRIVAL_TIMEOUT_MS, + ); } diff --git a/apps/web/src/leadChat.ts b/apps/web/src/leadChat.ts index 3807b3307..369a3a727 100644 --- a/apps/web/src/leadChat.ts +++ b/apps/web/src/leadChat.ts @@ -11,7 +11,6 @@ import { DEFAULT_PROVIDER_INTERACTION_MODE, type EnvironmentId, type ProjectId, - type ScopedProjectRef, type ScopedThreadRef, type ThreadId, } from "@threadlines/contracts"; @@ -24,6 +23,7 @@ import { readEnvironmentApi } from "./environmentApi"; import { readEnvironmentDescriptor } from "./environments/runtime"; import { newCommandId, newThreadId } from "./lib/utils"; import { + fallbackNewThreadModelSelection, lastUsedSelection, readComputerConfig, resolveNewThreadDefaults, @@ -32,7 +32,9 @@ import { type AppState, selectProjectByRef, selectSidebarThreadSummaryByRef, + selectThreadExistsByRef, useStore, + waitForAppState, } from "./store"; import type { Project, SidebarThreadSummary } from "./types"; @@ -213,11 +215,12 @@ export function readProjectLeadRefForThread(threadRef: ScopedThreadRef): ScopedT /** * "New lead chat": makes a thread in the project's own folder (no worktree), - * with the computer's default agent, makes it the lead and returns it. Null - * when it couldn't, having said why. + * with the agent a new thread there would get, makes it the lead and returns + * it once this app has it, ready to open. Null when it couldn't, or when the + * thread hasn't reached this app in time, having said so either way. */ export async function createLeadChat( - project: Pick, + project: Pick, ): Promise { const failure = "Couldn't start a lead chat"; const api = readEnvironmentApi(project.environmentId); @@ -231,18 +234,13 @@ export async function createLeadChat( return null; } const config = readComputerConfig(project.environmentId); + // The same agent a new thread here would get, down to the composer's own + // fallback when nothing is chosen, so the two never disagree. Not the + // project's stored `defaultModelSelection`: new threads ignore that old pin. const modelSelection = (config === null ? null : resolveNewThreadDefaults(config).modelSelection) ?? - project.defaultModelSelection ?? - lastUsedSelection(); - if (modelSelection === null) { - toastManager.add({ - type: "warning", - title: failure, - description: "Pick a default agent for new threads in Settings first.", - }); - return null; - } + lastUsedSelection() ?? + fallbackNewThreadModelSelection(config); const threadId = newThreadId(); try { await api.orchestration.dispatchCommand({ @@ -267,9 +265,28 @@ export async function createLeadChat( projectId: project.id, threadId, }); - return made ? scopeThreadRef(project.environmentId, threadId) : null; + if (!made) return null; + // Opened once this app has it: before that its page finds no thread there + // and goes home. + const ref = scopeThreadRef(project.environmentId, threadId); + const arrived = await waitForAppState( + (state) => selectThreadExistsByRef(state, ref), + THREAD_ARRIVAL_TIMEOUT_MS, + ); + if (!arrived) { + toastManager.add({ + type: "info", + title: "Lead chat started", + description: "It shows in the sidebar once this window catches up.", + }); + return null; + } + return ref; } +/** How long "New lead chat" waits for its thread to reach this app before opening it anyway. */ +const THREAD_ARRIVAL_TIMEOUT_MS = 10_000; + /** * The project's name when `threadRef` is its lead chat, else null. A * primitive, so a store selector built on it redraws only when it changes. diff --git a/apps/web/src/newThreadDefaults.test.ts b/apps/web/src/newThreadDefaults.test.ts index 05f6f43e3..3c7bd29d6 100644 --- a/apps/web/src/newThreadDefaults.test.ts +++ b/apps/web/src/newThreadDefaults.test.ts @@ -1,5 +1,6 @@ import { scopeProjectRef } from "@threadlines/client-runtime"; import { + DEFAULT_MODEL, DEFAULT_SERVER_SETTINGS, EnvironmentId, ProjectId, @@ -20,6 +21,7 @@ import { applyMovedDraftDefaults, applyNewThreadDefaultsToDraft, buildNewThreadParticipants, + fallbackNewThreadModelSelection, placeDraftFromSettings, readComputerConfig, resolveNewThreadDefaults, @@ -110,6 +112,33 @@ describe("resolveNewThreadDefaults", () => { }); }); +describe("fallbackNewThreadModelSelection", () => { + const settings = DEFAULT_SERVER_SETTINGS; + + it("settles where a fresh draft's composer does: Codex while it is on, else the first agent on", () => { + expect(fallbackNewThreadModelSelection({ settings, providers })).toEqual(astra); + const codexOff = [providers[0]!, { ...providers[1]!, enabled: false }]; + expect(fallbackNewThreadModelSelection({ settings, providers: codexOff })).toEqual(opus); + }); + + it("takes the stock Codex over a custom Codex account listed before it", () => { + const work = provider({ + driver: "codex", + instanceId: ProviderInstanceId.make("codex_work"), + models: [{ slug: "gpt-6-astra", name: "GPT-6 Astra" }], + }); + expect( + fallbackNewThreadModelSelection({ settings, providers: [work, providers[1]!] }).instanceId, + ).toBe(CODEX); + }); + + it("uses the draft's offline fallback while the computer's agents are not known yet", () => { + const offline = { instanceId: CODEX, model: DEFAULT_MODEL }; + expect(fallbackNewThreadModelSelection({ settings, providers: [] })).toEqual(offline); + expect(fallbackNewThreadModelSelection(null)).toEqual(offline); + }); +}); + describe("buildNewThreadParticipants", () => { it("names agents like the model picker does, numbered past the thread's own agent", () => { let next = 0; diff --git a/apps/web/src/newThreadDefaults.ts b/apps/web/src/newThreadDefaults.ts index e530e2858..d22ffddaa 100644 --- a/apps/web/src/newThreadDefaults.ts +++ b/apps/web/src/newThreadDefaults.ts @@ -7,10 +7,12 @@ * "Start in" says (`placeDraftFromSettings` when it is not known yet). */ import { + DEFAULT_MODEL, type EnvironmentId, type ModelSelection, + ProviderDriverKind, + ProviderInstanceId, type NewThreadRoomAgent, - type ProviderInstanceId, type ScopedProjectRef, type ServerConfig, type ServerProvider, @@ -39,9 +41,11 @@ import { randomUUID } from "./lib/utils"; import { deriveLogicalProjectKeyFromSettings } from "./logicalProject"; import { getClientSettings } from "./hooks/useSettings"; import { selectProjectByRef, useStore } from "./store"; +import { resolveAppModelSelectionForInstance } from "./modelSelection"; import { deriveDisplayProviderInstanceEntries, type ProviderInstanceEntry, + resolveComposerProviderSelection, } from "./providerInstances"; import { roomModelName } from "./rooms"; import { getServerConfig, onServerConfigUpdated, useServerConfig } from "./rpc/serverState"; @@ -198,6 +202,33 @@ function draftActiveSelection(draftId: DraftId): ModelSelection | null { ); } +/** + * The agent a new thread on this computer runs with when no default is chosen + * and nothing was picked yet: what a fresh draft's composer settles on. That + * is resolveComposerProviderSelection over the composer's own entry order + * (Codex when it is on, else the first agent that is) at that agent's default + * model; with no providers listed yet (still loading, or no config), the + * draft's offline fallback, Codex at DEFAULT_MODEL. + */ +export function fallbackNewThreadModelSelection(config: ComputerConfig | null): ModelSelection { + const offline = { instanceId: ProviderInstanceId.make("codex"), model: DEFAULT_MODEL }; + const entries = config === null ? [] : deriveDisplayProviderInstanceEntries(config.providers); + if (config === null || entries.length === 0) return offline; + const { instanceId } = resolveComposerProviderSelection({ + entries, + candidates: [], + lockedProvider: null, + fallbackDriverKind: ProviderDriverKind.make("codex"), + }); + const model = resolveAppModelSelectionForInstance( + instanceId, + { ...config.settings, ...getClientSettings() }, + config.providers, + null, + ); + return { instanceId, model: model ?? DEFAULT_MODEL }; +} + /** The model last picked on this device, if any. */ export function lastUsedSelection(): ModelSelection | null { const state = useComposerDraftStore.getState(); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index fbc59b241..3632e97fc 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -4102,6 +4102,35 @@ export function selectThreadByRef( : undefined; } +/** + * Waits until `ready` holds for this app's state: something the server just + * made (a project, a thread) arriving over its stream a moment after the + * command that made it returned. True once it holds; false if it hasn't by + * `timeoutMs`. Open a new thread or project through this, so its page finds it. + */ +export function waitForAppState( + ready: (state: AppState) => boolean, + timeoutMs: number, +): Promise { + if (ready(useStore.getState())) return Promise.resolve(true); + return new Promise((resolve) => { + let settled = false; + const finish = (result: boolean) => { + if (settled) return; + settled = true; + clearTimeout(timer); + unsubscribe(); + resolve(result); + }; + const timer = setTimeout(() => finish(false), timeoutMs); + const unsubscribe = useStore.subscribe((state) => { + if (ready(state)) finish(true); + }); + // It may have come in between the first look and the subscription. + if (ready(useStore.getState())) finish(true); + }); +} + export function selectThreadExistsByRef( state: AppState, ref: ScopedThreadRef | null | undefined,