Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 5 additions & 39 deletions apps/web/src/components/ChatView.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -2311,44 +2311,10 @@ export async function waitForStartedServerThread(
threadRef: ScopedThreadRef,
timeoutMs = 1_000,
): Promise<boolean> {
const getThread = () => selectThreadByRef(useStore.getState(), threadRef);
const thread = getThread();

if (threadHasStarted(thread)) {
return true;
}

return await new Promise<boolean>((resolve) => {
let settled = false;
let timeoutId: ReturnType<typeof globalThis.setTimeout> | 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 {
Expand Down
110 changes: 110 additions & 0 deletions apps/web/src/components/ChatView.sidebar.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -76,6 +77,8 @@ import {
waitForURL,
waitForComposerEditor,
waitForServerConfigToApply,
withCodexModels,
sendShellThreadUpsert,
mountChatView,
fixture,
clickProjectMenuItem,
Expand Down Expand Up @@ -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<HTMLElement>('[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,
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/sidebar/ProjectScopeMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
19 changes: 5 additions & 14 deletions apps/web/src/environments/projectSetups/projectSetups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<boolean> {
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,
);
}
47 changes: 32 additions & 15 deletions apps/web/src/leadChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
type EnvironmentId,
type ProjectId,
type ScopedProjectRef,
type ScopedThreadRef,
type ThreadId,
} from "@threadlines/contracts";
Expand All @@ -24,6 +23,7 @@ import { readEnvironmentApi } from "./environmentApi";
import { readEnvironmentDescriptor } from "./environments/runtime";
import { newCommandId, newThreadId } from "./lib/utils";
import {
fallbackNewThreadModelSelection,
lastUsedSelection,
readComputerConfig,
resolveNewThreadDefaults,
Expand All @@ -32,7 +32,9 @@ import {
type AppState,
selectProjectByRef,
selectSidebarThreadSummaryByRef,
selectThreadExistsByRef,
useStore,
waitForAppState,
} from "./store";
import type { Project, SidebarThreadSummary } from "./types";

Expand Down Expand Up @@ -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, "environmentId" | "id" | "defaultModelSelection">,
project: Pick<Project, "environmentId" | "id">,
): Promise<ScopedThreadRef | null> {
const failure = "Couldn't start a lead chat";
const api = readEnvironmentApi(project.environmentId);
Expand All @@ -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({
Expand All @@ -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.
Expand Down
29 changes: 29 additions & 0 deletions apps/web/src/newThreadDefaults.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { scopeProjectRef } from "@threadlines/client-runtime";
import {
DEFAULT_MODEL,
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
ProjectId,
Expand All @@ -20,6 +21,7 @@ import {
applyMovedDraftDefaults,
applyNewThreadDefaultsToDraft,
buildNewThreadParticipants,
fallbackNewThreadModelSelection,
placeDraftFromSettings,
readComputerConfig,
resolveNewThreadDefaults,
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading