Skip to content

Commit bacd935

Browse files
fix(queue): wait for edit acquisition before reconciling ownership
1 parent 9304967 commit bacd935

13 files changed

Lines changed: 153 additions & 34 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
147147
if (result._tag !== "Success") return;
148148
void Haptics.selectionAsync();
149149
beginQueuedRunEdit(threadKey, {
150-
editId: result.value,
150+
...result.value,
151151
runId,
152152
messageId: entry.messageId,
153153
originalText: entry.text,

‎apps/mobile/src/state/queued-run-edit.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const image = (id: string): ChatAttachment => ({
2424
function edit(attachments: ReadonlyArray<ChatAttachment>): QueuedRunEdit {
2525
return {
2626
editId: CommandId.make("edit-1"),
27+
sequence: 1,
2728
runId: RunId.make("run-1"),
2829
messageId: MessageId.make("message-1"),
2930
originalText: "original",

‎apps/mobile/src/state/queued-run-edit.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
} from "./use-composer-drafts";
3535

3636
export interface QueuedRunEdit {
37+
readonly sequence: number;
3738
readonly editId: CommandId;
3839
readonly runId: RunId;
3940
readonly messageId: MessageId;

‎apps/mobile/src/state/use-thread-composer-state.ts‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
2929
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
3030
import { nextPastedTextFileName, pastedTextDisposition } from "@t3tools/client-runtime/text-paste";
3131
import {
32+
EMPTY_ENVIRONMENT_THREAD_STATE,
3233
parseCodexFeedbackCommand,
34+
queuedRunEditOwnership,
3335
submitCodexFeedback,
3436
type CodexFeedbackSubmission,
3537
} from "@t3tools/client-runtime/state/threads";
@@ -112,6 +114,7 @@ import { useAtomCommand } from "./use-atom-command";
112114
const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
113115
Atom.withLabel("mobile-thread-queue-workflow:empty"),
114116
);
117+
const EMPTY_THREAD_STATE_ATOM = Atom.make(EMPTY_ENVIRONMENT_THREAD_STATE);
115118

116119
export function appendReviewCommentToDraft(input: {
117120
readonly environmentId: EnvironmentId;
@@ -183,6 +186,14 @@ export function useThreadComposerState() {
183186
selectedEnvironmentRuntime,
184187
} = useThreadSelection();
185188
const selectedThreadProjection = useSelectedThreadProjection();
189+
const selectedThreadState = useAtomValue(
190+
selectedThreadShell === null
191+
? EMPTY_THREAD_STATE_ATOM
192+
: environmentThreadDetails.stateAtom({
193+
environmentId: selectedThreadShell.environmentId,
194+
threadId: selectedThreadShell.id,
195+
}),
196+
);
186197
const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
187198
const composerDrafts = useAtomValue(composerDraftsAtom);
188199
const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom);
@@ -430,19 +441,14 @@ export function useThreadComposerState() {
430441
// Another client can start or cancel the run, or end or take over its edit,
431442
// while its message is open. Leave edit mode rather than saving into a run the
432443
// server will refuse, and keep whatever was typed if there is room for it.
433-
const selectedThreadRuns = selectedThreadProjection?.projection.runs;
434444
const editedRunId = queuedRunEdit?.runId ?? null;
435-
const editedRunEditId = queuedRunEdit?.editId ?? null;
445+
const editOwnership =
446+
queuedRunEdit === null ? null : queuedRunEditOwnership(selectedThreadState, queuedRunEdit);
436447
useEffect(() => {
437-
if (selectedThreadKey === null || editedRunId === null || selectedThreadRuns === undefined) {
448+
if (selectedThreadKey === null || editedRunId === null || editOwnership !== "lost") {
438449
return;
439450
}
440451
if (isSavingQueuedEdit || savingQueuedEditRef.current) return;
441-
const stillOwned = selectedThreadRuns.some(
442-
(run) =>
443-
run.id === editedRunId && run.status === "queued" && run.queueEditId === editedRunEditId,
444-
);
445-
if (stillOwned) return;
446452
const editDraftKey = queuedEditDraftKey(selectedThreadKey, editedRunId);
447453
const editDraft = getComposerDraftSnapshot(editDraftKey);
448454
const threadDraft = getComposerDraftSnapshot(selectedThreadKey);
@@ -464,7 +470,7 @@ export function useThreadComposerState() {
464470
? "That queued message edit ended. Your edit is back in the composer."
465471
: "That queued message edit ended, so the edit was discarded.",
466472
);
467-
}, [editedRunId, editedRunEditId, isSavingQueuedEdit, selectedThreadKey, selectedThreadRuns]);
473+
}, [editedRunId, editOwnership, isSavingQueuedEdit, selectedThreadKey]);
468474

469475
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
470476
const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
@@ -478,9 +484,8 @@ export function useThreadComposerState() {
478484
savingQueuedEditRef.current = true;
479485
setIsSavingQueuedEdit(true);
480486
try {
481-
const currentRun = selectedThreadRuns?.find((run) => run.id === edit.runId);
482487
const result =
483-
currentRun !== undefined && currentRun.queueEditId !== edit.editId
488+
queuedRunEditOwnership(selectedThreadState, edit) === "lost"
484489
? null
485490
: await cancelQueuedEdit({
486491
environmentId: selectedThreadShell.environmentId,
@@ -491,7 +496,7 @@ export function useThreadComposerState() {
491496
savingQueuedEditRef.current = false;
492497
setIsSavingQueuedEdit(false);
493498
}
494-
}, [cancelQueuedEdit, selectedThreadKey, selectedThreadRuns, selectedThreadShell]);
499+
}, [cancelQueuedEdit, selectedThreadKey, selectedThreadState, selectedThreadShell]);
495500

496501
const onRemoveQueuedEditAttachment = useCallback(
497502
(attachmentId: string) => {

‎apps/server/src/orchestration-v2/QueuedRunEditing.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ import {
1111
import * as DateTime from "effect/DateTime";
1212
import * as Effect from "effect/Effect";
1313
import * as Exit from "effect/Exit";
14+
import type { ProviderAdapterV2 } from "@t3tools/provider-core/server/ProviderAdapter";
1415

1516
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
1617
import * as EventSink from "./EventSink.ts";
1718
import * as Orchestrator from "./Orchestrator.ts";
1819
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
19-
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
2020
import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
2121

2222
const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "test" };
@@ -26,7 +26,7 @@ const adapter = {
2626
getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
2727
planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
2828
openSession: () => Effect.die("provider execution is disabled in queue editing tests"),
29-
} as ProviderAdapterV2Shape;
29+
} satisfies ProviderAdapterV2["Service"];
3030
const layer = ProviderReplayHarness.layerWithRegistry(
3131
{ name: "queued-run-editing" },
3232
ProviderAdapterRegistry.layerFromAdapters([adapter]),

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

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider";
2+
import * as Option from "effect/Option";
23
import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
34
import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
45
import {
@@ -110,6 +111,7 @@ import { threadSupportsProviderHandoff } from "@t3tools/client-runtime/state/thr
110111
import {
111112
codexFeedbackMessage,
112113
parseCodexFeedbackCommand,
114+
queuedRunEditOwnership,
113115
shouldShowLoadEarlierControl,
114116
submitCodexFeedback,
115117
type CodexFeedbackSubmission,
@@ -424,7 +426,7 @@ import {
424426
useEnvironmentSupportsServerBrowser,
425427
useProject,
426428
useProjects,
427-
useThreadProjection,
429+
useThreadState,
428430
useThreadStatus,
429431
useThreadHistory,
430432
useThreadShell,
@@ -1678,6 +1680,7 @@ export default function ChatView(props: ChatViewProps) {
16781680
// keeps (removal is client state until save).
16791681
const [editingQueuedRun, setEditingQueuedRun] = useState<{
16801682
readonly editId: CommandId;
1683+
readonly sequence: number;
16811684
readonly threadId: ThreadId;
16821685
readonly runId: RunId;
16831686
readonly messageId: MessageId;
@@ -1707,8 +1710,8 @@ export default function ChatView(props: ChatViewProps) {
17071710
shellExists: serverThread !== null,
17081711
waitForShell: draftThread !== null,
17091712
});
1710-
const serverThreadProjection = useThreadProjection(routeThreadDetailRef);
1711-
const serverProjection = serverThreadProjection?.projection ?? null;
1713+
const serverThreadState = useThreadState(routeThreadDetailRef);
1714+
const serverProjection = Option.getOrNull(serverThreadState.data);
17121715
const reportedModelSelection = serverProjection
17131716
? deriveReportedModelSelection(serverProjection)
17141717
: null;
@@ -4701,7 +4704,7 @@ export default function ChatView(props: ChatViewProps) {
47014704
setComposerDraftPrompt(target, request.text);
47024705
}
47034706
setEditingQueuedRun({
4704-
editId: result.value,
4707+
...result.value,
47054708
threadId: activeThread.id,
47064709
runId: request.runId,
47074710
messageId: request.messageId,
@@ -4730,9 +4733,8 @@ export default function ChatView(props: ChatViewProps) {
47304733
queuedEditSaveInFlightRef.current = true;
47314734
setIsSavingQueuedEdit(true);
47324735
try {
4733-
const currentRun = serverProjection?.runs.find((run) => run.id === editingQueuedRun.runId);
47344736
const result =
4735-
currentRun !== undefined && currentRun.queueEditId !== editingQueuedRun.editId
4737+
queuedRunEditOwnership(serverThreadState, editingQueuedRun) === "lost"
47364738
? null
47374739
: await cancelQueuedRunEditCommand({
47384740
environmentId,
@@ -4753,7 +4755,7 @@ export default function ChatView(props: ChatViewProps) {
47534755
}, [
47544756
cancelQueuedRunEditCommand,
47554757
environmentId,
4756-
serverProjection,
4758+
serverThreadState,
47574759
clearComposerDraftContent,
47584760
editingQueuedRun,
47594761
queuedEditDraftTargetFor,
@@ -4782,8 +4784,7 @@ export default function ChatView(props: ChatViewProps) {
47824784
}
47834785
if (serverProjection === null || isSavingQueuedEdit || queuedEditSaveInFlightRef.current)
47844786
return;
4785-
const run = serverProjection.runs.find((candidate) => candidate.id === editingQueuedRun.runId);
4786-
if (run?.status === "queued" && run.queueEditId === editingQueuedRun.editId) return;
4787+
if (queuedRunEditOwnership(serverThreadState, editingQueuedRun) !== "lost") return;
47874788
const recovery = recoverQueuedMessageEdit({
47884789
editTarget: queuedEditDraftTargetFor(editingQueuedRun.runId),
47894790
threadTarget: baseComposerDraftTarget,
@@ -4814,6 +4815,7 @@ export default function ChatView(props: ChatViewProps) {
48144815
isSavingQueuedEdit,
48154816
queuedEditDraftTargetFor,
48164817
serverProjection,
4818+
serverThreadState,
48174819
]);
48184820
const addTerminalContextToDraft = useCallback(
48194821
(selection: TerminalContextSelection) => {

‎apps/web/src/state/entities.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
} from "@t3tools/client-runtime/state/shell";
77
import {
88
EMPTY_THREAD_HISTORY_META,
9+
EMPTY_ENVIRONMENT_THREAD_STATE,
910
type EnvironmentThreadStatus,
1011
type ThreadHistoryMeta,
1112
} from "@t3tools/client-runtime/state/threads";
@@ -40,6 +41,7 @@ const EMPTY_THREAD_SHELL_ATOM = Atom.make<EnvironmentThreadShell | null>(null).p
4041
const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
4142
Atom.withLabel("web-thread-projection:empty"),
4243
);
44+
const EMPTY_THREAD_STATE_ATOM = Atom.make(EMPTY_ENVIRONMENT_THREAD_STATE);
4345
const EMPTY_THREAD_STATUS_ATOM = Atom.make<EnvironmentThreadStatus>("empty").pipe(
4446
Atom.withLabel("web-thread-status:empty"),
4547
);
@@ -129,6 +131,12 @@ export function useThreadProjection(ref: ScopedThreadRef | null): EnvironmentThr
129131
);
130132
}
131133

134+
export function useThreadState(ref: ScopedThreadRef | null) {
135+
return useAtomValue(
136+
ref === null ? EMPTY_THREAD_STATE_ATOM : environmentThreadDetails.stateAtom(ref),
137+
);
138+
}
139+
132140
export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadStatus {
133141
return useAtomValue(
134142
ref === null ? EMPTY_THREAD_STATUS_ATOM : environmentThreadDetails.statusAtom(ref),

‎packages/client-runtime/src/operations/commands.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -732,7 +732,7 @@ describe("V2 environment commands", () => {
732732
supervisor,
733733
);
734734
const runId = RunId.make("editing-run");
735-
const editId = yield* beginQueuedRunEdit({
735+
const { editId, sequence } = yield* beginQueuedRunEdit({
736736
commandId: CommandId.make("begin-edit"),
737737
threadId: v2ThreadId,
738738
runId,
@@ -752,6 +752,7 @@ describe("V2 environment commands", () => {
752752
editId,
753753
}).pipe(provide);
754754
expect(editId).toBe("begin-edit");
755+
expect(sequence).toBe(1);
755756
expect(commands).toMatchObject([
756757
{ type: "queued-run.edit.begin", commandId: editId, previousEditId: null },
757758
{ type: "queued-run.edit", editId, text: "Revised" },

‎packages/client-runtime/src/operations/commands.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,14 +1075,14 @@ export const beginQueuedRunEdit = Effect.fn("EnvironmentCommands.beginQueuedRunE
10751075
input: BeginQueuedRunEditInput,
10761076
) {
10771077
const commandId = yield* allocateCommandId(input);
1078-
yield* dispatch({
1078+
const { sequence } = yield* dispatch({
10791079
type: "queued-run.edit.begin",
10801080
commandId,
10811081
threadId: input.threadId,
10821082
runId: input.runId,
10831083
previousEditId: input.previousEditId,
10841084
});
1085-
return commandId;
1085+
return { editId: commandId, sequence };
10861086
});
10871087

10881088
export const cancelQueuedRunEdit = Effect.fn("EnvironmentCommands.cancelQueuedRunEdit")(function* (

‎packages/client-runtime/src/state/threadDetail.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ function threadState(
2828
partial: Pick<EnvironmentThreadState, "data" | "status" | "error"> &
2929
Partial<Pick<EnvironmentThreadState, "history">>,
3030
): EnvironmentThreadState {
31-
return { ...partial, history: partial.history ?? EMPTY_THREAD_HISTORY_META };
31+
return { sequence: 0, ...partial, history: partial.history ?? EMPTY_THREAD_HISTORY_META };
3232
}
3333

3434
describe("createEnvironmentThreadDetailAtoms", () => {

0 commit comments

Comments
 (0)