Skip to content

Commit 16f0fbb

Browse files
committed
fix(web): reuse grouped logical key for New Chat drafts
New Chat looked up and registered drafts from a key re-derived from the selected winner row. buildProjectGroups can take identity from a sibling, so reuse that map key instead. Add TSDoc on the touched helpers.
1 parent 25b2073 commit 16f0fbb

4 files changed

Lines changed: 73 additions & 26 deletions

File tree

‎apps/web/src/hooks/useHandleNewThread.test.ts‎

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -255,8 +255,24 @@ vi.mock("../uiStateStore", () => ({
255255
}));
256256
vi.mock("./useSettings", () => ({ useClientSettings: () => ({}) }));
257257

258+
import { derivePhysicalProjectKey } from "../logicalProject";
259+
import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
258260
import { useNewThreadHandler } from "./useHandleNewThread";
259261

262+
/** Logical key New Chat should register: the group key from `buildProjectGroups`, not a re-derivation. */
263+
function expectedLogicalProjectKey(project: {
264+
environmentId: string;
265+
workspaceRoot: string;
266+
}): string {
267+
return (
268+
buildPhysicalToLogicalProjectKeyMap({
269+
projects: testState.projects,
270+
settings: {},
271+
primaryEnvironmentId: "environment-primary",
272+
}).get(derivePhysicalProjectKey(project)) ?? "remote-project"
273+
);
274+
}
275+
260276
describe.each([
261277
["new", null],
262278
[
@@ -283,7 +299,7 @@ describe.each([
283299
const opened = await pendingOpen;
284300

285301
expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
286-
"remote-project",
302+
expectedLogicalProjectKey(testState.remoteProject),
287303
projectRef,
288304
opened!.draftId,
289305
expect.objectContaining({ runtimeMode }),
@@ -327,7 +343,7 @@ describe.each([
327343
threadId: draft?.threadId ?? "thread-delayed",
328344
});
329345
expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
330-
"remote-project",
346+
expectedLogicalProjectKey(testState.remoteProject),
331347
projectRef,
332348
opened!.draftId,
333349
expect.objectContaining({ envMode: "worktree", startFromOrigin }),
@@ -354,7 +370,7 @@ describe.each([
354370
const opened = await openThread(projectRef, { envMode: "worktree", startFromOrigin });
355371

356372
expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
357-
"remote-project",
373+
expectedLogicalProjectKey(testState.remoteProject),
358374
projectRef,
359375
opened!.draftId,
360376
expect.objectContaining({ envMode: "worktree", startFromOrigin }),
@@ -369,6 +385,7 @@ describe("useNewThreadHandler with a disconnected remote", () => {
369385
projectId: "project-remote",
370386
} as never;
371387

388+
/** Marks the SSH environment reconnecting so New Chat cannot target it. */
372389
function disconnectRemote() {
373390
testState.environments = testState.environments.map((environment) =>
374391
environment.environmentId === "environment-ssh"
@@ -425,7 +442,7 @@ describe("useNewThreadHandler with a disconnected remote", () => {
425442
expect(opened).toEqual({ draftId: "draft-delayed", threadId: "thread-delayed" });
426443
expect(testState.toastAdd).not.toHaveBeenCalled();
427444
expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
428-
"remote-project",
445+
expectedLogicalProjectKey(testState.localProject),
429446
{ environmentId: "environment-primary", projectId: "project-local" },
430447
"draft-delayed",
431448
expect.objectContaining({
@@ -436,6 +453,36 @@ describe("useNewThreadHandler with a disconnected remote", () => {
436453
);
437454
});
438455

456+
it("reuses the group key when the reachable winner has no repository identity", async () => {
457+
testState.reset(null);
458+
const unidentifiedLocal = {
459+
...testState.localProject,
460+
repositoryIdentity: null,
461+
updatedAt: "2026-01-04T00:00:00.000Z",
462+
};
463+
testState.projects = [
464+
{ ...testState.remoteProject, repositoryIdentity: testState.repositoryIdentity },
465+
unidentifiedLocal,
466+
{
467+
...testState.localProject,
468+
id: "project-local-identified",
469+
updatedAt: "2026-01-03T00:00:00.000Z",
470+
},
471+
];
472+
disconnectRemote();
473+
474+
const pendingOpen = useNewThreadHandler()(remoteRef);
475+
testState.completeProjectFileRead(null);
476+
await pendingOpen;
477+
478+
expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
479+
testState.repositoryIdentity.canonicalKey,
480+
{ environmentId: "environment-primary", projectId: "project-local" },
481+
"draft-delayed",
482+
expect.objectContaining({ envMode: "local" }),
483+
);
484+
});
485+
439486
it("keeps the requested worktree when that environment is connected", async () => {
440487
testState.reset(null);
441488
const featureWorktree = {
@@ -453,7 +500,7 @@ describe("useNewThreadHandler with a disconnected remote", () => {
453500
await pendingOpen;
454501

455502
expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
456-
"remote-project",
503+
expectedLogicalProjectKey(featureWorktree),
457504
{ environmentId: "environment-primary", projectId: "project-worktree" },
458505
"draft-delayed",
459506
expect.objectContaining({ envMode: "local" }),

‎apps/web/src/hooks/useHandleNewThread.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import { newDraftId, newThreadId } from "../lib/utils";
2626
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
2727
import {
2828
deriveLogicalProjectKeyFromSettings,
29+
derivePhysicalProjectKey,
2930
getProjectOrderKey,
3031
selectProjectGroupingSettings,
3132
} from "../logicalProject";
@@ -53,9 +54,7 @@ interface NewThreadWorkspaceOptions {
5354
startFromOrigin?: boolean;
5455
}
5556

56-
// The workspace options the caller passed explicitly, shaped for the draft
57-
// store: absent keys stay absent so they never overwrite existing draft
58-
// state. Every reuse path applies exactly this set.
57+
/** Copies only workspace fields the caller passed so reuse cannot clobber stored draft state. */
5958
function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undefined) {
6059
return {
6160
...(options?.branch !== undefined ? { branch: options.branch } : {}),
@@ -65,6 +64,7 @@ function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undef
6564
};
6665
}
6766

67+
/** Opens New Chat on a reachable copy of the requested project, reusing an empty mapped draft. */
6868
export function useNewThreadHandler() {
6969
const environmentServerConfigs = useAtomValue(environmentServerConfigsAtom);
7070
const { environments } = useEnvironments();
@@ -96,15 +96,16 @@ export function useNewThreadHandler() {
9696
environments.find((environment) => environment.environmentId === environmentId)
9797
?.connection.phase,
9898
);
99+
const logicalKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({
100+
projects,
101+
settings: projectGroupingSettings,
102+
primaryEnvironmentId,
103+
});
99104
const projectRef = resolveAvailableNewThreadProjectRef({
100105
requested: requestedProjectRef,
101106
projects,
102107
settings: projectGroupingSettings,
103-
logicalKeyByPhysicalKey: buildPhysicalToLogicalProjectKeyMap({
104-
projects,
105-
settings: projectGroupingSettings,
106-
primaryEnvironmentId,
107-
}),
108+
logicalKeyByPhysicalKey,
108109
isEnvironmentReachable,
109110
primaryEnvironmentId,
110111
});
@@ -211,8 +212,10 @@ export function useNewThreadHandler() {
211212
projectFile,
212213
).settings.defaultThreadEnvMode;
213214
};
215+
// Group key from buildProjectGroups (identitySource), not a re-derivation from the winner row.
214216
const logicalProjectKey = project
215-
? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
217+
? (logicalKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
218+
deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings))
216219
: scopedProjectKey(projectRef);
217220
const hasBranchOption = workspaceOptions?.branch !== undefined;
218221
const hasWorktreePathOption = workspaceOptions?.worktreePath !== undefined;
@@ -494,6 +497,7 @@ export function useNewThreadHandler() {
494497
);
495498
}
496499

500+
/** Chat-view bindings for New Chat: the active thread or draft and the default project to open. */
497501
export function useHandleNewThread() {
498502
const projectOrder = useUiStateStore((store) => store.projectOrder);
499503
const routeTarget = useParams({

‎apps/web/src/lib/chatThreadActions.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ const groupingSettings = {
190190
sidebarProjectGroupingOverrides: {},
191191
};
192192

193+
/** Project fixture for New Chat sibling-resolution cases. */
193194
function makeProject(overrides: Partial<Project> = {}): Project {
194195
return {
195196
id: ProjectId.make("project-1"),

‎apps/web/src/lib/chatThreadActions.ts‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -89,15 +89,12 @@ export function resolveThreadActionProjectRef(
8989
return context.defaultProjectRef;
9090
}
9191

92-
// New Chat must not wait on a down host. Keep the requested checkout when
93-
// that environment can serve — including the active worktree, which is its
94-
// own physical member. Otherwise use a reachable sibling from the same
95-
// logical group.
96-
//
97-
// The logical key comes from the physical-to-logical map. Deriving it from
98-
// the requested row alone misses a stale or unidentified duplicate whose
99-
// repository identity lives on a newer row, so the reachable sibling never
100-
// matches.
92+
/**
93+
* Picks a reachable New Chat target: keep the requested checkout when that host
94+
* can serve, otherwise a sibling from the same logical group. The logical key
95+
* comes from the physical-to-logical map so a stale or unidentified row still
96+
* finds its identified duplicate.
97+
*/
10198
export function resolveAvailableNewThreadProjectRef(input: {
10299
requested: ScopedProjectRef;
103100
projects: ReadonlyArray<EnvironmentProject>;
@@ -148,9 +145,7 @@ export function resolveAvailableNewThreadProjectRef(input: {
148145
: scopeProjectRef(selected.project.environmentId, selected.project.id);
149146
}
150147

151-
// A branch or worktree path belongs to the requested host. Drop those fields
152-
// when New Chat moves to a different environment; keep them for another
153-
// checkout on the same host.
148+
/** Drops branch and worktree path when New Chat retargets to a different environment. */
154149
export function resolveWorkspaceOptionsAfterEnvironmentRetarget<
155150
TOptions extends {
156151
branch?: string | null;

0 commit comments

Comments
 (0)