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

thread-model-selection.ts

54 lines2.2 KB

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