Skip to content

Commit 89a2929

Browse files
fix: preserve handovers across async races
2 parents 2f3fa5e + f47a3fe commit 89a2929

18 files changed

Lines changed: 363 additions & 68 deletions

File tree

‎apps/mobile/src/features/settings/SettingsRouteScreen.tsx‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
type ServerSettingsPatch,
4545
} from "@t3tools/contracts";
4646
import {
47+
filterSharedServerPatch,
4748
findSharedSettingsMismatches,
4849
pickSharedServerSettings,
4950
supportsSharedSettingsSync,
@@ -584,11 +585,13 @@ function AutoSettleSettingsRows() {
584585
const mismatches = findSharedSettingsMismatches({
585586
primaryEnvironmentId: reference.environmentId,
586587
primarySettings: referenceSettings,
588+
primaryCapabilities: reference.serverConfig?.environment.capabilities,
587589
environments: environments.map((environment) => ({
588590
environmentId: environment.environmentId,
589591
label: environment.label,
590592
syncEligible: supportsSharedSettingsSync(environment),
591593
settings: environment.serverConfig?.settings ?? null,
594+
capabilities: environment.serverConfig?.environment.capabilities,
592595
})),
593596
});
594597

@@ -652,11 +655,22 @@ function AutoSettleSettingsRows() {
652655
<Pressable
653656
accessibilityRole="button"
654657
onPress={() => {
655-
const patch = pickSharedServerSettings(referenceSettings);
658+
const patch = pickSharedServerSettings(
659+
referenceSettings,
660+
reference.serverConfig?.environment.capabilities,
661+
);
656662
for (const mismatch of mismatches) {
663+
const target = environments.find(
664+
(candidate) => candidate.environmentId === mismatch.environmentId,
665+
);
657666
void updateSettings({
658667
environmentId: mismatch.environmentId,
659-
input: { patch },
668+
input: {
669+
patch: filterSharedServerPatch(
670+
patch,
671+
target?.serverConfig?.environment.capabilities,
672+
),
673+
},
660674
});
661675
}
662676
}}

‎apps/mobile/src/features/threads/ThreadRouteScreen.tsx‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -356,19 +356,21 @@ function ThreadRouteContent(
356356
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
357357
);
358358
const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
359-
const selectedThreadKeyRef = useRef(
360-
selectedThread ? scopedThreadKey(selectedThread.environmentId, selectedThread.id) : null,
359+
const selectedHandoverKeyRef = useRef(
360+
selectedThread
361+
? threadHandoverDraftImportId(selectedThread.environmentId, selectedThread.id)
362+
: null,
361363
);
362-
selectedThreadKeyRef.current = selectedThread
363-
? scopedThreadKey(selectedThread.environmentId, selectedThread.id)
364+
selectedHandoverKeyRef.current = selectedThread
365+
? threadHandoverDraftImportId(selectedThread.environmentId, selectedThread.id)
364366
: null;
365-
const currentThreadKey = selectedThread
366-
? scopedThreadKey(selectedThread.environmentId, selectedThread.id)
367+
const currentHandoverKey = selectedThread
368+
? threadHandoverDraftImportId(selectedThread.environmentId, selectedThread.id)
367369
: null;
368370
const handoverState = useSyncExternalStore(
369371
subscribeMobileHandoverState,
370-
() => mobileHandoverStateSnapshot(currentThreadKey),
371-
() => mobileHandoverStateSnapshot(currentThreadKey),
372+
() => mobileHandoverStateSnapshot(currentHandoverKey),
373+
() => mobileHandoverStateSnapshot(currentHandoverKey),
372374
);
373375
const isGeneratingHandover = handoverState.startsWith("true:");
374376
const mountedRef = useRef(true);
@@ -386,11 +388,11 @@ function ThreadRouteContent(
386388
!selectedThreadProject ||
387389
!selectedThreadDetail ||
388390
serverConfig?.environment.capabilities.threadHandoverGeneration !== true ||
389-
currentThreadKey === null
391+
currentHandoverKey === null
390392
) {
391393
return;
392394
}
393-
const sourceThreadKey = currentThreadKey;
395+
const sourceThreadKey = currentHandoverKey;
394396
if (generatingMobileHandovers.has(sourceThreadKey)) return;
395397
generatingMobileHandovers.add(sourceThreadKey);
396398
notifyMobileHandoverListeners();
@@ -420,7 +422,7 @@ function ThreadRouteContent(
420422
if (
421423
!mountedRef.current ||
422424
!isFocusedRef.current ||
423-
selectedThreadKeyRef.current !== sourceThreadKey
425+
selectedHandoverKeyRef.current !== sourceThreadKey
424426
) {
425427
return;
426428
}
@@ -455,7 +457,7 @@ function ThreadRouteContent(
455457
if (
456458
!mountedRef.current ||
457459
!isFocusedRef.current ||
458-
selectedThreadKeyRef.current !== sourceThreadKey
460+
selectedHandoverKeyRef.current !== sourceThreadKey
459461
) {
460462
return;
461463
}
@@ -481,7 +483,7 @@ function ThreadRouteContent(
481483
notifyMobileHandoverListeners();
482484
}
483485
}, [
484-
currentThreadKey,
486+
currentHandoverKey,
485487
generateThreadHandover,
486488
isFocused,
487489
navigation,

‎apps/mobile/src/state/threadHandoverDraft.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
2+
import { threadHandoverSourceKey } from "@t3tools/shared/threadReference";
23

34
/**
45
* Stable receipt for importing one source thread's handover into its project
@@ -9,5 +10,5 @@ export function threadHandoverDraftImportId(
910
environmentId: EnvironmentId,
1011
threadId: ThreadId,
1112
): string {
12-
return `handover:${JSON.stringify([environmentId, threadId])}`;
13+
return threadHandoverSourceKey(environmentId, threadId);
1314
}

‎apps/server/src/environment/ServerEnvironment.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
175175
expect(second.capabilities.usagePriceOverrides).toBe(true);
176176
expect(second.capabilities.threadTitleRegeneration).toBe(true);
177177
expect(second.capabilities.threadPullRequestLinking).toBe(true);
178+
expect(second.capabilities.threadRestartContinuation).toBe(true);
178179
expect(second.capabilities.agentActivityPublishing).toBe(false);
179180
expect(second.capabilities.threadHandoverGeneration).toBe(false);
180181
}),

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ const makeWithProviderRegistry = (
229229
pullRequests: true,
230230
threadSettlement: true,
231231
threadAutoSettlement: true,
232+
threadRestartContinuation: true,
232233
threadSnooze: true,
233234
environmentThemes: true,
234235
usageLimitSources: true,

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@ import {
4848
} from "@t3tools/shared/model";
4949
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
5050
import { truncate } from "@t3tools/shared/String";
51-
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
51+
import {
52+
resolveThreadReferenceCopyTarget,
53+
threadHandoverSourceKey,
54+
} from "@t3tools/shared/threadReference";
5255
import {
5356
getTerminalLabel,
5457
nextTerminalId,
@@ -1381,8 +1384,18 @@ export default function ChatView(props: ChatViewProps) {
13811384
[environmentId, threadId],
13821385
);
13831386
const routeThreadKey = useMemo(() => scopedThreadKey(routeThreadRef), [routeThreadRef]);
1384-
const routeThreadKeyRef = useRef(routeThreadKey);
1385-
routeThreadKeyRef.current = routeThreadKey;
1387+
const routeHandoverKey = useMemo(
1388+
() => threadHandoverSourceKey(routeThreadRef.environmentId, routeThreadRef.threadId),
1389+
[routeThreadRef],
1390+
);
1391+
const routeHandoverKeyRef = useRef<string | null>(routeHandoverKey);
1392+
routeHandoverKeyRef.current = routeHandoverKey;
1393+
useEffect(() => {
1394+
routeHandoverKeyRef.current = routeHandoverKey;
1395+
return () => {
1396+
routeHandoverKeyRef.current = null;
1397+
};
1398+
}, [routeHandoverKey]);
13861399
const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false });
13871400
const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
13881401
reportFailure: false,
@@ -5437,7 +5450,9 @@ export default function ChatView(props: ChatViewProps) {
54375450
isStoppingBackgroundWork,
54385451
]);
54395452
const [, setHandoverStateVersion] = useState(0);
5440-
const activeThreadHandoverKey = activeThread ? routeThreadKey : null;
5453+
const activeThreadHandoverKey = activeThread
5454+
? threadHandoverSourceKey(activeThread.environmentId, activeThread.id)
5455+
: null;
54415456
const isGeneratingHandover = activeThreadHandoverKey
54425457
? generatingThreadHandovers.has(activeThreadHandoverKey)
54435458
: false;
@@ -5486,7 +5501,7 @@ export default function ChatView(props: ChatViewProps) {
54865501
const handoverAttempt = attempt;
54875502
const handover = handoverAttempt.handover;
54885503

5489-
if (routeThreadKeyRef.current !== sourceThreadKey) {
5504+
if (routeHandoverKeyRef.current !== sourceThreadKey) {
54905505
return;
54915506
}
54925507

@@ -5554,6 +5569,7 @@ export default function ChatView(props: ChatViewProps) {
55545569
const contextLimitBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
55555570
if (!activeThreadReachedContextLimit || !activeThread) return null;
55565571
const supportsGeneration =
5572+
activeProject !== null &&
55575573
serverConfig?.environment.capabilities.threadHandoverGeneration === true;
55585574
return buildContextLimitBannerItem({
55595575
threadId: activeThread.id,
@@ -5574,6 +5590,7 @@ export default function ChatView(props: ChatViewProps) {
55745590
}, [
55755591
activeThread,
55765592
activeThreadReachedContextLimit,
5593+
activeProject,
55775594
environmentId,
55785595
handleGenerateHandover,
55795596
isGeneratingHandover,

‎apps/web/src/components/settings/SettingsPanels.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2490,7 +2490,7 @@ export function GeneralSettingsPanel() {
24902490
<SettingsRow
24912491
{...searchableSetting("continue-threads-after-server-update")}
24922492
serverScoped
2493-
description="Automatically resume interrupted threads when this environment starts again after an update, crash, or machine restart."
2493+
description="Automatically resume interrupted threads after an update, crash, or machine restart. Applies to this environment and all connected environments that support it. Update older servers first."
24942494
resetAction={
24952495
settings.continueThreadsAfterServerUpdate !==
24962496
DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate ? (

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

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { EnvironmentId, ProjectId, type ScopedProjectRef } from "@t3tools/contracts";
12
import { describe, expect, it, vi } from "vite-plus/test";
23

34
const testState = vi.hoisted(() => {
@@ -13,13 +14,19 @@ const testState = vi.hoisted(() => {
1314
let storedDraft: StoredDraft | null = null;
1415
let prompts: Record<string, string> = {};
1516
let navigationFailure: Error | null = null;
17+
let completeNavigation: (() => void) | null = null;
1618
const router = {
1719
state: {
1820
location: { href: "/" },
1921
matches: [{ params: {} }],
2022
},
2123
navigate: vi.fn(async (request: { readonly params: { readonly draftId: string } }) => {
2224
if (navigationFailure !== null) throw navigationFailure;
25+
if (completeNavigation !== null) {
26+
await new Promise<void>((resolve) => {
27+
completeNavigation = resolve;
28+
});
29+
}
2330
router.state.location.href = `/draft/${request.params.draftId}`;
2431
}),
2532
};
@@ -73,6 +80,7 @@ const testState = vi.hoisted(() => {
7380
: { ...nextStoredDraft, logicalProjectKey: "remote-project" };
7481
prompts = {};
7582
navigationFailure = null;
83+
completeNavigation = null;
7684
router.state.location.href = "/";
7785
router.navigate.mockClear();
7886
draftStore.setLogicalProjectDraftThreadId.mockClear();
@@ -82,6 +90,13 @@ const testState = vi.hoisted(() => {
8290
});
8391
},
8492
router,
93+
holdNavigation() {
94+
completeNavigation = () => undefined;
95+
},
96+
releaseNavigation() {
97+
completeNavigation?.();
98+
completeNavigation = null;
99+
},
85100
setNavigationFailure(error: Error | null) {
86101
navigationFailure = error;
87102
},
@@ -96,7 +111,11 @@ vi.mock("@t3tools/client-runtime/environment", () => ({
96111
scopeProjectRef: (environmentId: string, projectId: string) => ({ environmentId, projectId }),
97112
scopeThreadRef: (environmentId: string, threadId: string) => ({ environmentId, threadId }),
98113
}));
99-
vi.mock("@t3tools/contracts", () => ({ DEFAULT_RUNTIME_MODE: "default" }));
114+
vi.mock("@t3tools/contracts", () => ({
115+
DEFAULT_RUNTIME_MODE: "default",
116+
EnvironmentId: { make: (value: string) => value },
117+
ProjectId: { make: (value: string) => value },
118+
}));
100119
vi.mock("@t3tools/shared/threadEnvMode", () => ({
101120
resolveDefaultThreadEnvMode: (input: {
102121
readonly projectFile: "local" | "worktree" | null;
@@ -252,4 +271,30 @@ describe("useNewThreadHandler", () => {
252271
expect(testState.draftStore.setPrompt).toHaveBeenCalledOnce();
253272
expect(testState.router.navigate).toHaveBeenCalledTimes(2);
254273
});
274+
275+
it("does not deliver a raced handover into another invocation's draft", async () => {
276+
testState.reset(null);
277+
testState.holdNavigation();
278+
const openThread = useNewThreadHandler();
279+
const projectRef = {
280+
environmentId: EnvironmentId.make("environment-ssh"),
281+
projectId: ProjectId.make("project-remote"),
282+
} satisfies ScopedProjectRef;
283+
const ordinaryOpen = openThread(projectRef);
284+
const onHandoverDraftReady = vi.fn();
285+
const handoverOpen = openThread(projectRef, {
286+
initialPrompt: "Generated handover",
287+
onDraftReady: onHandoverDraftReady,
288+
});
289+
290+
testState.completeProjectFileRead(null);
291+
292+
await expect(handoverOpen).resolves.toBeNull();
293+
expect(testState.draftStore.setPrompt).not.toHaveBeenCalled();
294+
expect(onHandoverDraftReady).not.toHaveBeenCalled();
295+
expect(testState.router.navigate).toHaveBeenCalledOnce();
296+
297+
testState.releaseNavigation();
298+
await expect(ordinaryOpen).resolves.toMatchObject({ draftId: "draft-delayed" });
299+
});
255300
});

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,13 @@ export function useNewThreadHandler() {
424424
racedDraft.draftId !== storedDraftThread?.draftId &&
425425
readThreadShell(scopeThreadRef(racedDraft.environmentId, racedDraft.threadId)) === null
426426
) {
427+
// A caller-specific prompt belongs to this invocation, not to the
428+
// winner that registered while defaults were loading. Report the
429+
// collision so the caller can retain/recover its payload instead of
430+
// treating an untouched winner as a successful delivery.
431+
if (options?.initialPrompt !== undefined) {
432+
return null;
433+
}
427434
// Same remap the reuse paths above perform: point the draft at the
428435
// caller's project member and apply explicit workspace options if
429436
// the caller passed any. Without explicit options the winner's
@@ -439,7 +446,6 @@ export function useNewThreadHandler() {
439446
interactionMode: racedDraft.interactionMode,
440447
...pickExplicitWorkspaceOptions(options),
441448
});
442-
prepareDraft(racedDraft.draftId);
443449
await router.navigate({
444450
to: "/draft/$draftId",
445451
params: { draftId: racedDraft.draftId },

0 commit comments

Comments
 (0)