Skip to content
Merged
Prev Previous commit
Next Next commit
fix(composer): retain model picks until live shell confirmation
  • Loading branch information
juliusmarminge committed Oct 19, 2026
commit 66069a3d74f12e3520999f2251131461ceb96a45
2 changes: 2 additions & 0 deletions apps/mobile/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { RootStack } from "./Stack";
import { appAtomRegistry } from "./state/atom-registry";
import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
import { environmentThreadShells } from "./state/threads";
import { environmentShell } from "./state/shell";
import { OverlayPortalHost } from "./components/ui/OverlayPortal";
import { shouldHandleAppLink } from "./lib/appLinking";
import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
Expand Down Expand Up @@ -65,6 +66,7 @@ export default function App() {
registry: appAtomRegistry,
threadShellAtom: environmentThreadShells.threadShellAtom,
threadRefsAtom: environmentThreadShells.threadRefsAtom,
shellStateAtom: environmentShell.stateAtom,
}),
[],
);
Expand Down
79 changes: 64 additions & 15 deletions apps/mobile/src/state/use-composer-drafts.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads";
import { applyShellStreamEvent } from "@t3tools/client-runtime/state/shell";
import {
applyShellStreamEvent,
createEnvironmentSnapshotAtom,
type EnvironmentShellState,
type EnvironmentShellStatus,
} from "@t3tools/client-runtime/state/shell";
import {
v2ShellSnapshot,
v2ThreadShell,
} from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
import * as Option from "effect/Option";
import { Atom, AtomRegistry } from "effect/reactivity";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { afterEach, describe, expect, it } from "@effect/vitest";
import {
CommandId,
Expand Down Expand Up @@ -253,7 +258,11 @@ function contextDraft(start: number, count: number): ComposerDraft {
};
}

function modelReconciliationHarness(environmentId: EnvironmentId, threadId: ThreadId) {
function modelReconciliationHarness(
environmentId: EnvironmentId,
threadId: ThreadId,
initialStatus: EnvironmentShellStatus = "live",
) {
const tasks: Array<() => void> = [];
const registry = AtomRegistry.make({
scheduleTask: (task) => {
Expand All @@ -266,13 +275,20 @@ function modelReconciliationHarness(environmentId: EnvironmentId, threadId: Thre
for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();
};
const selectedThreadId = ThreadId.make("another-selected-thread");
const snapshotAtom = Atom.make<OrchestrationV2ShellSnapshot>({
const initialSnapshot: OrchestrationV2ShellSnapshot = {
...v2ShellSnapshot,
threads: [
{ ...v2ThreadShell, id: threadId },
{ ...v2ThreadShell, id: selectedThreadId },
],
};
const shellStateAtom = Atom.make<EnvironmentShellState>({
snapshot: Option.some(initialSnapshot),
status: initialStatus,
error: Option.none(),
});
const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);
const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);
const catalogValueAtom = Atom.make({
isReady: true,
entries: new Map([
Expand Down Expand Up @@ -302,21 +318,31 @@ function modelReconciliationHarness(environmentId: EnvironmentId, threadId: Thre
registry,
threadShellAtom: shells.threadShellAtom,
threadRefsAtom: shells.threadRefsAtom,
shellStateAtom: () => shellResultAtom,
}),
);
flush();
return {
update(changes: Partial<OrchestrationV2ThreadShell>) {
const snapshot = registry.get(snapshotAtom);
registry.set(
snapshotAtom,
applyShellStreamEvent(snapshot, {
kind: "thread.updated",
location: "active",
sequence: snapshot.snapshotSequence + 1,
thread: { ...snapshot.threads[0]!, ...changes },
}),
);
flush,
setStatus(status: EnvironmentShellStatus) {
registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });
flush();
},
update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) {
const state = registry.get(shellStateAtom);
const snapshot = Option.getOrThrow(state.snapshot);
registry.set(shellStateAtom, {
...state,
status: status ?? state.status,
snapshot: Option.some(
applyShellStreamEvent(snapshot, {
kind: "thread.updated",
location: "active",
sequence: snapshot.snapshotSequence + 1,
thread: { ...snapshot.threads[0]!, ...changes },
}),
),
});
flush();
expect(registry.get(selectedShell)?.id).toBe(selectedThreadId);
},
Expand Down Expand Up @@ -510,6 +536,29 @@ describe("mobile composer drafts", () => {
expect(draft.text).toContain(String(record?.contextId));
});

it("retains a pick matching cached state until the live shell confirms it", () => {
const environmentId = EnvironmentId.make("environment-1");
const threadId = ThreadId.make("thread-1");
const key = `${environmentId}:${threadId}`;
const h = modelReconciliationHarness(environmentId, threadId, "cached");
const pick = h.model();
updateComposerDraftSettings(key, { modelSelection: pick });
h.flush();
const before = getComposerDraftSnapshot(key);
expect(before.modelSelection).toEqual(pick);

for (const status of ["empty", "synchronizing", "cached"] as const) {
h.setStatus(status);
expect(getComposerDraftSnapshot(key)).toEqual(before);
}
h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live");
expect(getComposerDraftSnapshot(key)).toEqual(before);
h.update({ modelSelection: pick }, "synchronizing");
expect(getComposerDraftSnapshot(key)).toEqual(before);
h.setStatus("live");
expect(appAtomRegistry.get(composerDraftsAtom)[key]).toBeUndefined();
});

it("releases an inactive thread pick only after its queued model becomes durable", () => {
const environmentId = EnvironmentId.make("environment-1");
const threadId = ThreadId.make("thread-1");
Expand Down
26 changes: 23 additions & 3 deletions apps/mobile/src/state/use-composer-drafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,13 @@ import {
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { useEffect } from "react";
import { Atom, type AtomRegistry } from "effect/reactivity";
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
import * as Option from "effect/Option";
import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentShellState,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { draftModelPickMatchesThread } from "@t3tools/shared/model";

import { writeFileAtomically } from "../lib/atomic-file";
Expand Down Expand Up @@ -1465,6 +1469,9 @@ export function subscribeComposerDraftModelReconciliation(input: {
readonly registry: AtomRegistry.AtomRegistry;
readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;
readonly shellStateAtom: (
environmentId: EnvironmentId,
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
}): () => void {
const draftsAtom = Atom.make(appAtomRegistry.get(composerDraftsAtom));
const unsubscribeDrafts = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) =>
Expand All @@ -1482,7 +1489,20 @@ export function subscribeComposerDraftModelReconciliation(input: {
const ref = parseScopedThreadKey(key);
if (!ref || !threadKeys.has(key)) continue;
const thread = get(input.threadShellAtom(ref));
if (thread && draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection)) {
if (!thread || !draftModelPickMatchesThread(draft.modelSelection, thread.modelSelection))
continue;
// Status and selection must come from the same emission; derived atoms can update apart.
const shell = Option.getOrNull(
AsyncResult.value(get(input.shellStateAtom(ref.environmentId))),
);
if (shell?.status !== "live") continue;
const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(
(candidate) => candidate.id === ref.threadId,
);
if (
authoritativeThread &&
draftModelPickMatchesThread(draft.modelSelection, authoritativeThread.modelSelection)
) {
matches.push([key, draft]);
}
}
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/AppRoot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useEffect } from "react";

import { subscribeComposerDraftModelReconciliation } from "./composerDraftStore";
import { environmentThreadShells } from "./state/threads";
import { environmentShell } from "./state/shell";

import { BrowserProfileReporter } from "./browser/BrowserProfileReporter";
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
Expand All @@ -22,6 +23,7 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
registry: appAtomRegistry,
threadShellAtom: environmentThreadShells.threadShellAtom,
threadRefsAtom: environmentThreadShells.threadRefsAtom,
shellStateAtom: environmentShell.stateAtom,
}),
[],
);
Expand Down
76 changes: 61 additions & 15 deletions apps/web/src/composerDraftStore.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads";
import { applyShellStreamEvent } from "@t3tools/client-runtime/state/shell";
import {
applyShellStreamEvent,
createEnvironmentSnapshotAtom,
type EnvironmentShellState,
type EnvironmentShellStatus,
} from "@t3tools/client-runtime/state/shell";
import { makeThreadProjectionFixture } from "./test-fixtures";
import * as Option from "effect/Option";
import { Atom, AtomRegistry } from "effect/reactivity";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import {
scopedProjectKey,
scopedThreadKey,
Expand Down Expand Up @@ -1922,7 +1927,11 @@ describe("composerDraftStore project draft thread mapping", () => {
});
});

function modelReconciliationHarness(environmentId: EnvironmentId, threadId: ThreadId) {
function modelReconciliationHarness(
environmentId: EnvironmentId,
threadId: ThreadId,
initialStatus: EnvironmentShellStatus = "live",
) {
const tasks: Array<() => void> = [];
const registry = AtomRegistry.make({
scheduleTask: (task) => {
Expand All @@ -1947,7 +1956,7 @@ function modelReconciliationHarness(environmentId: EnvironmentId, threadId: Thre
itemCount: 0,
visibleItemCount: 0,
};
const snapshotAtom = Atom.make<OrchestrationV2ShellSnapshot>({
const initialSnapshot: OrchestrationV2ShellSnapshot = {
schemaVersion: 1,
snapshotSequence: 0,
projects: [],
Expand All @@ -1956,7 +1965,14 @@ function modelReconciliationHarness(environmentId: EnvironmentId, threadId: Thre
{ ...thread, id: threadId },
{ ...thread, id: selectedThreadId },
],
};
const shellStateAtom = Atom.make<EnvironmentShellState>({
snapshot: Option.some(initialSnapshot),
status: initialStatus,
error: Option.none(),
});
const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);
const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);
const catalogValueAtom = Atom.make({
isReady: true,
entries: new Map([
Expand Down Expand Up @@ -1986,21 +2002,31 @@ function modelReconciliationHarness(environmentId: EnvironmentId, threadId: Thre
registry,
threadShellAtom: shells.threadShellAtom,
threadRefsAtom: shells.threadRefsAtom,
shellStateAtom: () => shellResultAtom,
}),
);
flush();
return {
update(changes: Partial<OrchestrationV2ThreadShell>) {
const snapshot = registry.get(snapshotAtom);
registry.set(
snapshotAtom,
applyShellStreamEvent(snapshot, {
kind: "thread.updated",
location: "active",
sequence: snapshot.snapshotSequence + 1,
thread: { ...snapshot.threads[0]!, ...changes },
}),
);
flush,
setStatus(status: EnvironmentShellStatus) {
registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status });
flush();
},
update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) {
const state = registry.get(shellStateAtom);
const snapshot = Option.getOrThrow(state.snapshot);
registry.set(shellStateAtom, {
...state,
status: status ?? state.status,
snapshot: Option.some(
applyShellStreamEvent(snapshot, {
kind: "thread.updated",
location: "active",
sequence: snapshot.snapshotSequence + 1,
thread: { ...snapshot.threads[0]!, ...changes },
}),
),
});
flush();
expect(registry.get(selectedShell)?.id).toBe(selectedThreadId);
},
Expand Down Expand Up @@ -2036,6 +2062,26 @@ describe("composerDraftStore modelSelection", () => {
);
});

it("retains a pick matching cached state until the live shell confirms it", () => {
const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId, "cached");
const pick = h.model();
useComposerDraftStore.getState().setModelSelection(threadRef, pick, { explicit: true });
h.flush();
const before = draftFor(threadId, TEST_ENVIRONMENT_ID);
expect(before?.modelSelectionByProvider[pick.instanceId]).toEqual(pick);

for (const status of ["empty", "synchronizing", "cached"] as const) {
h.setStatus(status);
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
}
h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live");
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
h.update({ modelSelection: pick }, "synchronizing");
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before);
h.setStatus("live");
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined();
});

it("releases an inactive thread pick only after its queued model becomes durable", () => {
const store = useComposerDraftStore.getState();
const pick = modelSelection(CODEX_DRIVER, "gpt-5.5", { fastMode: false });
Expand Down
25 changes: 22 additions & 3 deletions apps/web/src/composerDraftStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,12 @@ import {
draftModelPickMatchesThread,
normalizeModelSlug,
} from "@t3tools/shared/model";
import { Atom, type AtomRegistry } from "effect/reactivity";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
import * as Option from "effect/Option";
import type {
EnvironmentShellState,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { getLocalStorageItem } from "./hooks/useLocalStorage";
import { readThreadPreviewState } from "./previewStateStore";
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
Expand Down Expand Up @@ -4149,6 +4153,9 @@ export function subscribeComposerDraftModelReconciliation(input: {
readonly registry: AtomRegistry.AtomRegistry;
readonly threadRefsAtom: Atom.Atom<ReadonlyArray<ScopedThreadRef>>;
readonly threadShellAtom: (ref: ScopedThreadRef) => Atom.Atom<EnvironmentThreadShell | null>;
readonly shellStateAtom: (
environmentId: EnvironmentId,
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, unknown>>;
}): () => void {
const draftsAtom = Atom.make(composerDraftStore.getState());
const unsubscribeDrafts = composerDraftStore.subscribe((state) =>
Expand All @@ -4169,7 +4176,19 @@ export function subscribeComposerDraftModelReconciliation(input: {
const pick = draft.modelSelectionByProvider[draft.activeProvider];
if (!ref || !pick || !threadKeys.has(key)) continue;
const thread = get(input.threadShellAtom(ref));
if (thread && draftModelPickMatchesThread(pick, thread.modelSelection)) {
if (!thread || !draftModelPickMatchesThread(pick, thread.modelSelection)) continue;
// Status and selection must come from the same emission; derived atoms can update apart.
const shell = Option.getOrNull(
AsyncResult.value(get(input.shellStateAtom(ref.environmentId))),
);
if (shell?.status !== "live") continue;
const authoritativeThread = Option.getOrNull(shell.snapshot)?.threads.find(
(candidate) => candidate.id === ref.threadId,
);
if (
authoritativeThread &&
draftModelPickMatchesThread(pick, authoritativeThread.modelSelection)
) {
matches.push([key, draft]);
}
}
Expand Down
Loading