Prepare datamodel for multi-environment (#1765)

Co-authored-by: justsomelegs <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-04-09 02:05:20 +00:00
1 parent 72b7f90c50
commit b96308fc5a
121 files changed
+10195 -4958

No files matched your search

+330 -229
View File
@@ -4,6 +4,7 @@ import "../index.css";
import {
EventId,
ORCHESTRATION_WS_METHODS,
EnvironmentId,
type MessageId,
type OrchestrationEvent,
type OrchestrationReadModel,
@@ -12,11 +13,16 @@ import {
type ServerLifecycleWelcomePayload,
type ThreadId,
type TurnId,
type UserInputQuestion,
WS_METHODS,
OrchestrationSessionStatus,
DEFAULT_SERVER_SETTINGS,
} from "@t3tools/contracts";
import {
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime";
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { HttpResponse, http, ws } from "msw";
import { setupWorker } from "msw/browser";
@@ -24,19 +30,20 @@ import { page } from "vitest/browser";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
import { useComposerDraftStore, DraftId } from "../composerDraftStore";
import {
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
type TerminalContextDraft,
removeInlineTerminalContextPlaceholder,
} from "../lib/terminalContext";
import { isMacPlatform } from "../lib/utils";
import { __resetNativeApiForTests } from "../nativeApi";
import { __resetLocalApiForTests } from "../localApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getRouter } from "../router";
import { useStore } from "../store";
import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness";
import { estimateTimelineMessageHeight } from "./timelineHeight";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
@@ -49,8 +56,13 @@ vi.mock("../lib/gitStatusState", () => ({
}));
const THREAD_ID = "thread-browser-test" as ThreadId;
const UUID_ROUTE_RE = /^\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_ID = "project-1" as ProjectId;
const LOCAL_ENVIRONMENT_ID = EnvironmentId.makeUnsafe("environment-local");
const THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, THREAD_ID);
const THREAD_KEY = scopedThreadKey(THREAD_REF);
const UUID_ROUTE_RE = /^\/draft\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const PROJECT_DRAFT_KEY = `${LOCAL_ENVIRONMENT_ID}:${PROJECT_ID}`;
const PROJECT_KEY = scopedProjectKey(scopeProjectRef(LOCAL_ENVIRONMENT_ID, PROJECT_ID));
const NOW_ISO = "2026-03-04T12:00:00.000Z";
const BASE_TIME_MS = Date.parse(NOW_ISO);
const ATTACHMENT_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120'></svg>";
@@ -129,6 +141,13 @@ function isoAt(offsetSeconds: number): string {
function createBaseServerConfig(): ServerConfig {
return {
environment: {
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Local environment",
platform: { os: "darwin" as const, arch: "arm64" as const },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
cwd: "/repo/project",
keybindingsConfigPath: "/repo/project/.t3code-keybindings.json",
keybindings: [],
@@ -314,6 +333,13 @@ function buildFixture(snapshot: OrchestrationReadModel): TestFixture {
snapshot,
serverConfig: createBaseServerConfig(),
welcome: {
environment: {
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Local environment",
platform: { os: "darwin" as const, arch: "arm64" as const },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
},
cwd: "/repo/project",
projectName: "Project",
bootstrapProjectId: PROJECT_ID,
@@ -396,6 +422,33 @@ function createThreadCreatedEvent(threadId: ThreadId, sequence: number): Orchest
};
}
function createThreadSessionSetEvent(threadId: ThreadId, sequence: number): OrchestrationEvent {
return {
sequence,
eventId: EventId.makeUnsafe(`event-thread-session-set-${sequence}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: NOW_ISO,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.session-set",
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: `turn-${threadId}` as TurnId,
lastError: null,
updatedAt: NOW_ISO,
},
},
};
}
function sendOrchestrationDomainEvent(event: OrchestrationEvent): void {
rpcHarness.emitStreamValue(WS_METHODS.subscribeOrchestrationDomainEvents, event);
}
@@ -419,25 +472,72 @@ async function waitForWsClient(): Promise<void> {
);
}
function threadRefFor(threadId: ThreadId) {
return scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);
}
function threadKeyFor(threadId: ThreadId): string {
return scopedThreadKey(threadRefFor(threadId));
}
function composerDraftFor(target: string) {
const { draftsByThreadKey } = useComposerDraftStore.getState();
return draftsByThreadKey[target] ?? draftsByThreadKey[threadKeyFor(target as ThreadId)];
}
function draftIdFromPath(pathname: string) {
const segments = pathname.split("/");
const draftId = segments[segments.length - 1];
if (!draftId) {
throw new Error(`Expected thread path, received "${pathname}".`);
}
return DraftId.makeUnsafe(draftId);
}
function draftThreadIdFor(draftId: ReturnType<typeof draftIdFromPath>): ThreadId {
const draftSession = useComposerDraftStore.getState().getDraftSession(draftId);
if (!draftSession) {
throw new Error(`Expected draft session for "${draftId}".`);
}
return draftSession.threadId;
}
function serverThreadPath(threadId: ThreadId): string {
return `/${LOCAL_ENVIRONMENT_ID}/${threadId}`;
}
async function waitForAppBootstrap(): Promise<void> {
await vi.waitFor(
() => {
expect(getServerConfig()).not.toBeNull();
expect(useStore.getState().bootstrapComplete).toBe(true);
expect(selectBootstrapCompleteForActiveEnvironment(useStore.getState())).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
}
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
async function materializePromotedDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
await waitForWsClient();
fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId);
sendOrchestrationDomainEvent(
createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence),
);
}
async function startPromotedServerThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
sendOrchestrationDomainEvent(
createThreadSessionSetEvent(threadId, fixture.snapshot.snapshotSequence + 1),
);
}
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
await materializePromotedDraftThreadViaDomainEvent(threadId);
await startPromotedServerThreadViaDomainEvent(threadId);
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined();
expect(useComposerDraftStore.getState().draftThreadsByThreadKey[threadKeyFor(threadId)]).toBe(
undefined,
);
},
{ timeout: 8_000, interval: 16 },
);
@@ -468,9 +568,12 @@ function withProjectScripts(
function setDraftThreadWithoutWorktree(): void {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -479,8 +582,8 @@ function setDraftThreadWithoutWorktree(): void {
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
}
@@ -542,51 +645,12 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
};
}
function createSnapshotWithPendingUserInput(options?: {
questions?: ReadonlyArray<UserInputQuestion>;
}): OrchestrationReadModel {
function createSnapshotWithPendingUserInput(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-pending-input-target" as MessageId,
targetText: "question thread",
});
const questions =
options?.questions ??
([
{
id: "scope",
header: "Scope",
question: "What should this change cover?",
options: [
{
label: "Tight",
description: "Touch only the footer layout logic.",
},
{
label: "Broad",
description: "Also adjust the related composer controls.",
},
],
multiSelect: false,
},
{
id: "risk",
header: "Risk",
question: "How aggressive should the imaginary plan be?",
options: [
{
label: "Conservative",
description: "Favor reliability and low-risk changes.",
},
{
label: "Balanced",
description: "Mix quick wins with one structural improvement.",
},
],
multiSelect: false,
},
] satisfies ReadonlyArray<UserInputQuestion>);
return {
...snapshot,
threads: snapshot.threads.map((thread) =>
@@ -601,7 +665,38 @@ function createSnapshotWithPendingUserInput(options?: {
summary: "User input requested",
payload: {
requestId: "req-browser-user-input",
questions,
questions: [
{
id: "scope",
header: "Scope",
question: "What should this change cover?",
options: [
{
label: "Tight",
description: "Touch only the footer layout logic.",
},
{
label: "Broad",
description: "Also adjust the related composer controls.",
},
],
},
{
id: "risk",
header: "Risk",
question: "How aggressive should the imaginary plan be?",
options: [
{
label: "Conservative",
description: "Favor reliability and low-risk changes.",
},
{
label: "Balanced",
description: "Mix quick wins with one structural improvement.",
},
],
},
],
},
turnId: null,
sequence: 1,
@@ -1057,7 +1152,7 @@ async function mountChatView(options: {
const router = getRouter(
createMemoryHistory({
initialEntries: [`/${THREAD_ID}`],
initialEntries: [`/${LOCAL_ENVIRONMENT_ID}/${THREAD_ID}`],
}),
);
@@ -1162,42 +1257,32 @@ describe("ChatView timeline estimator parity (full app)", () => {
return [];
},
});
await __resetNativeApiForTests();
await __resetLocalApiForTests();
await setViewport(DEFAULT_VIEWPORT);
localStorage.clear();
document.body.innerHTML = "";
wsRequests.length = 0;
customWsRpcResolver = null;
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
stickyActiveProvider: null,
});
useStore.setState({
projectIds: [],
projectById: {},
threadIds: [],
threadIdsByProjectId: {},
threadShellById: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {},
activityByThreadId: {},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
sidebarThreadSummaryById: {},
bootstrapComplete: false,
activeEnvironmentId: null,
environmentStateById: {},
});
useUiStateStore.setState({
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
});
useTerminalStateStore.persist.clearStorage();
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalLaunchContextByThreadId: {},
terminalStateByThreadKey: {},
terminalLaunchContextByThreadKey: {},
terminalEventEntriesByKey: {},
nextTerminalEventId: 1,
});
@@ -1241,6 +1326,35 @@ describe("ChatView timeline estimator parity (full app)", () => {
},
);
it("re-expands the bootstrap project using its scoped key", async () => {
useUiStateStore.setState({
projectExpandedById: {
[PROJECT_KEY]: false,
},
projectOrder: [PROJECT_KEY],
threadLastVisitedAtById: {},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-bootstrap-project-expand" as MessageId,
targetText: "bootstrap project expand",
}),
});
try {
await vi.waitFor(
() => {
expect(useUiStateStore.getState().projectExpandedById[PROJECT_KEY]).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("tracks wrapping parity while resizing an existing ChatView across the viewport matrix", async () => {
const userText = "x".repeat(3_200);
const targetMessageId = "msg-user-target-resize" as MessageId;
@@ -1438,8 +1552,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
useTerminalStateStore.setState({
terminalStateByThreadId: {
[THREAD_ID]: {
terminalStateByThreadKey: {
[THREAD_KEY]: {
terminalOpen: true,
terminalHeight: 280,
terminalIds: ["default"],
@@ -1449,8 +1563,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
activeTerminalGroupId: "group-default",
},
},
terminalLaunchContextByThreadId: {
[THREAD_ID]: {
terminalLaunchContextByThreadKey: {
[THREAD_KEY]: {
cwd: "/repo/project",
worktreePath: null,
},
@@ -1696,9 +1810,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("runs project scripts from local draft threads at the project cwd", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -1707,8 +1824,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -1772,9 +1889,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("runs project scripts from worktree draft threads at the worktree cwd", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -1783,8 +1903,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -1835,9 +1955,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("lets the server own setup after preparing a pull request worktree thread", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -1846,8 +1969,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -1957,12 +2080,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("sends bootstrap turn-starts and waits for server setup on first-send worktree drafts", async () => {
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalStateByThreadKey: {},
});
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -1971,8 +2097,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -1998,7 +2124,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it");
useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");
await waitForLayout();
const sendButton = await waitForSendButton();
@@ -2057,12 +2183,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("shows the send state once bootstrap dispatch is in flight", async () => {
useTerminalStateStore.setState({
terminalStateByThreadId: {},
terminalStateByThreadKey: {},
});
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
draftThreadsByThreadKey: {
[THREAD_KEY]: {
threadId: THREAD_ID,
environmentId: LOCAL_ENVIRONMENT_ID,
projectId: PROJECT_ID,
logicalProjectKey: PROJECT_DRAFT_KEY,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
@@ -2071,8 +2200,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
logicalProjectDraftThreadKeyByLogicalProjectKey: {
[PROJECT_DRAFT_KEY]: THREAD_KEY,
},
});
@@ -2101,7 +2230,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_ID, "Ship it");
useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");
await waitForLayout();
const sendButton = await waitForSendButton();
@@ -2193,7 +2322,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
const removedLabel = "Terminal 1 lines 1-2";
const addedLabel = "Terminal 2 lines 9-10";
useComposerDraftStore.getState().addTerminalContext(
THREAD_ID,
THREAD_REF,
createTerminalContext({
id: "ctx-removed",
terminalLabel: "Terminal 1",
@@ -2220,21 +2349,21 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
const store = useComposerDraftStore.getState();
const currentPrompt = store.draftsByThreadId[THREAD_ID]?.prompt ?? "";
const currentPrompt = store.draftsByThreadKey[THREAD_KEY]?.prompt ?? "";
const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0);
store.setPrompt(THREAD_ID, nextPrompt.prompt);
store.removeTerminalContext(THREAD_ID, "ctx-removed");
store.setPrompt(THREAD_REF, nextPrompt.prompt);
store.removeTerminalContext(THREAD_REF, "ctx-removed");
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftsByThreadId[THREAD_ID]).toBeUndefined();
expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]).toBeUndefined();
expect(document.body.textContent).not.toContain(removedLabel);
},
{ timeout: 8_000, interval: 16 },
);
useComposerDraftStore.getState().addTerminalContext(
THREAD_ID,
THREAD_REF,
createTerminalContext({
id: "ctx-added",
terminalLabel: "Terminal 2",
@@ -2246,7 +2375,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
() => {
const draft = useComposerDraftStore.getState().draftsByThreadId[THREAD_ID];
const draft = useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY];
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]);
expect(document.body.textContent).toContain(addedLabel);
expect(document.body.textContent).not.toContain(removedLabel);
@@ -2261,7 +2390,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("disables send when the composer only contains an expired terminal pill", async () => {
const expiredLabel = "Terminal 1 line 4";
useComposerDraftStore.getState().addTerminalContext(
THREAD_ID,
THREAD_REF,
createTerminalContext({
id: "ctx-expired-only",
terminalLabel: "Terminal 1",
@@ -2297,7 +2426,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
it("warns when sending text while omitting expired terminal pills", async () => {
const expiredLabel = "Terminal 1 line 4";
useComposerDraftStore.getState().addTerminalContext(
THREAD_ID,
THREAD_REF,
createTerminalContext({
id: "ctx-expired-send-warning",
terminalLabel: "Terminal 1",
@@ -2308,7 +2437,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
useComposerDraftStore
.getState()
.setPrompt(THREAD_ID, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`);
.setPrompt(THREAD_REF, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`);
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -2448,7 +2577,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("keeps the new thread selected after clicking the new-thread button", async () => {
it("canonicalizes promoted draft threads to the server thread route", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
@@ -2470,21 +2599,34 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
const newDraftId = draftIdFromPath(newThreadPath);
const newThreadId = draftThreadIdFor(newDraftId);
// The composer editor should be present for the new draft thread.
await waitForComposerEditor();
// Simulate the steady-state promotion path: the server emits
// `thread.created`, the client materializes the thread incrementally,
// and the draft is cleared by live batch effects.
await promoteDraftThreadViaDomainEvent(newThreadId);
// `thread.created` should only mark the draft as promoting; it should
// not navigate away until the server thread has actual runtime state.
await materializePromotedDraftThreadViaDomainEvent(newThreadId);
expect(mounted.router.state.location.pathname).toBe(newThreadPath);
await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
// The route should still be on the new thread — not redirected away.
// Once the server thread starts, the route should canonicalize.
await startPromotedServerThreadViaDomainEvent(newThreadId);
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftThreadsByThreadKey[newDraftId]).toBe(
undefined,
);
},
{ timeout: 8_000, interval: 16 },
);
// The route should switch to the canonical server thread path.
await waitForURL(
mounted.router,
(path) => path === newThreadPath,
"New thread should remain selected after server thread promotion clears the draft.",
(path) => path === serverThreadPath(newThreadId),
"Promoted drafts should canonicalize to the server thread route.",
);
// The empty thread view and composer should still be visible.
@@ -2497,6 +2639,48 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("canonicalizes stale promoted draft routes to the server thread route", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-draft-hydration-race-test" as MessageId,
targetText: "draft hydration race test",
}),
});
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.click();
const newThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newDraftId = draftIdFromPath(newThreadPath);
const newThreadId = draftThreadIdFor(newDraftId);
await promoteDraftThreadViaDomainEvent(newThreadId);
await mounted.router.navigate({
to: "/draft/$draftId",
params: { draftId: newDraftId },
});
await waitForURL(
mounted.router,
(path) => path === serverThreadPath(newThreadId),
"Stale promoted draft routes should canonicalize to the server thread path.",
);
await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument();
} finally {
await mounted.cleanup();
}
});
it("snapshots sticky codex settings into a new draft thread", async () => {
useComposerDraftStore.setState({
stickyModelSelectionByProvider: {
@@ -2531,9 +2715,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
const newDraftId = draftIdFromPath(newThreadPath);
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
expect(composerDraftFor(newDraftId)).toMatchObject({
modelSelectionByProvider: {
codex: {
provider: "codex",
@@ -2584,9 +2768,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new sticky claude draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
const newDraftId = draftIdFromPath(newThreadPath);
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
expect(composerDraftFor(newDraftId)).toMatchObject({
modelSelectionByProvider: {
claudeAgent: {
provider: "claudeAgent",
@@ -2624,9 +2808,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID.",
);
const newThreadId = newThreadPath.slice(1) as ThreadId;
const newDraftId = draftIdFromPath(newThreadPath);
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toBeUndefined();
expect(composerDraftFor(newDraftId)).toBe(undefined);
} finally {
await mounted.cleanup();
}
@@ -2666,9 +2850,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a sticky draft thread UUID.",
);
const threadId = threadPath.slice(1) as ThreadId;
const draftId = draftIdFromPath(threadPath);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
expect(composerDraftFor(draftId)).toMatchObject({
modelSelectionByProvider: {
codex: {
provider: "codex",
@@ -2681,7 +2865,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
activeProvider: "codex",
});
useComposerDraftStore.getState().setModelSelection(threadId, {
useComposerDraftStore.getState().setModelSelection(draftId, {
provider: "codex",
model: "gpt-5.4",
options: {
@@ -2697,7 +2881,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => path === threadPath,
"New-thread should reuse the existing project draft thread.",
);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
expect(composerDraftFor(draftId)).toMatchObject({
modelSelectionByProvider: {
codex: {
provider: "codex",
@@ -2804,7 +2988,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a promoted draft thread UUID.",
);
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
const promotedDraftId = draftIdFromPath(promotedThreadPath);
const promotedThreadId = draftThreadIdFor(promotedDraftId);
await promoteDraftThreadViaDomainEvent(promotedThreadId);
@@ -2925,70 +3110,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("does not trigger numeric option shortcuts while the composer is focused", async () => {
it("submits pending user input after the final option selection resolves the draft answers", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotWithPendingUserInput(),
});
try {
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
const event = new KeyboardEvent("keydown", {
key: "2",
bubbles: true,
cancelable: true,
});
composerEditor.dispatchEvent(event);
await waitForLayout();
expect(event.defaultPrevented).toBe(false);
expect(document.body.textContent).toContain("What should this change cover?");
expect(document.body.textContent).not.toContain(
"How aggressive should the imaginary plan be?",
);
await waitForButtonByText("Next question");
} finally {
await mounted.cleanup();
}
});
it("submits multi-select questionnaire answers as arrays", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
snapshot: createSnapshotWithPendingUserInput({
questions: [
{
id: "scope",
header: "Scope",
question: "Which areas should this change cover?",
options: [
{
label: "Server",
description: "Touch server orchestration.",
},
{
label: "Web",
description: "Touch the browser UI.",
},
],
multiSelect: true,
},
{
id: "risk",
header: "Risk",
question: "How aggressive should the imaginary plan be?",
options: [
{
label: "Balanced",
description: "Mix quick wins with one structural improvement.",
},
],
multiSelect: false,
},
],
}),
resolveRpc: (body) => {
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
return {
@@ -3000,37 +3125,11 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
const serverOption = await waitForButtonContainingText("Server");
serverOption.click();
await waitForLayout();
const firstOption = await waitForButtonContainingText("Tight");
firstOption.click();
expect(document.body.textContent).toContain("Which areas should this change cover?");
const webOption = await waitForButtonContainingText("Web");
webOption.click();
await waitForLayout();
expect(document.body.textContent).toContain("Which areas should this change cover?");
const nextButton = await waitForButtonByText("Next question");
expect(nextButton.disabled).toBe(false);
nextButton.click();
await vi.waitFor(
() => {
expect(document.body.textContent).toContain(
"How aggressive should the imaginary plan be?",
);
},
{ timeout: 8_000, interval: 16 },
);
const balancedOption = await waitForButtonContainingText("Balanced");
balancedOption.click();
const submitButton = await waitForButtonByText("Submit answers");
expect(submitButton.disabled).toBe(false);
submitButton.click();
const finalOption = await waitForButtonContainingText("Conservative");
finalOption.click();
await vi.waitFor(
() => {
@@ -3042,6 +3141,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
| {
_tag: string;
type?: string;
requestId?: string;
answers?: Record<string, unknown>;
}
| undefined;
@@ -3049,9 +3149,10 @@ describe("ChatView timeline estimator parity (full app)", () => {
expect(dispatchRequest).toMatchObject({
_tag: ORCHESTRATION_WS_METHODS.dispatchCommand,
type: "thread.user-input.respond",
requestId: "req-browser-user-input",
answers: {
scope: ["Server", "Web"],
risk: "Balanced",
scope: "Tight",
risk: "Conservative",
},
});
},