Skip to content

Commit 22bcb07

Browse files
refactor(web): chat view, composer and timeline stop syncing state
ChatView, the composer core, timeline follow, sidebar, terminal drawer and command palette read stores and the router at use time. This layer also carries ThreadRouteView, the _chat route, the sidebar location, announcer and visited-time migration services, and onboarding's wizard. Effect categories removed: - latest-value ref mirrors in the composer and ChatView replaced by reads of the draft store, router and committed DOM at use time - composer registries (typing guard, responding state, open question attachments, uploads) moved to thread-keyed stores and a reconciler - timeline scroll, follow and position restore driven by the viewport handle and a follow state machine; citations load from a procedure - palette event bus moved to a store; chat route, chat, paste and window refocus listeners register once from dispatcher scopes and the chat root ref callback - draft route promotion effects replaced by rendering the store's redirect; thread change and terminal focus moved to handlers - terminal output and height mirrors replaced by a session subscription and a controlled store - optimistic messages, diff scope, file tabs, sidebar drops and details card mode moved to stores, render-time reconciles and app subscriptions - sidebar route reveal, scope and snooze wakes derived in render and from row ref callbacks; location and announcements run as services Bugs fixed: - Chat route shortcuts ran in an order that depended on render history. - Drafts promoted while off screen never finalized until visited. - Onboarding stuck after pairing finished, or spun forever on import. - Sidebar scopes were erased when a project left; many elapsed snooze wakes crashed the sidebar. - Uploads re-ran on every attachment change; queued-edit uploads stuck. - The find shortcut during a thread switch said find was unavailable. - Position restore re-ran on every row change; a fullscreen app pin kept follow off after a thread switch. - Citations to responses outside the loaded history failed at once. - A question could look answerable while its response was in flight, and a focused composer switching threads stopped holding requests. - An acknowledged message rendered twice for one commit. - A palette intent while open kept the previous session's state. - File tabs of a removed project only closed when that thread was active. - Switching to a thread with its terminal open pulled focus into it. Kept effects: - Timeline position restore and follow anchor release: must land before paint after the commit that changes the list. - Prompt editor editable, attribute and value sync: Tiptap's API. - Composer resting visibility and FLIP microtask: wait on a CSS rework. - Sidebar ordering mirror, drag cancel and list motion: post-commit. - Resume-compaction persistence and work-locally resend: server-driven. - Terminal surface setup: imperative WASM widget. Removes compat shims added lower in the stack: - rightPanelStore.ts (added in layer 05) - browserFaviconStore.ts (added in layer 05) - composerDraftStore.ts (added in layer 02) - appInit.tsx (added in layer 10) - routes/__root.tsx (added in layer 10) Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c98f581 commit 22bcb07

110 files changed

Lines changed: 7455 additions & 6697 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/web/src/appInit.tsx‎

Lines changed: 87 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,20 @@ import { applyAppearanceContrast } from "./appearanceContrast";
88
import { applyAppearanceFontVariables } from "./appearanceFonts";
99
import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
1010
import { resolveServerBackedAppDisplayName } from "./branding.logic";
11-
import { subscribeComposerDraftModelReconciliation } from "./composerDraftStore";
11+
import {
12+
subscribeComposerDraftModelReconciliation,
13+
subscribeDraftThreadPromotion,
14+
useComposerDraftStore,
15+
} from "./composerDraftStore";
16+
import { startDraftAttachmentUploads } from "./attachmentUploads";
17+
import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
18+
import { focusTerminalOnThreadEnter } from "./lib/terminalFocus";
1219
import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter";
20+
import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
1321
import { startElectronBrowserHost } from "./browser/ElectronBrowserHost";
1422
import { startIndexDraftStart } from "./components/indexDraftStart";
1523
import { startNewThreadLinks } from "./components/promptLinks/openNewThreadLink";
24+
import { startThreadLinkPrompts } from "./components/promptLinks/threadLinkPrompts";
1625
import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
1726
import { KeybindingsConfigWarning } from "./components/KeybindingsConfigWarning";
1827
import { createKeybindingsUpdateToastController } from "./components/KeybindingsUpdateToast.logic";
@@ -23,10 +32,13 @@ import { startGuideRunNotifications } from "./components/pullRequest/guide/PullR
2332
import { installReopenClosedViewCommands } from "./components/ReopenClosedViewShortcut";
2433
import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator";
2534
import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
35+
import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
2636
import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
2737
import { startDesktopAppActivation } from "./components/desktop/DesktopAppActivationCoordinator";
2838
import { startDesktopWebLinks } from "./components/desktop/DesktopWebLinkCoordinator";
39+
import { startSnapShotCoordinator } from "./components/desktop/SnapShotCoordinator";
2940
import { startFirstRunGate, whileFirstRunAppOpen } from "./components/onboarding/firstRunGateStore";
41+
import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
3042
import { startPreviewTitleRecording } from "./browserHistoryStore";
3143
import { stackedThreadToast, toastManager } from "./components/ui/toast";
3244
import { isElectron } from "./env";
@@ -38,7 +50,8 @@ import {
3850
subscribeClientSettings,
3951
} from "./hooks/useSettings";
4052
import { syncBrowserChromeTheme } from "./hooks/useTheme";
41-
import { installDesktopPasteAsText } from "./lib/desktopPasteAsText";
53+
import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
54+
import "./lib/desktopPasteAsText";
4255
import {
4356
syncDocumentElectronPlatformClasses,
4457
syncDocumentWindowControlsOverlayClass,
@@ -51,16 +64,24 @@ import {
5164
import { startProviderAuthDelivery } from "./providerAuthDelivery";
5265
import { getRouter, type AppRouter } from "./router";
5366
import { appAtomRegistry } from "./rpc/atomRegistry";
67+
import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
68+
import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
69+
import { retainPendingFileDropsForThread } from "./sidebarPendingFileDropStore";
70+
import { retainThreadFindForThread } from "./components/chat/threadFindStore";
5471
import { primaryEnvironmentIdAtom } from "./state/primaryEnvironment";
5572
import { readProject } from "./state/entities";
73+
import { environmentProjects } from "./state/projects";
5674
import {
5775
primaryServerConfigAtom,
5876
primaryServerConfigEventAtom,
5977
primaryServerWelcomeAtom,
6078
} from "./state/server";
6179
import { environmentShell, liveShellEnvironmentIdsAtom } from "./state/shell";
6280
import { environmentThreadShells } from "./state/threads";
81+
import { resolveThreadRouteTarget } from "./threadRoutes";
6382
import { useUiStateStore } from "./uiStateStore";
83+
import { useRightPanelStore } from "./rightPanelStore";
84+
import { Atom } from "effect/reactivity";
6485

6586
/** Writes appearance settings onto the document, touching only the groups that changed. */
6687
function startClientAppearance(): void {
@@ -221,13 +242,72 @@ function startComposerDraftServices(): void {
221242
threadRefsAtom: environmentThreadShells.threadRefsAtom,
222243
shellStateAtom: environmentShell.stateAtom,
223244
});
245+
subscribeDraftThreadPromotion({
246+
registry: appAtomRegistry,
247+
threadShellAtom: environmentThreadShells.quietThreadShellAtom,
248+
threadRefsAtom: environmentThreadShells.threadRefsAtom,
249+
});
250+
startDraftAttachmentUploads();
251+
}
252+
253+
/** A thread's workspace file tabs close once its project is gone from a loaded snapshot. */
254+
function startFileSurfaceReconciliation(): void {
255+
const projectsChangedAtom = Atom.make((get) => [
256+
get(environmentProjects.projectsAtom),
257+
get(liveShellEnvironmentIdsAtom),
258+
]);
259+
appAtomRegistry.subscribe(
260+
projectsChangedAtom,
261+
() =>
262+
useRightPanelStore.getState().reconcileAllFileSurfaces((ref) => {
263+
if (!appAtomRegistry.get(environmentShell.hasSnapshotAtom(ref.environmentId))) return null;
264+
const projectId =
265+
appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref))?.projectId ??
266+
useComposerDraftStore.getState().getDraftThread(ref)?.projectId;
267+
if (projectId === undefined) return null;
268+
return readProject(scopeProjectRef(ref.environmentId, projectId)) !== null;
269+
}),
270+
{ immediate: true },
271+
);
224272
}
225273

226274
function startRouteServices(router: AppRouter): void {
275+
installChatRouteCommands(router);
276+
installCommandPaletteCommands(router);
227277
installReopenClosedViewCommands(router);
278+
startMainAppLocationTracking(router);
228279
startIndexDraftStart(router);
280+
startThreadLinkPrompts(router);
229281
startNewThreadLinks(router);
230282

283+
let enteredThreadKey: string | null = null;
284+
router.subscribe("onResolved", () => {
285+
// Draft-promotion redirects and sidebar file drops only serve the route they lead to.
286+
const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
287+
useComposerDraftStore.getState().retainPromotedDraftRedirectsForRoute(target);
288+
retainPendingFileDropsForThread(target?.kind === "server" ? target.threadRef : null);
289+
retainThreadFindForThread(target?.kind === "server" ? target.threadRef : null);
290+
// Chat overlays belong to the thread they were opened in.
291+
const draftSession =
292+
target?.kind === "draft"
293+
? useComposerDraftStore.getState().getDraftSession(target.draftId)
294+
: null;
295+
const threadRef =
296+
target?.kind === "server"
297+
? target.threadRef
298+
: draftSession
299+
? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
300+
: null;
301+
const threadKey = threadRef ? scopedThreadKey(threadRef) : null;
302+
retainThreadOverlaysForThread(threadKey);
303+
// Arriving at a thread with its drawer open focuses the drawer terminal;
304+
// otherwise ChatView focuses the composer.
305+
if (threadKey !== enteredThreadKey) {
306+
enteredThreadKey = threadKey;
307+
if (threadRef) focusTerminalOnThreadEnter(threadRef);
308+
}
309+
});
310+
231311
// Each route paints its own surface, which the browser chrome samples once it is on screen.
232312
// onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
233313
// can swap the root between the bare outlet and the shell at the same address.
@@ -236,8 +316,6 @@ function startRouteServices(router: AppRouter): void {
236316
router.subscribe("onResolved", resyncBrowserChrome);
237317
}
238318

239-
// Compat shim until the web-chat-view layer: services the base chat view and
240-
// sidebar still run themselves are not started here yet.
241319
/**
242320
* Starts every app-lifetime service once, before the first render, and returns the router.
243321
* They run for the life of the page, so their disposers (kept for tests) are dropped here.
@@ -254,14 +332,15 @@ export function startAppServices(): AppRouter {
254332
syncDocumentWindowControlsOverlayClass();
255333
}
256334

257-
installDesktopPasteAsText(window.desktopBridge, window);
258335
startClientAppearance();
259336
startDocumentTitle();
260337
startEnvironmentThemeRepaint();
261338
startDefaultThemeAdoption();
262339
startModelPreferencesMigration();
263340

264341
startComposerDraftServices();
342+
startFileSurfaceReconciliation();
343+
startAgentOpenedPreviews();
265344
startPreviewTitleRecording();
266345
startBrowserProfileReporting();
267346
if (isElectron) startElectronBrowserHost();
@@ -271,6 +350,7 @@ export function startAppServices(): AppRouter {
271350
if (isElectron) {
272351
startDesktopAppActivation(router);
273352
startDesktopWebLinks(router);
353+
whileFirstRunAppOpen(() => startSnapShotCoordinator(router));
274354
}
275355

276356
startKeybindingsUpdateToasts();
@@ -280,6 +360,8 @@ export function startAppServices(): AppRouter {
280360
startPermissionUpdateNotices(router);
281361
startProjectCloneToasts(router);
282362
startThreadNotifications(appAtomRegistry, router);
363+
startBackgroundThreadAnnouncements(appAtomRegistry, router);
364+
startThreadVisitedMigration(appAtomRegistry);
283365
startGuideRunNotifications(appAtomRegistry, router);
284366
if (isElectron) startDesktopUpdateLaunchNotice();
285367

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2+
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3+
import { describe, expect, it, vi } from "vite-plus/test";
4+
5+
import {
6+
type AttachmentUploadPolicy,
7+
planAttachmentUploads,
8+
planDraftUploadsForPolicies,
9+
} from "./attachmentUploads";
10+
import {
11+
DraftId,
12+
QUEUED_EDIT_DRAFT_PREFIX,
13+
type ComposerFileAttachment,
14+
type ComposerImageAttachment,
15+
type ComposerThreadDraftState,
16+
} from "./composerDraftStore";
17+
import { questionAttachmentDraftId } from "./questionAttachments";
18+
19+
vi.mock("./lib/attachmentUploadQueue", () => ({
20+
releaseAttachmentUpload: vi.fn(),
21+
releaseDraftAttachments: vi.fn(),
22+
startAttachmentUpload: vi.fn(),
23+
}));
24+
vi.mock("./state/server", async () => {
25+
const { Atom } = await import("effect/reactivity");
26+
return { environmentServerConfigsAtom: Atom.make(new Map()) };
27+
});
28+
vi.mock("./state/session", async () => {
29+
const { Atom } = await import("effect/reactivity");
30+
return { environmentSession: { sessionStateAtom: () => Atom.make(null) } };
31+
});
32+
33+
const environmentId = EnvironmentId.make("environment-1");
34+
const otherEnvironmentId = EnvironmentId.make("environment-2");
35+
const threadRef = scopeThreadRef(environmentId, ThreadId.make("thread-1"));
36+
const threadKey = scopedThreadKey(threadRef);
37+
const policy: AttachmentUploadPolicy = { supported: true, maxFileBytes: 10, canOperate: true };
38+
39+
function image(id: string): ComposerImageAttachment {
40+
return {
41+
type: "image",
42+
id,
43+
name: `${id}.png`,
44+
mimeType: "image/png",
45+
sizeBytes: 4,
46+
previewUrl: `blob:${id}`,
47+
file: new File(["png"], `${id}.png`, { type: "image/png" }),
48+
};
49+
}
50+
51+
function file(
52+
id: string,
53+
sizeBytes = 4,
54+
extra: Partial<ComposerFileAttachment> = {},
55+
): ComposerFileAttachment {
56+
return {
57+
type: "file",
58+
id,
59+
name: `${id}.pdf`,
60+
mimeType: "application/pdf",
61+
sizeBytes,
62+
file: new File(["pdf"], `${id}.pdf`, { type: "application/pdf" }),
63+
...extra,
64+
} as ComposerFileAttachment;
65+
}
66+
67+
function draft(
68+
attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
69+
): ComposerThreadDraftState {
70+
return {
71+
images: attachments.filter((attachment) => attachment.type === "image"),
72+
files: attachments.filter((attachment) => attachment.type === "file"),
73+
} as ComposerThreadDraftState;
74+
}
75+
76+
const ids = (attachments: ReadonlyArray<{ readonly id: string }>) =>
77+
attachments.map((attachment) => attachment.id);
78+
79+
describe("planAttachmentUploads", () => {
80+
it("starts images and files that fit, releases oversized files", () => {
81+
const plan = planAttachmentUploads(policy, [image("a"), file("small"), file("big", 11)]);
82+
expect(ids(plan.start)).toEqual(["a", "small"]);
83+
expect(ids(plan.release)).toEqual(["big"]);
84+
});
85+
86+
it("releases only unpersisted uploads when the capability is gone", () => {
87+
const persisted = file("persisted", 4, {
88+
uploadEnvironmentId: environmentId,
89+
uploadedAttachmentId: "server-copy",
90+
});
91+
const plan = planAttachmentUploads({ ...policy, supported: false }, [image("a"), persisted]);
92+
expect(ids(plan.release)).toEqual(["a"]);
93+
expect(plan.start).toEqual([]);
94+
});
95+
96+
it("starts nothing without operate access, and no files without a size limit", () => {
97+
expect(
98+
planAttachmentUploads({ ...policy, canOperate: false }, [image("a"), file("f")]),
99+
).toEqual({ release: [], start: [] });
100+
const unlimited = planAttachmentUploads({ ...policy, maxFileBytes: null }, [
101+
image("a"),
102+
file("f"),
103+
]);
104+
expect(ids(unlimited.start)).toEqual(["a"]);
105+
expect(ids(unlimited.release)).toEqual(["f"]);
106+
});
107+
});
108+
109+
describe("planDraftUploadsForPolicies", () => {
110+
const policies = new Map([
111+
[environmentId, policy],
112+
[otherEnvironmentId, policy],
113+
]);
114+
115+
it("re-plans every attachment of drafts in a changed environment only", () => {
116+
const otherKey = scopedThreadKey(scopeThreadRef(otherEnvironmentId, ThreadId.make("t2")));
117+
const state = {
118+
draftsByThreadKey: {
119+
[threadKey]: draft([image("a"), file("f")]),
120+
[otherKey]: draft([image("b")]),
121+
},
122+
draftThreadsByThreadKey: {},
123+
};
124+
const work = planDraftUploadsForPolicies(new Map(), state, policies, new Set([environmentId]));
125+
expect(work.map((entry) => [entry.draftTarget, ids(entry.start)])).toEqual([
126+
[threadRef, ["a", "f"]],
127+
]);
128+
});
129+
130+
it("uses the environment the add named for a queued-edit draft", () => {
131+
const key = `${QUEUED_EDIT_DRAFT_PREFIX}${threadKey}:run-1`;
132+
const draftTarget = DraftId.make(key);
133+
const state = {
134+
draftsByThreadKey: { [key]: draft([image("a")]) },
135+
draftThreadsByThreadKey: {},
136+
};
137+
expect(planDraftUploadsForPolicies(new Map(), state, policies, null)).toEqual([]);
138+
const targets = new Map([[key, { environmentId, draftTarget }]]);
139+
const work = planDraftUploadsForPolicies(targets, state, policies, new Set([environmentId]));
140+
expect(work.map((entry) => [entry.environmentId, entry.draftTarget, ids(entry.start)])).toEqual(
141+
[[environmentId, draftTarget, ["a"]]],
142+
);
143+
});
144+
145+
it("restores a draft session's environment and releases on capability loss", () => {
146+
const key = "draft-1";
147+
const state = {
148+
draftsByThreadKey: { [key]: draft([image("a")]) },
149+
draftThreadsByThreadKey: { [key]: { environmentId: otherEnvironmentId } },
150+
};
151+
const lost = planDraftUploadsForPolicies(
152+
new Map(),
153+
state,
154+
new Map([[otherEnvironmentId, { ...policy, supported: false }]]),
155+
null,
156+
);
157+
expect(lost.map((work) => [work.environmentId, ids(work.release)])).toEqual([
158+
[otherEnvironmentId, ["a"]],
159+
]);
160+
});
161+
162+
it("plans a draft session in its current environment, not the one its adds named", () => {
163+
const key = "draft-moved";
164+
const draftTarget = DraftId.make(key);
165+
const state = {
166+
draftsByThreadKey: { [key]: draft([image("a")]) },
167+
draftThreadsByThreadKey: { [key]: { environmentId: otherEnvironmentId } },
168+
};
169+
const targets = new Map([[key, { environmentId, draftTarget }]]);
170+
expect(planDraftUploadsForPolicies(targets, state, policies, new Set([environmentId]))).toEqual(
171+
[],
172+
);
173+
const work = planDraftUploadsForPolicies(targets, state, policies, null);
174+
expect(work.map((entry) => [entry.environmentId, entry.draftTarget])).toEqual([
175+
[otherEnvironmentId, draftTarget],
176+
]);
177+
});
178+
179+
it("uploads question drafts to the environment encoded in their key", () => {
180+
const key = questionAttachmentDraftId(environmentId, threadRef.threadId, "request", "q1");
181+
const work = planDraftUploadsForPolicies(
182+
new Map(),
183+
{ draftsByThreadKey: { [key]: draft([image("a")]) }, draftThreadsByThreadKey: {} },
184+
policies,
185+
null,
186+
);
187+
expect(work.map((entry) => [entry.environmentId, entry.draftTarget])).toEqual([
188+
[environmentId, key],
189+
]);
190+
});
191+
192+
it("forgets targets of drafts that no longer exist", () => {
193+
const targets = new Map([["gone", { environmentId, draftTarget: DraftId.make("gone") }]]);
194+
planDraftUploadsForPolicies(
195+
targets,
196+
{ draftsByThreadKey: {}, draftThreadsByThreadKey: {} },
197+
policies,
198+
null,
199+
);
200+
expect(targets.size).toBe(0);
201+
});
202+
});

0 commit comments

Comments
 (0)