Open History to see the last commit
1import { scopedThreadKey } from "@v12/client-runtime/environment";
2import type { MessageId, ScopedThreadRef, ThreadId } from "@v12/contracts";
3import { create } from "zustand";
4import { createJSONStorage, persist } from "zustand/middleware";
5
6import { resolveStorage } from "./lib/storage";
7import type { ActivePlanState } from "./session-logic";
8
9const TASK_HUD_STORAGE_KEY = "v12:task-hud-state:v1";
10const MAX_PERSISTED_PLAN_OVERRIDES = 100;
11const MAX_PERSISTED_CONTEXT_TASKS = 200;
12
13export type TaskHudSourceStep = ActivePlanState["steps"][number];
14
15export interface TaskHudStep extends TaskHudSourceStep {
16 readonly id: string;
17}
18
19export interface TaskHudPlanOverrides {
20 readonly order: readonly string[];
21 readonly removed: readonly string[];
22 readonly completedByTaskId: Readonly<Record<string, boolean>>;
23}
24
25export interface ContextualTask {
26 readonly id: string;
27 readonly instruction: string;
28 readonly quote: string;
29 readonly sourceThreadId: ThreadId;
30 readonly sourceMessageId: MessageId;
31 readonly sourceAuthor: "user" | "assistant";
32 readonly sourceCreatedAt: string;
33 readonly completed: boolean;
34 readonly pendingSend?: boolean;
35}
36
37const EMPTY_OVERRIDES: TaskHudPlanOverrides = Object.freeze({
38 order: Object.freeze([]),
39 removed: Object.freeze([]),
40 completedByTaskId: Object.freeze({}),
41});
42
43interface TaskHudStoreState {
44 readonly overridesByPlanKey: Record<string, TaskHudPlanOverrides>;
45 readonly contextTasksByThreadKey: Record<string, readonly ContextualTask[]>;
46 readonly setTaskCompleted: (planKey: string, taskId: string, completed: boolean) => void;
47 readonly removeTask: (planKey: string, taskId: string) => void;
48 readonly setTaskOrder: (planKey: string, taskIds: readonly string[]) => void;
49 readonly addContextTask: (threadKey: string, task: ContextualTask) => void;
50 readonly setContextTaskCompleted: (threadKey: string, taskId: string, completed: boolean) => void;
51 readonly removeContextTask: (threadKey: string, taskId: string) => void;
52 readonly markContextTasksSent: (threadKey: string, taskIds: readonly string[]) => void;
53 readonly copyContextTasksToFork: (input: {
54 readonly sourceThreadKey: string;
55 readonly targetThreadKey: string;
56 readonly sourceThreadId: ThreadId;
57 readonly targetThreadId: ThreadId;
58 readonly messageIdBySourceId: Readonly<Record<string, MessageId>>;
59 }) => void;
60}
61
62export function buildForkMessageIdMap(
63 sourceMessages: ReadonlyArray<Pick<{ id: MessageId }, "id">>,
64 targetMessages: ReadonlyArray<Pick<{ id: MessageId }, "id">>,
65): Readonly<Record<string, MessageId>> {
66 if (sourceMessages.length !== targetMessages.length) {
67 throw new Error(
68 `Fork history is incomplete: expected ${sourceMessages.length} messages, received ${targetMessages.length}.`,
69 );
70 }
71 const messageIdBySourceId: Record<string, MessageId> = {};
72 for (let index = 0; index < sourceMessages.length; index += 1) {
73 const sourceMessage = sourceMessages[index];
74 const targetMessage = targetMessages[index];
75 if (sourceMessage && targetMessage) {
76 messageIdBySourceId[sourceMessage.id] = targetMessage.id;
77 }
78 }
79 return messageIdBySourceId;
80}
81
82export function taskHudPlanKey(
83 threadRef: ScopedThreadRef,
84 plan: Pick<ActivePlanState, "turnId" | "createdAt">,
85): string {
86 return `${scopedThreadKey(threadRef)}:${plan.turnId ?? plan.createdAt}`;
87}
88
89export function appendContextTasksToPrompt(
90 prompt: string,
91 tasks: readonly Pick<ContextualTask, "instruction" | "quote">[],
92): string {
93 if (tasks.length === 0) return prompt;
94 const taskLines = tasks.map((task, index) => {
95 const selectedContext =
96 task.quote === task.instruction
97 ? ""
98 : `\n Selected text: ${task.quote.replaceAll("\n", "\n ")}`;
99 return `${index + 1}. ${task.instruction}${selectedContext}`;
100 });
101 const taskBlock = tasks.length === 1 ? taskLines[0]! : `Tasks:\n${taskLines.join("\n")}`;
102 const trimmedPrompt = prompt.trim();
103 return trimmedPrompt ? `${trimmedPrompt}\n\n${taskBlock}` : taskBlock;
104}
105
106export function identifyTaskHudSteps(steps: readonly TaskHudSourceStep[]): TaskHudStep[] {
107 const occurrenceByText = new Map<string, number>();
108 return steps.map((step) => {
109 const occurrence = occurrenceByText.get(step.step) ?? 0;
110 occurrenceByText.set(step.step, occurrence + 1);
111 return {
112 ...step,
113 id: `${step.step}\u0000${occurrence}`,
114 };
115 });
116}
117
118export function applyTaskHudOverrides(
119 steps: readonly TaskHudSourceStep[],
120 overrides: TaskHudPlanOverrides | undefined,
121): TaskHudStep[] {
122 const identified = identifyTaskHudSteps(steps);
123 if (!overrides) return identified;
124
125 const removed = new Set(overrides.removed);
126 const availableById = new Map(
127 identified.filter((step) => !removed.has(step.id)).map((step) => [step.id, step] as const),
128 );
129 const orderedIds = [
130 ...overrides.order.filter((taskId) => availableById.has(taskId)),
131 ...identified.map((step) => step.id).filter((taskId) => availableById.has(taskId)),
132 ];
133 const emitted = new Set<string>();
134
135 return orderedIds.flatMap((taskId) => {
136 if (emitted.has(taskId)) return [];
137 const step = availableById.get(taskId);
138 if (!step) return [];
139 emitted.add(taskId);
140 const completedOverride = overrides.completedByTaskId[taskId];
141 return [
142 completedOverride === undefined
143 ? step
144 : { ...step, status: completedOverride ? ("completed" as const) : ("pending" as const) },
145 ];
146 });
147}
148
149function updateOverrides(
150 state: TaskHudStoreState,
151 planKey: string,
152 update: (current: TaskHudPlanOverrides) => TaskHudPlanOverrides,
153): Pick<TaskHudStoreState, "overridesByPlanKey"> {
154 const current = state.overridesByPlanKey[planKey] ?? EMPTY_OVERRIDES;
155 const nextEntries = { ...state.overridesByPlanKey, [planKey]: update(current) };
156 const planKeys = Object.keys(nextEntries);
157 for (const stalePlanKey of planKeys.slice(0, -MAX_PERSISTED_PLAN_OVERRIDES)) {
158 delete nextEntries[stalePlanKey];
159 }
160 return { overridesByPlanKey: nextEntries };
161}
162
163export const useTaskHudStore = create<TaskHudStoreState>()(
164 persist(
165 (set) => ({
166 overridesByPlanKey: {},
167 contextTasksByThreadKey: {},
168 setTaskCompleted: (planKey, taskId, completed) =>
169 set((state) =>
170 updateOverrides(state, planKey, (current) => ({
171 ...current,
172 completedByTaskId: { ...current.completedByTaskId, [taskId]: completed },
173 })),
174 ),
175 removeTask: (planKey, taskId) =>
176 set((state) =>
177 updateOverrides(state, planKey, (current) => ({
178 ...current,
179 order: current.order.filter((candidate) => candidate !== taskId),
180 removed: current.removed.includes(taskId)
181 ? current.removed
182 : [...current.removed, taskId],
183 })),
184 ),
185 setTaskOrder: (planKey, taskIds) =>
186 set((state) =>
187 updateOverrides(state, planKey, (current) => ({
188 ...current,
189 order: [...new Set(taskIds)],
190 })),
191 ),
192 addContextTask: (threadKey, task) =>
193 set((state) => ({
194 contextTasksByThreadKey: {
195 ...state.contextTasksByThreadKey,
196 [threadKey]: [...(state.contextTasksByThreadKey[threadKey] ?? []), task].slice(
197 -MAX_PERSISTED_CONTEXT_TASKS,
198 ),
199 },
200 })),
201 setContextTaskCompleted: (threadKey, taskId, completed) =>
202 set((state) => ({
203 contextTasksByThreadKey: {
204 ...state.contextTasksByThreadKey,
205 [threadKey]: (state.contextTasksByThreadKey[threadKey] ?? []).map((task) =>
206 task.id === taskId ? { ...task, completed } : task,
207 ),
208 },
209 })),
210 removeContextTask: (threadKey, taskId) =>
211 set((state) => ({
212 contextTasksByThreadKey: {
213 ...state.contextTasksByThreadKey,
214 [threadKey]: (state.contextTasksByThreadKey[threadKey] ?? []).filter(
215 (task) => task.id !== taskId,
216 ),
217 },
218 })),
219 markContextTasksSent: (threadKey, taskIds) => {
220 if (taskIds.length === 0) return;
221 const sentIds = new Set(taskIds);
222 set((state) => ({
223 contextTasksByThreadKey: {
224 ...state.contextTasksByThreadKey,
225 [threadKey]: (state.contextTasksByThreadKey[threadKey] ?? []).map((task) =>
226 sentIds.has(task.id) ? { ...task, pendingSend: false } : task,
227 ),
228 },
229 }));
230 },
231 copyContextTasksToFork: ({
232 sourceThreadKey,
233 targetThreadKey,
234 sourceThreadId,
235 targetThreadId,
236 messageIdBySourceId,
237 }) =>
238 set((state) => ({
239 contextTasksByThreadKey: {
240 ...state.contextTasksByThreadKey,
241 [targetThreadKey]: (state.contextTasksByThreadKey[sourceThreadKey] ?? []).flatMap(
242 (task) => {
243 if (task.sourceThreadId !== sourceThreadId) return [task];
244 const targetMessageId = messageIdBySourceId[task.sourceMessageId];
245 if (!targetMessageId) return [];
246 return [
247 {
248 ...task,
249 sourceThreadId: targetThreadId,
250 sourceMessageId: targetMessageId,
251 },
252 ];
253 },
254 ),
255 },
256 })),
257 }),
258 {
259 name: TASK_HUD_STORAGE_KEY,
260 storage: createJSONStorage(() =>
261 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
262 ),
263 partialize: (state) => ({
264 overridesByPlanKey: state.overridesByPlanKey,
265 contextTasksByThreadKey: state.contextTasksByThreadKey,
266 }),
267 },
268 ),
269);