Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

thread-model-selection.ts

73 lines2.7 KB

1import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import {
4 AuthOrchestrationOperateScope,
5 type EnvironmentId,
6 type ModelSelection,
7 type ThreadId,
8} from "@t3tools/contracts";
9​
10import { scopedThreadKey } from "../lib/scopedEntities";
11import * as Dialog from "../components/ui/Dialog";
12import { msg } from "gt-react-native";
13import { m } from "../i18n/messages";
14import { appAtomRegistry } from "./atom-registry";
15import { activeComposerDraftKey, getQueuedRunEdit, isQueuedRunEditSaving } from "./queued-run-edit";
16import { readEnvironmentScope } from "./session";
17import { environmentThreadShells, threadEnvironment } from "./threads";
18import {
19 releaseComposerDraftModelSelection,
20 updateComposerDraftSettings,
21} from "./use-composer-drafts";
22​
23/** Sets an existing thread's pick on the thread, so any next turn runs on it. */
24export function selectThreadModel(
25 ref: {
26 readonly environmentId: EnvironmentId;
27 readonly threadId: ThreadId;
28 readonly draftKey?: string;
29 },
30 value: ModelSelection,
31): void {
32 const threadKey = scopedThreadKey(ref.environmentId, ref.threadId);
33 // Its own object, so an older reply for an equal pick cannot release this one.
34 const modelSelection = { ...value };
35 const draftKey = activeComposerDraftKey(
36 threadKey,
37 ref.draftKey ?? threadKey,
38 getQueuedRunEdit(threadKey),
39 );
40 if (draftKey !== threadKey && isQueuedRunEditSaving(threadKey)) return;
41 updateComposerDraftSettings(draftKey, { modelSelection });
42 if (draftKey !== threadKey) return;
43 const thread = appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
44 // Another instance replaces the live session, which may hold an open question; that pick
45 // still waits for a sent message.
46 if (
47 thread?.modelSelection.instanceId !== modelSelection.instanceId ||
48 !readEnvironmentScope(ref.environmentId, AuthOrchestrationOperateScope)
49 ) {
50 return;
51 }
52 void runAtomCommand(
53 appAtomRegistry,
54 threadEnvironment.setModelSelection,
55 { environmentId: ref.environmentId, input: { threadId: ref.threadId, modelSelection } },
56 { label: "change model", reportFailure: true, reportDefect: true },
57 ).then((result) => {
58 // Released on the reply, so a later change from another client shows.
59 if (result._tag === "Success") {
60 releaseComposerDraftModelSelection(threadKey, modelSelection);
61 } else {
62 const error = squashAtomCommandFailure(result);
63 Dialog.alert(
64 m(msg("Could not apply model selection")),
65 m(
66 msg("This model pick was not saved. {detail}", {
67 detail: errorDisplayMessage(error, m) ?? m(msg("Try again.")),
68 }),
69 ),
70 );
71 }
72 });