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

sideChat.logic.ts

174 lines6.0 KB

1import {
2 type EnvironmentThreadShell,
3 threadRuntimeIsActive,
4} from "@t3tools/client-runtime/state/models";
5import type { RuntimeSubagent } from "@t3tools/client-runtime/state/subagentRuntime";
6import type { KeybindingCommand, ThreadId } from "@t3tools/contracts";
7​
8/**
9 * A side chat is an ordinary thread whose `sideChat` flag moves it out of the
10 * sidebar. The parent it hangs from is `lineage.parentThreadId`, whether it
11 * was forked (shared history) or only linked (none).
12 */
13type SideChatShell = Pick<
14 EnvironmentThreadShell,
15 | "id"
16 | "sideChat"
17 | "lineage"
18 | "archivedAt"
19 | "deletedAt"
20 | "createdAt"
21 | "latestRun"
22 | "runtime"
23 | "itemCount"
24>;
25​
26/** The parent's side chats, newest first. Archived and deleted ones are gone for good. */
27export function sideChatsOf<T extends SideChatShell>(
28 threads: ReadonlyArray<T>,
29 parentThreadId: ThreadId,
30): T[] {
31 return threads
32 .filter(
33 (thread) =>
34 thread.sideChat &&
35 thread.lineage.parentThreadId === parentThreadId &&
36 thread.archivedAt === null &&
37 thread.deletedAt === null,
38 )
39 .toSorted((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt));
41​
42const SETTLED_RUN_STATUSES = new Set([
43 "completed",
44 "failed",
45 "interrupted",
46 "cancelled",
47 "rolled_back",
48]);
49​
50/**
51 * A side chat is "previous" once nothing is running in it, like a finished
52 * subagent. The live runtime decides first: a cancelled queued follow-up is the
53 * latest run while an older one may still be working.
54 */
55export function isPreviousSideChat(thread: Pick<SideChatShell, "latestRun" | "runtime">): boolean {
56 if (threadRuntimeIsActive(thread.runtime)) return false;
57 return thread.latestRun === null || SETTLED_RUN_STATUSES.has(thread.latestRun.status);
59​
60/** Shapes a side chat's current or latest run for `AgentElapsed`, the timer subagent rows use. */
61export function sideChatActivity(
62 thread: Pick<SideChatShell, "latestRun" | "runtime">,
63): Pick<RuntimeSubagent, "status" | "startedAt" | "completedAt"> {
64 const run = thread.latestRun;
65 const runtime = thread.runtime;
66 if (runtime !== null && threadRuntimeIsActive(runtime)) {
67 return {
68 status: runtime.status === "waiting" ? "waiting" : "running",
69 startedAt:
70 runtime.activityStartedAt ??
71 (run !== null && !SETTLED_RUN_STATUSES.has(run.status)
72 ? (run.startedAt ?? run.requestedAt)
73 : null),
74 completedAt: null,
75 };
76 }
77 if (run === null) return { status: "idle", startedAt: null, completedAt: null };
78 const status: RuntimeSubagent["status"] = SETTLED_RUN_STATUSES.has(run.status)
79 ? run.status === "completed"
80 ? "completed"
81 : run.status === "failed"
82 ? "failed"
83 : "interrupted"
84 : run.status === "waiting"
85 ? "waiting"
86 : "running";
87 return {
88 status,
89 startedAt: run.startedAt ?? run.requestedAt,
90 completedAt: run.completedAt,
91 };
93​
94/** Closing a side chat that never received a message throws it away. */
95export function isEmptySideChat(thread: Pick<SideChatShell, "latestRun" | "itemCount">): boolean {
96 return thread.latestRun === null && thread.itemCount === 0;
98​
99/** Blockquote a selection so it reads as a citation in the side chat's first message. */
100export function quoteForSideChat(text: string): string {
101 return `${text
102 .trim()
103 .split("\n")
104 .map((line) => `> ${line}`.trimEnd())
105 .join("\n")}\n\n`;
107​
108export interface ParsedSideCommand {
109 readonly command: "side" | "btw";
110 readonly question: string;
112​
113/**
114 * `/side` and its alias `/btw`. A question after the command is sent
115 * immediately; the bare command reopens the latest side chat.
116 */
117export function parseSideCommand(prompt: string): ParsedSideCommand | null {
118 const match = /^\/(side|btw)(?:\s+([\s\S]*))?$/.exec(prompt.trim());
119 if (match === null) return null;
120 return { command: match[1] as ParsedSideCommand["command"], question: (match[2] ?? "").trim() };
122​
123/** Panel layout and Find shortcuts the host thread still handles while a side chat has focus. */
124const SIDE_CHAT_PASSTHROUGH_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
125 "chat.find",
126 "rightPanel.close",
127 "rightPanel.toggle",
128 "rightPanel.toggleMaximized",
129 "threadPanel.toggle",
130]);
131/** Shortcuts a side chat handles itself: its own run, composer, toolbar, and queue. */
132export const SIDE_CHAT_OWN_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
133 "thread.stop",
134 "modelPicker.toggle",
135 "composer.effort",
136 "composer.increaseEffort",
137 "composer.decreaseEffort",
138 "composer.mode",
139 "composer.host",
140 "composer.workspace",
141 "composer.branch",
142 "composer.previousWorktree",
143 "thread.steerQueuedMessage",
144 "thread.editQueuedMessage",
145]);
146​
147/**
148 * Whether one chat view takes a window shortcut. A host thread and its embedded
149 * side chat both listen, so each claims only its own keys. `targetChat` is the
150 * embedded chat the event came from, or null outside any; `resolveCommand` is
151 * only called when the answer depends on the command.
152 */
153export function chatClaimsShortcut(input: {
154 readonly embedded: boolean;
155 readonly threadId: string;
156 /** Embedded only: this side chat has its parent's composer. */
157 readonly focused: boolean;
158 /** Host only: the side chat that has this thread's composer. */
159 readonly focusedSideChatId: string | null;
160 readonly targetChat: string | null;
161 readonly resolveCommand: () => KeybindingCommand | null;
162}): boolean {
163 const { targetChat } = input;
164 // A side chat answers keys pressed inside it, and keys pressed outside any
165 // chat while it has its parent's composer.
166 if (input.embedded)
167 return targetChat === input.threadId || (targetChat === null && input.focused);
168 if (targetChat === null && input.focusedSideChatId === null) return true;
169 const command = input.resolveCommand();
170 // Outside any chat, composer shortcuts go to the side chat that has the composer.
171 if (targetChat === null) return command === null || !SIDE_CHAT_OWN_COMMANDS.has(command);
172 // With focus in a side chat, only panel layout and Find act on the host.
173 return command !== null && SIDE_CHAT_PASSTHROUGH_COMMANDS.has(command);