@devries-cameron20 / t3code Mirror · read-only / commits / 6f8c7433d0
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 00:45 UTC

fix(web): new threads use the last used project

New threads started without an active thread or draft used the first project in sidebar order, even after working in another project. This was visible when creating a draft from Settings or delivering a pending snapshot after reopening the app. Remember the project from the current thread or draft, including its environment, and prefer it when a new draft needs a project. Removed or archived projects fall back to sidebar order. The new-thread keyboard shortcut reads the same preference when invoked. Pending snapshots wait while the remembered environment loads and retry when its project state becomes available. Validation: regression coverage for project selection across environments, missing and archived projects, and a preference changed after shortcut registration. Verified Settings → reload → New thread in the client. `vp run check:changed` covers formatting, lint, affected typechecks, tests, and React compiler checks. Model: GPT 6.1 Sol via the Codex harness.

Yash Singh committed Nov 9, 2026 at 19:44 UTC 6f8c7433d018351caea8e3858105ff2096a37fad
8 files changed +209 -13
apps/web/src/components/Sidebar.browser.test.tsx
+1
@@ -61,6 +61,7 @@ describe("sidebar header new thread", () => {
61 activeDraftThread: null,
62 activeThread: null,
63 defaultProjectRef: currentProjectRef,
64 + defaultProjectFallbackReady: true,
65 handleNewThread: startThread,
66 routeDraftId: null,
67 routeThreadRef: null,
apps/web/src/components/desktop/SnapShotCoordinator.tsx
+37 -4
@@ -13,7 +13,13 @@ import {
13 type PersistedComposerImageAttachment,
14 useComposerDraftStore,
15 } from "../../composerDraftStore";
16 -import { useHandleNewThread } from "../../hooks/useHandleNewThread";
16 +import {
17 + LAST_USED_PROJECT_STORAGE_KEY,
18 + lastUsedProjectKeySchema,
19 + useHandleNewThread,
20 +} from "../../hooks/useHandleNewThread";
21 +import { scopedProjectKey } from "@t3tools/client-runtime/environment";
22 +import { useLocalStorage } from "../../hooks/useLocalStorage";
23 import { useStableCallback } from "../../hooks/useStableCallback";
24 import { getClientSettings, useClientSettings } from "../../hooks/useSettings";
25 import { readThreadShell } from "../../state/entities";
@@ -226,10 +232,30 @@ export function SnapShotCoordinator() {
232 activeDraftThread,
233 activeThread,
234 defaultProjectRef,
235 + defaultProjectFallbackReady,
236 handleNewThread,
237 routeDraftId,
238 routeThreadRef,
239 } = useHandleNewThread();
240 + const [lastUsedProjectKey, setLastUsedProjectKey] = useLocalStorage(
241 + LAST_USED_PROJECT_STORAGE_KEY,
242 + null,
243 + lastUsedProjectKeySchema,
244 + );
245 + const currentProject = activeThread ?? activeDraftThread;
246 + const currentProjectKey = currentProject
247 + ? scopedProjectKey({
248 + environmentId: currentProject.environmentId,
249 + projectId: currentProject.projectId,
250 + })
251 + : null;
252 + const rememberProject = useEffectEvent((projectKey: string) => {
253 + if (projectKey !== lastUsedProjectKey) setLastUsedProjectKey(projectKey);
254 + });
255 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Persist route changes without overwriting project choices from other tabs.
256 + useEffect(() => {
257 + if (currentProjectKey) rememberProject(currentProjectKey);
258 + }, [currentProjectKey]);
259 const captureSound = useClientSettings((settings) =>
260 settings.snapShotPlaySound ? settings.snapShotSound : null,
261 );
@@ -341,6 +367,7 @@ export function SnapShotCoordinator() {
367 ? resolveExistingSnapShotTarget(capturedTarget, routeThreadRef)
368 : null;
369 if (!target) {
370 + if (!defaultProjectFallbackReady) continue;
371 await dismissSnapShotAnimation(item.id);
372 reportOnce(
373 item.id,
@@ -400,6 +427,7 @@ export function SnapShotCoordinator() {
427 };
428
429 const drainPending = useEffectEvent(() => drain());
430 + const hasDefaultProject = defaultProjectRef !== null;
431 const handleSnapShotEvent = useEffectEvent(
432 (bridge: DesktopBridge, event: DesktopSnapShotEvent) => {
433 if (!getClientSettings().snapShotEnabled) return;
@@ -470,10 +498,15 @@ export function SnapShotCoordinator() {
498 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to SnapShot events from the desktop bridge and drains pending ones while enabled
499 useEffect(() => {
500 const bridge = getDesktopSnapShotBridge();
473 - if (!bridge || !enabled) return;
474 - void drainPending();
501 + if (
502 + !bridge ||
503 + !enabled ||
504 + (!defaultProjectFallbackReady && !hasDefaultProject && !lastRouteTarget)
505 + )
506 + return;
507 + void Promise.resolve(drainingRef.current).then(() => drainPending());
508 return bridge.onSnapShotEvent((event) => handleSnapShotEvent(bridge, event));
476 - }, [enabled]);
509 + }, [enabled, defaultProjectFallbackReady, hasDefaultProject, lastRouteTarget]);
510
511 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches window blur, focus and visibilitychange listeners to dismiss or drain SnapShot animations
512 useEffect(() => {
apps/web/src/hooks/useHandleNewThread.test.ts
+44 -4
@@ -1,5 +1,5 @@
1 import { describe, expect, it, vi } from "vite-plus/test";
2 -import type { RuntimeMode } from "@t3tools/contracts";
2 +import type { EnvironmentId, ProjectId, RuntimeMode } from "@t3tools/contracts";
3
4 const testState = vi.hoisted(() => {
5 let completeProjectFileRead: (value: null) => void = () => undefined;
@@ -145,7 +145,8 @@ vi.mock("@effect/atom-react", () => ({
145 : testServerConfigs(),
146 }));
147 vi.mock("@t3tools/client-runtime/environment", () => ({
148 - scopedProjectKey: () => "remote-project",
148 + scopedProjectKey: (ref: { environmentId: string; projectId: string }) =>
149 + `${ref.environmentId}:${ref.projectId}`,
150 scopeProjectRef: (environmentId: string, projectId: string) => ({ environmentId, projectId }),
151 scopeThreadRef: (environmentId: string, threadId: string) => ({ environmentId, threadId }),
152 }));
@@ -183,7 +184,9 @@ vi.mock("react", () => ({
184 useCallback: <T>(callback: T) => callback,
185 useMemo: <T>(factory: () => T) => factory(),
186 }));
186 -vi.mock("../components/Sidebar.logic", () => ({ orderItemsByPreferredIds: () => [] }));
187 +vi.mock("../components/Sidebar.logic", () => ({
188 + orderItemsByPreferredIds: ({ items }: { items: unknown[] }) => items,
189 +}));
190 vi.mock("../composerDraftStore", () => {
191 const useComposerDraftStore = Object.assign(() => null, {
192 getState: () => testState.draftStore,
@@ -230,6 +233,7 @@ vi.mock("../state/entities", () => {
233 useThread: () => null,
234 };
235 });
236 +vi.mock("../state/projects", () => ({ defaultProjectFallbackReadyAtom: () => true }));
237 vi.mock("../state/olderSettledShelf", () => ({ readUnloadedThreadCount: () => 0 }));
238 vi.mock("../state/presentation", () => ({
239 environmentSummaries: { connectedEnvironmentIdsAtom: "connected-environment-ids" },
@@ -247,7 +251,7 @@ vi.mock("../uiStateStore", () => ({
251 }));
252 vi.mock("./useSettings", () => ({ getClientSettings: () => ({}) }));
253
250 -import { useNewThreadHandler } from "./useHandleNewThread";
254 +import { resolveDefaultProjectRef, useNewThreadHandler } from "./useHandleNewThread";
255
256 describe.each([
257 ["new", null],
@@ -365,3 +369,39 @@ describe("useNewThreadHandler", () => {
369 expect(testState.router.navigate).toHaveBeenCalledOnce();
370 });
371 });
372 +
373 +describe("default project selection", () => {
374 + it("prefers the last used project in its environment and falls back when unavailable", () => {
375 + const projects = [
376 + { id: "project", environmentId: "first", workspaceRoot: "/first" },
377 + { id: "project", environmentId: "last-used", workspaceRoot: "/last-used" },
378 + ].map((project) => ({
379 + ...project,
380 + id: project.id as ProjectId,
381 + environmentId: project.environmentId as EnvironmentId,
382 + title: project.environmentId,
383 + defaultModelSelection: null,
384 + scripts: [],
385 + createdAt: "2026-11-09T00:00:00.000Z",
386 + updatedAt: "2026-11-09T00:00:00.000Z",
387 + }));
388 + expect(resolveDefaultProjectRef(projects, [], "last-used:project")).toEqual({
389 + environmentId: "last-used",
390 + projectId: "project",
391 + });
392 + expect(
393 + resolveDefaultProjectRef(projects.slice(0, 1), [], "last-used:project", false),
394 + ).toBeNull();
395 + expect(resolveDefaultProjectRef(projects.slice(0, 1), [], "last-used:project")).toEqual({
396 + environmentId: "first",
397 + projectId: "project",
398 + });
399 + expect(
400 + resolveDefaultProjectRef(
401 + [projects[0]!, { ...projects[1]!, archivedAt: "2026-11-09T00:00:00.000Z" }],
402 + [],
403 + "last-used:project",
404 + ),
405 + ).toEqual({ environmentId: "first", projectId: "project" });
406 + });
407 +});
apps/web/src/hooks/useHandleNewThread.ts
+39 -1
@@ -42,11 +42,26 @@ import { environmentServerConfigsAtom } from "../state/server";
42 import { resolveThreadRouteTarget } from "../threadRoutes";
43 import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
44 import { getClientSettings } from "./useSettings";
45 +import { getLocalStorageItem, useLocalStorage } from "./useLocalStorage";
46 +import * as Schema from "effect/Schema";
47 +import { useAtomValue } from "@effect/atom-react";
48 +import { defaultProjectFallbackReadyAtom } from "../state/projects";
49 import { useThreadRouteTarget } from "./useThreadRouteTarget";
50 import { readUnloadedThreadCount } from "../state/olderSettledShelf";
51 import { resolveProjectDefaultProviderModelSelection } from "../providerInstances";
52 import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";
53
54 +export const LAST_USED_PROJECT_STORAGE_KEY = "t3code:last-used-project:v1";
55 +export const lastUsedProjectKeySchema = Schema.NullOr(Schema.String);
56 +
57 +export function readLastUsedProjectKey(): string | null {
58 + try {
59 + return getLocalStorageItem(LAST_USED_PROJECT_STORAGE_KEY, lastUsedProjectKeySchema);
60 + } catch {
61 + return null;
62 + }
63 +}
64 +
65 interface NewThreadWorkspaceOptions {
66 branch?: string | null;
67 worktreePath?: string | null;
@@ -426,7 +441,16 @@ export function createNewThreadHandler(router: AnyRouter) {
441 export function resolveDefaultProjectRef(
442 projects: ReadonlyArray<EnvironmentProject>,
443 projectOrder: readonly string[],
444 + lastUsedProjectKey: string | null,
445 + fallbackReady = true,
446 ): ScopedProjectRef | null {
447 + const lastUsed = projects.find(
448 + (project) =>
449 + project.archivedAt == null &&
450 + scopedProjectKey(scopeProjectRef(project.environmentId, project.id)) === lastUsedProjectKey,
451 + );
452 + if (lastUsed) return scopeProjectRef(lastUsed.environmentId, lastUsed.id);
453 + if (!fallbackReady) return null;
454 const [defaultProject] = orderItemsByPreferredIds({
455 items: projects.filter((project) => project.archivedAt == null),
456 preferredIds: projectOrder,
@@ -441,6 +465,14 @@ export function resolveDefaultProjectRef(
465
466 export function useHandleNewThread() {
467 const projectOrder = useUiStateStore((store) => store.projectOrder);
468 + const [lastUsedProjectKey] = useLocalStorage(
469 + LAST_USED_PROJECT_STORAGE_KEY,
470 + null,
471 + lastUsedProjectKeySchema,
472 + );
473 + const defaultProjectFallbackReady = useAtomValue(
474 + defaultProjectFallbackReadyAtom(lastUsedProjectKey),
475 + );
476 const routeTarget = useThreadRouteTarget();
477 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
478 const routeDraftId = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
@@ -455,12 +487,18 @@ export function useHandleNewThread() {
487 );
488 const projects = useProjects();
489 const handleNewThread = useNewThreadHandler();
458 - const defaultProjectRef = resolveDefaultProjectRef(projects, projectOrder);
490 + const defaultProjectRef = resolveDefaultProjectRef(
491 + projects,
492 + projectOrder,
493 + lastUsedProjectKey,
494 + defaultProjectFallbackReady,
495 + );
496
497 return {
498 activeDraftThread,
499 activeThread,
500 defaultProjectRef,
501 + defaultProjectFallbackReady,
502 handleNewThread,
503 routeDraftId,
504 routeThreadRef,
apps/web/src/shortcuts/chatRouteCommands.test.ts
+12
@@ -4,8 +4,11 @@ import { describe, expect, it, vi } from "vite-plus/test";
4
5 import * as commandPalette from "../commandPaletteBus";
6 import * as settings from "../hooks/useSettings";
7 +import * as storage from "../hooks/useLocalStorage";
8 import * as threadActions from "../lib/chatThreadActions";
9 import * as entities from "../state/entities";
10 +import * as projectsState from "../state/projects";
11 +import { Atom } from "effect/reactivity";
12 import type { Project } from "../types";
13 import { installChatRouteCommands } from "./chatRouteCommands";
14 import * as dispatcher from "./dispatcher";
@@ -38,6 +41,10 @@ describe("new thread commands", () => {
41 using _projects = vi
42 .spyOn(entities, "readProjects")
43 .mockReturnValue([project("active"), project("idle")].slice(0, scenario.count));
44 + using _ready = vi
45 + .spyOn(projectsState, "defaultProjectFallbackReadyAtom")
46 + .mockReturnValue(Atom.make(true));
47 + using storedProject = vi.spyOn(storage, "getLocalStorageItem").mockReturnValue("local:active");
48 using openPicker = vi.spyOn(commandPalette, "openCommandPalette").mockImplementation(() => {});
49 using startLocal = vi.spyOn(threadActions, "startNewThreadFromContext").mockResolvedValue(true);
50 using register = vi.spyOn(dispatcher, "registerCommands").mockReturnValue(() => {});
@@ -50,6 +57,7 @@ describe("new thread commands", () => {
57 stopPropagation: vi.fn(),
58 } as unknown as KeyboardEvent;
59
60 + storedProject.mockReturnValue("local:idle");
61 commands[scenario.command]!(event);
62
63 if (scenario.picker) {
@@ -58,6 +66,10 @@ describe("new thread commands", () => {
66 } else {
67 expect(openPicker).not.toHaveBeenCalled();
68 expect(startLocal).toHaveBeenCalledOnce();
69 + expect(startLocal.mock.calls[0]![0].defaultProjectRef).toEqual({
70 + environmentId: "local",
71 + projectId: scenario.count === 1 ? "active" : "idle",
72 + });
73 }
74 });
75 });
apps/web/src/shortcuts/chatRouteCommands.ts
+9 -1
@@ -8,7 +8,11 @@ import { useComposerDraftStore } from "../composerDraftStore";
8 import { dispatchPreviewAction, type PreviewAction } from "../components/preview/previewActionBus";
9 import { isAppModalPage } from "../components/sidebar/mainAppLocation";
10 import { shouldCreateNewThreadInCurrentProject } from "../components/Sidebar.logic";
11 -import { createNewThreadHandler, resolveDefaultProjectRef } from "../hooks/useHandleNewThread";
11 +import {
12 + createNewThreadHandler,
13 + readLastUsedProjectKey,
14 + resolveDefaultProjectRef,
15 +} from "../hooks/useHandleNewThread";
16 import { createScratchProjectActions } from "../hooks/useScratchProject";
17 import { getClientSettings } from "../hooks/useSettings";
18 import { startNewThreadFromContext } from "../lib/chatThreadActions";
@@ -17,6 +21,7 @@ import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
21 import { appAtomRegistry } from "../rpc/atomRegistry";
22 import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";
23 import { readProjects, readThreadShell } from "../state/entities";
24 +import { defaultProjectFallbackReadyAtom } from "../state/projects";
25 import { environmentPresentations } from "../state/presentation";
26 import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
27 import { readEnvironmentScope } from "../state/session";
@@ -59,6 +64,7 @@ export function installChatRouteCommands(router: AnyRouter): () => void {
64 : false;
65 };
66 const readThreadContext = () => {
67 + const lastUsedProjectKey = readLastUsedProjectKey();
68 const target = readRouteTarget();
69 const drafts = useComposerDraftStore.getState();
70 const activeThread = target?.kind === "server" ? readThreadShell(target.threadRef) : null;
@@ -73,6 +79,8 @@ export function installChatRouteCommands(router: AnyRouter): () => void {
79 defaultProjectRef: resolveDefaultProjectRef(
80 readProjects(),
81 useUiStateStore.getState().projectOrder,
82 + lastUsedProjectKey,
83 + appAtomRegistry.get(defaultProjectFallbackReadyAtom(lastUsedProjectKey)),
84 ),
85 handleNewThread,
86 };
apps/web/src/state/projects.ts
+32 -1
@@ -5,7 +5,10 @@ import { WS_METHODS } from "@t3tools/contracts";
5
6 import { environmentCatalog } from "../connection/catalog";
7 import { connectionAtomRuntime } from "../connection/runtime";
8 -import { environmentSnapshotAtom } from "./shell";
8 +import { environmentShell, environmentSnapshotAtom, expectsPrimaryEnvironment } from "./shell";
9 +import { parseScopedProjectKey } from "@t3tools/client-runtime/environment";
10 +import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection";
11 +import { AsyncResult, Atom } from "effect/reactivity";
12 import { serverEnvironment } from "./server";
13
14 export const environmentProjects = createEnvironmentProjectAtoms({
@@ -22,3 +25,31 @@ export const projectContentSearch = createEnvironmentRpcQueryAtomFamily(connecti
25 staleTimeMs: 5_000,
26 idleTtlMs: 60_000,
27 });
28 +
29 +export const defaultProjectFallbackReadyAtom = Atom.family((projectKey: string | null) =>
30 + Atom.make((get) => {
31 + const remembered = projectKey === null ? null : parseScopedProjectKey(projectKey);
32 + if (!remembered) return true;
33 + const catalog = get(environmentCatalog.catalogValueAtom);
34 + if (!catalog.isReady) return false;
35 + if (
36 + expectsPrimaryEnvironment() &&
37 + !Array.from(catalog.entries.values()).some(
38 + (entry) => entry.target._tag === "PrimaryConnectionTarget",
39 + )
40 + )
41 + return false;
42 + const entry = catalog.entries.get(remembered.environmentId);
43 + if (!entry?.enabled || entry.unsupportedReason !== undefined) return true;
44 + if (get(environmentShell.statusAtom(remembered.environmentId)) === "live") return true;
45 + const connection = AsyncResult.getOrElse(
46 + get(environmentCatalog.stateAtom(remembered.environmentId)),
47 + () => AVAILABLE_CONNECTION_STATE,
48 + );
49 + return (
50 + connection.phase === "offline" ||
51 + connection.phase === "blocked" ||
52 + (connection.phase === "backoff" && connection.attempt > 2)
53 + );
54 + }).pipe(Atom.withLabel(`web-default-project-fallback-ready:${projectKey}`)),
55 +);
apps/web/src/state/shell.test.ts
+35 -2
@@ -1,4 +1,5 @@
1 import {
2 + AVAILABLE_CONNECTION_STATE,
3 BearerConnectionTarget,
4 PrimaryConnectionTarget,
5 } from "@t3tools/client-runtime/connection";
@@ -6,10 +7,16 @@ import type { EnvironmentCatalogState } from "@t3tools/client-runtime/state/conn
7 import { EMPTY_SHELL_STATE, type EnvironmentShellState } from "@t3tools/client-runtime/state/shell";
8 import { EnvironmentId } from "@t3tools/contracts";
9 import * as Option from "effect/Option";
9 -import { Atom, AtomRegistry } from "effect/reactivity";
10 +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11 import { describe, expect, it, vi } from "vite-plus/test";
12
12 -import { createAllEnvironmentProjectSnapshotsReadyAtom, expectsPrimaryEnvironment } from "./shell";
13 +import {
14 + createAllEnvironmentProjectSnapshotsReadyAtom,
15 + expectsPrimaryEnvironment,
16 + environmentShell,
17 +} from "./shell";
18 +import { environmentCatalog } from "../connection/catalog";
19 +import { defaultProjectFallbackReadyAtom } from "./projects";
20
21 const LOCAL = EnvironmentId.make("local");
22 const REMOTE = EnvironmentId.make("remote");
@@ -148,3 +155,29 @@ it("expects a primary environment only on desktops with the local environment en
155 expect(desktop(true)).toBe(true);
156 expect(desktop(false)).toBe(false);
157 });
158 +
159 +it.each([undefined, "", "Server update required"])(
160 + "settles fallback for an unsupported remembered environment: %s",
161 + (unsupportedReason) => {
162 + const catalog = catalogState([LOCAL, REMOTE]);
163 + const entries = new Map(catalog.entries);
164 + entries.set(REMOTE, {
165 + ...entries.get(REMOTE)!,
166 + ...(unsupportedReason === undefined ? {} : { unsupportedReason }),
167 + });
168 + const registry = AtomRegistry.make({
169 + initialValues: [
170 + [environmentCatalog.catalogValueAtom, { ...catalog, entries }],
171 + [environmentShell.statusAtom(REMOTE), "empty"],
172 + [environmentCatalog.stateAtom(REMOTE), AsyncResult.success(AVAILABLE_CONNECTION_STATE)],
173 + ],
174 + });
175 + try {
176 + expect(registry.get(defaultProjectFallbackReadyAtom("remote:project"))).toBe(
177 + unsupportedReason !== undefined,
178 + );
179 + } finally {
180 + registry.dispose();
181 + }
182 + },
183 +);