File size: 16,079 Bytes
79b2fcc
 
 
 
 
 
 
 
 
 
f56fa2e
 
 
 
 
 
79b2fcc
67b16c6
79b2fcc
67b16c6
2523e77
 
 
 
 
 
79b2fcc
ac3d272
79b2fcc
 
 
 
 
 
 
07fe978
79b2fcc
 
 
 
 
 
 
 
 
ac3d272
 
79b2fcc
 
 
ae24efc
79b2fcc
3b6a2ca
 
79b2fcc
f56fa2e
 
 
 
 
 
 
 
fff300b
 
901a405
 
f56fa2e
 
 
 
 
 
 
 
 
fff300b
901a405
f56fa2e
 
67b16c6
f56fa2e
 
 
 
 
67b16c6
 
79b2fcc
67b16c6
 
79b2fcc
 
 
 
 
 
 
 
2523e77
79b2fcc
 
 
 
 
 
67b16c6
4b24bd9
 
 
 
 
 
219e6a7
 
 
f56fa2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b16c6
 
79b2fcc
67b16c6
 
79b2fcc
 
 
 
 
 
 
 
 
2523e77
79b2fcc
 
 
 
 
 
 
4b24bd9
 
 
 
 
 
219e6a7
 
 
67b16c6
 
f56fa2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b24bd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79b2fcc
f56fa2e
 
 
67b16c6
 
79b2fcc
67b16c6
 
79b2fcc
67b16c6
79b2fcc
 
 
35dc01a
79b2fcc
67b16c6
79b2fcc
 
4b24bd9
 
219e6a7
67b16c6
f56fa2e
 
 
 
 
 
 
 
 
 
3b6a2ca
f56fa2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fff300b
901a405
f56fa2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79b2fcc
67b16c6
79b2fcc
 
3b6a2ca
79b2fcc
67b16c6
79b2fcc
 
 
 
 
67b16c6
79b2fcc
f56fa2e
 
 
 
 
 
 
 
 
 
79b2fcc
67b16c6
f56fa2e
 
 
 
3ce798d
f56fa2e
 
 
 
 
 
 
3ce798d
f56fa2e
 
79b2fcc
f56fa2e
 
 
 
 
72af187
f56fa2e
 
 
 
3ce798d
f56fa2e
 
 
 
2523e77
79b2fcc
ac3d272
f56fa2e
 
 
 
ac3d272
79b2fcc
ac3d272
79b2fcc
 
 
 
463e470
 
79b2fcc
72af187
79b2fcc
72af187
79b2fcc
463e470
79b2fcc
 
 
 
463e470
79b2fcc
 
4b24bd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219e6a7
 
 
 
 
 
 
 
 
 
 
 
67b16c6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/**
 * Agent store β€” manages UI state that is NOT handled by the Vercel AI SDK.
 *
 * Message state (messages, streaming, tool calls) is now managed by useChat().
 * This store only handles:
 *  - Connection / processing flags
 *  - Panel state (right panel β€” single-artifact pattern)
 *  - Plan state
 *  - User info / error banners
 *  - Edited scripts (for hf_jobs code editing)
 *
 * Per-session state:
 *  Each session maintains its own snapshot of processing/activity/panel/plan
 *  state in `sessionStates`. Background sessions keep updating their own
 *  snapshot via `updateSession()`. The active session's snapshot is mirrored
 *  to the flat top-level fields so the UI reads from a single place.
 */
import { create } from 'zustand';
import type { User } from '@/types/agent';

export interface PlanItem {
  id: string;
  content: string;
  status: 'pending' | 'in_progress' | 'completed';
}

export interface PanelSection {
  content: string;
  language: string;
}

export interface PanelData {
  title: string;
  script?: PanelSection;
  output?: PanelSection;
  input?: PanelSection;
  parameters?: Record<string, unknown>;
}

export type PanelView = 'script' | 'output';

export interface LLMHealthError {
  error: string;
  errorType: 'auth' | 'credits' | 'rate_limit' | 'network' | 'unknown';
  model: string;
}

export type ActivityStatus =
  | { type: 'idle' }
  | { type: 'thinking' }
  | { type: 'tool'; toolName: string; description?: string }
  | { type: 'waiting-approval' }
  | { type: 'streaming' }
  | { type: 'cancelled' };

/** State that is tracked per-session (each session has its own copy). */
export interface PerSessionState {
  isProcessing: boolean;
  activityStatus: ActivityStatus;
  panelData: PanelData | null;
  panelView: PanelView;
  panelEditable: boolean;
  plan: PlanItem[];
  /** Steps completed by the research sub-agent (tool_log events). */
  researchSteps: string[];
  /** Live stats from the research sub-agent. */
  researchStats: { toolCount: number; tokenCount: number; startedAt: number | null; finalElapsed: number | null };
}

const defaultSessionState: PerSessionState = {
  isProcessing: false,
  activityStatus: { type: 'idle' },
  panelData: null,
  panelView: 'script',
  panelEditable: false,
  plan: [],
  researchSteps: [],
  researchStats: { toolCount: 0, tokenCount: 0, startedAt: null, finalElapsed: null },
};

interface AgentStore {
  // ── Per-session state map ───────────────────────────────────────────
  sessionStates: Record<string, PerSessionState>;
  activeSessionId: string | null;

  // ── Flat state (mirrors active session β€” UI reads from here) ────────
  isProcessing: boolean;
  isConnected: boolean;
  activityStatus: ActivityStatus;
  user: User | null;
  error: string | null;
  llmHealthError: LLMHealthError | null;

  // Right panel (single-artifact pattern)
  panelData: PanelData | null;
  panelView: PanelView;
  panelEditable: boolean;

  // Plan
  plan: PlanItem[];

  // Edited scripts (tool_call_id -> edited content)
  editedScripts: Record<string, string>;

  // Job URLs (tool_call_id -> job URL) for HF jobs
  jobUrls: Record<string, string>;

  // Job statuses (tool_call_id -> job status) for HF jobs
  jobStatuses: Record<string, string>;

  // Tool error states (tool_call_id -> true if errored) - persisted across renders
  toolErrors: Record<string, boolean>;

  // Tool rejected states (tool_call_id -> true if rejected by user) - persisted across renders
  rejectedTools: Record<string, boolean>;

  // ── Per-session actions ─────────────────────────────────────────────

  /** Update a session's state. If it's the active session, also update flat state. */
  updateSession: (sessionId: string, updates: Partial<PerSessionState>) => void;

  /** Get a session's current state (from map, not flat). */
  getSessionState: (sessionId: string) => PerSessionState;

  /** Switch the active session β€” restores its state to flat fields. */
  switchActiveSession: (sessionId: string) => void;

  /** Remove a session's state from the map. */
  clearSessionState: (sessionId: string) => void;

  // ── Global actions (not per-session) ────────────────────────────────
  setProcessing: (isProcessing: boolean) => void;
  setConnected: (isConnected: boolean) => void;
  setActivityStatus: (status: ActivityStatus) => void;
  setUser: (user: User | null) => void;
  setError: (error: string | null) => void;
  setLlmHealthError: (error: LLMHealthError | null) => void;

  setPanel: (data: PanelData, view?: PanelView, editable?: boolean) => void;
  setPanelView: (view: PanelView) => void;
  setPanelOutput: (output: PanelSection) => void;
  updatePanelScript: (content: string) => void;
  lockPanel: () => void;
  clearPanel: () => void;

  setPlan: (plan: PlanItem[]) => void;

  setEditedScript: (toolCallId: string, content: string) => void;
  getEditedScript: (toolCallId: string) => string | undefined;
  clearEditedScripts: () => void;

  setJobUrl: (toolCallId: string, jobUrl: string) => void;
  getJobUrl: (toolCallId: string) => string | undefined;

  setJobStatus: (toolCallId: string, status: string) => void;
  getJobStatus: (toolCallId: string) => string | undefined;

  setToolError: (toolCallId: string, hasError: boolean) => void;
  getToolError: (toolCallId: string) => boolean | undefined;

  setToolRejected: (toolCallId: string, isRejected: boolean) => void;
  getToolRejected: (toolCallId: string) => boolean | undefined;
}

/**
 * Helper: patch the active session's snapshot with partial per-session fields.
 * Returns the `sessionStates` slice to spread into a `set()` call, or `{}`
 * if there's no active session snapshot to update.
 */
function syncSnapshot(
  state: AgentStore,
  patch: Partial<PerSessionState>,
): { sessionStates: Record<string, PerSessionState> } | Record<string, never> {
  const { activeSessionId, sessionStates } = state;
  if (!activeSessionId || !sessionStates[activeSessionId]) return {};
  return {
    sessionStates: {
      ...sessionStates,
      [activeSessionId]: { ...sessionStates[activeSessionId], ...patch },
    },
  };
}

// Load persisted tool errors from localStorage
function loadToolErrors(): Record<string, boolean> {
  try {
    const stored = localStorage.getItem('hf-agent-tool-errors');
    return stored ? JSON.parse(stored) : {};
  } catch {
    return {};
  }
}

// Save tool errors to localStorage
function saveToolErrors(errors: Record<string, boolean>): void {
  try {
    localStorage.setItem('hf-agent-tool-errors', JSON.stringify(errors));
  } catch (e) {
    console.warn('Failed to persist tool errors:', e);
  }
}

// Load persisted rejected tools from localStorage
function loadRejectedTools(): Record<string, boolean> {
  try {
    const stored = localStorage.getItem('hf-agent-rejected-tools');
    return stored ? JSON.parse(stored) : {};
  } catch {
    return {};
  }
}

// Save rejected tools to localStorage
function saveRejectedTools(rejected: Record<string, boolean>): void {
  try {
    localStorage.setItem('hf-agent-rejected-tools', JSON.stringify(rejected));
  } catch (e) {
    console.warn('Failed to persist rejected tools:', e);
  }
}

export const useAgentStore = create<AgentStore>()((set, get) => ({
  sessionStates: {},
  activeSessionId: null,

  isProcessing: false,
  isConnected: false,
  activityStatus: { type: 'idle' },
  user: null,
  error: null,
  llmHealthError: null,

  panelData: null,
  panelView: 'script',
  panelEditable: false,

  plan: [],

  editedScripts: {},
  jobUrls: {},
  jobStatuses: {},
  toolErrors: loadToolErrors(),
  rejectedTools: loadRejectedTools(),

  // ── Per-session state management ──────────────────────────────────

  updateSession: (sessionId, updates) => {
    const state = get();
    const current = state.sessionStates[sessionId] || { ...defaultSessionState };
    const updated = { ...current, ...updates };

    // Apply the processing→idle side effect
    const processingCleared = 'isProcessing' in updates && !updates.isProcessing;
    if (processingCleared) {
      if (updated.activityStatus.type !== 'waiting-approval' && updated.activityStatus.type !== 'cancelled') {
        updated.activityStatus = { type: 'idle' };
      }
    }

    const isActive = state.activeSessionId === sessionId;

    // Build flat-state mirror: only the fields explicitly in `updates`
    // (plus activityStatus when the processing→idle side-effect fires).
    // This prevents overwriting flat fields changed by global setters
    // (e.g. setPanelView called from CodePanel) with stale snapshot values.
    let flatMirror: Record<string, unknown> = {};
    if (isActive) {
      for (const key of Object.keys(updates)) {
        flatMirror[key] = updated[key as keyof PerSessionState];
      }
      // Side-effect may have changed activityStatus even if it wasn't in updates
      if (processingCleared) {
        flatMirror.activityStatus = updated.activityStatus;
      }
    }

    set({
      sessionStates: { ...state.sessionStates, [sessionId]: updated },
      ...flatMirror,
    });
  },

  getSessionState: (sessionId) => {
    return get().sessionStates[sessionId] || { ...defaultSessionState };
  },

  switchActiveSession: (sessionId) => {
    const state = get();

    // Build a new sessionStates map (never mutate the existing object)
    const updatedStates = { ...state.sessionStates };

    // Save current active session's flat state back to its snapshot
    if (state.activeSessionId && state.activeSessionId !== sessionId) {
      updatedStates[state.activeSessionId] = {
        isProcessing: state.isProcessing,
        activityStatus: state.activityStatus,
        panelData: state.panelData,
        panelView: state.panelView,
        panelEditable: state.panelEditable,
        plan: state.plan,
        researchSteps: state.sessionStates[state.activeSessionId]?.researchSteps ?? [],
        researchStats: state.sessionStates[state.activeSessionId]?.researchStats ?? defaultSessionState.researchStats,
      };
    }

    // Restore the new session's state
    const incoming = updatedStates[sessionId] || { ...defaultSessionState };
    set({
      activeSessionId: sessionId,
      sessionStates: updatedStates,
      isProcessing: incoming.isProcessing,
      activityStatus: incoming.activityStatus,
      panelData: incoming.panelData,
      panelView: incoming.panelView,
      panelEditable: incoming.panelEditable,
      plan: incoming.plan,
      // Clear transient error on switch
      error: null,
    });
  },

  clearSessionState: (sessionId) => {
    set((state) => {
      const { [sessionId]: _, ...rest } = state.sessionStates;
      return { sessionStates: rest };
    });
  },

  // ── Global flags ──────────────────────────────────────────────────

  setProcessing: (isProcessing) => {
    const current = get().activityStatus;
    const preserveStatus = current.type === 'waiting-approval' || current.type === 'cancelled';
    set({ isProcessing, ...(!isProcessing && !preserveStatus ? { activityStatus: { type: 'idle' } } : {}) });
  },
  setConnected: (isConnected) => set({ isConnected }),
  setActivityStatus: (status) => set({ activityStatus: status }),
  setUser: (user) => set({ user }),
  setError: (error) => set({ error }),
  setLlmHealthError: (error) => set({ llmHealthError: error }),

  // ── Panel (single-artifact) ───────────────────────────────────────
  // Each setter also patches the active session's snapshot so that
  // getSessionState() stays consistent with flat state.

  setPanel: (data, view, editable) => set((state) => {
    const patch: Partial<PerSessionState> = {
      panelData: data,
      panelView: view ?? (data.script ? 'script' : 'output'),
      panelEditable: editable ?? false,
    };
    return { ...patch, ...syncSnapshot(state, patch) };
  }),

  setPanelView: (view) => set((state) => {
    const patch: Partial<PerSessionState> = { panelView: view };
    return { ...patch, ...syncSnapshot(state, patch) };
  }),

  setPanelOutput: (output) => set((state) => {
    const panelData = state.panelData
      ? { ...state.panelData, output }
      : { title: 'Output', output };
    const patch: Partial<PerSessionState> = { panelData, panelView: 'output' };
    return { ...patch, ...syncSnapshot(state, patch) };
  }),

  updatePanelScript: (content) => set((state) => {
    const panelData = state.panelData?.script
      ? { ...state.panelData, script: { ...state.panelData.script, content } }
      : state.panelData;
    if (!panelData) return {};
    const patch: Partial<PerSessionState> = { panelData };
    return { ...patch, ...syncSnapshot(state, patch) };
  }),

  lockPanel: () => set((state) => {
    const patch: Partial<PerSessionState> = { panelEditable: false };
    return { ...patch, ...syncSnapshot(state, patch) };
  }),

  clearPanel: () => set((state) => {
    const patch: Partial<PerSessionState> = { panelData: null, panelView: 'script', panelEditable: false };
    return { ...patch, ...syncSnapshot(state, patch) };
  }),

  // ── Plan ──────────────────────────────────────────────────────────

  setPlan: (plan) => set((state) => {
    const patch: Partial<PerSessionState> = { plan };
    return { ...patch, ...syncSnapshot(state, patch) };
  }),

  // ── Edited scripts ────────────────────────────────────────────────

  setEditedScript: (toolCallId, content) => {
    set((state) => ({
      editedScripts: { ...state.editedScripts, [toolCallId]: content },
    }));
  },

  getEditedScript: (toolCallId) => get().editedScripts[toolCallId],

  clearEditedScripts: () => set({ editedScripts: {} }),

  // ── Job URLs ────────────────────────────────────────────────────────

  setJobUrl: (toolCallId, jobUrl) => {
    set((state) => ({
      jobUrls: { ...state.jobUrls, [toolCallId]: jobUrl },
    }));
  },

  getJobUrl: (toolCallId) => get().jobUrls[toolCallId],

  // ── Job Statuses ────────────────────────────────────────────────────

  setJobStatus: (toolCallId, status) => {
    set((state) => ({
      jobStatuses: { ...state.jobStatuses, [toolCallId]: status },
    }));
  },

  getJobStatus: (toolCallId) => get().jobStatuses[toolCallId],

  // ── Tool Errors ─────────────────────────────────────────────────────

  setToolError: (toolCallId, hasError) => {
    set((state) => {
      const updated = { ...state.toolErrors, [toolCallId]: hasError };
      saveToolErrors(updated);
      return { toolErrors: updated };
    });
  },

  getToolError: (toolCallId) => get().toolErrors[toolCallId],

  // ── Tool Rejections ──────────────────────────────────────────────────

  setToolRejected: (toolCallId, isRejected) => {
    set((state) => {
      const updated = { ...state.rejectedTools, [toolCallId]: isRejected };
      saveRejectedTools(updated);
      return { rejectedTools: updated };
    });
  },

  getToolRejected: (toolCallId) => get().rejectedTools[toolCallId],
}));