All files / src store.ts

62.02% Statements 294/474
45.56% Branches 36/79
88.88% Functions 16/18
62.02% Lines 294/474

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 5541x                                                                                                                   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   1x 17x 17x   1x 29x 29x   7x 7x 7x 7x 7x 7x 7x 7x 7x   1x 1x 1x 1x 1x           3x 3x 3x   3x 3x 3x   3x 3x   3x 3x 3x 3x 3x 3x 3x 3x   3x 3x                   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x   2x 2x 2x 2x 2x                                               1x 1x 1x 1x   1x 1x 1x                                   1x 1x 1x   1x 8x 8x 8x 8x 8x 8x                                                                     8x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x         3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 8x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x               2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 8x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 8x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x   4x 4x 4x 4x 1x 1x 3x   3x 4x                 4x     4x 1x 1x 4x         4x 1x   1x 1x 1x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 4x                       4x                           4x                     4x                         4x                                 4x   4x   3x 3x 3x 3x 4x   4x 2x 4x 4x 2x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x  
import { create } from "zustand";
 
import type {
  ImageAttachment,
  LiveSession,
  LiveSessionRuntime,
  LiveSessionSnapshot,
  TimelineItem,
  UsagePayload,
  WebEvent,
} from "./types";
 
export type ConnectionState = "disconnected" | "connecting" | "connected";
 
export type SubAgentState = {
  title: string;
  status: string;
};
 
export type SessionRuntimeState = {
  liveSessionId: string | null;
  sessionId: string | null;
  runtime: LiveSessionRuntime | null;
  connection: ConnectionState;
  inputEnabled: boolean;
  waitMessage: string | null;
  sessionUsage: UsagePayload | null;
  turnUsage: { usage: UsagePayload | null; elapsedSeconds?: number } | null;
  sessionEnded: boolean;
  fatalError: string | null;
  items: TimelineItem[];
  itemsVersion: number;
  subAgents: Record<string, SubAgentState>;
  lastEventSeq: number;
};
 
type SessionStore = {
  activeSessionKey: string | null;
  sessionsByKey: Record<string, SessionRuntimeState>;
  liveSessionIndex: Record<string, string>;
  sessionIndex: Record<string, string>;
  setActiveSession: (sessionKey: string | null) => void;
  hydrateSavedSession: (sessionId: string, items?: TimelineItem[], lastEventSeq?: number) => void;
  attachLiveSession: (
    sessionKey: string,
    session: LiveSession,
    options?: { preserveItems?: boolean },
  ) => string;
  hydrateLiveSnapshot: (
    sessionKey: string,
    session: LiveSession,
    snapshot: LiveSessionSnapshot,
  ) => string;
  updateRuntimeFromSession: (sessionKey: string, session: LiveSession) => void;
  setConnection: (sessionKey: string, connection: ConnectionState) => void;
  applyEvent: (sessionKey: string, event: WebEvent) => string;
};
 
function createEmptySessionState(sessionId: string | null = null): SessionRuntimeState {
  return {
    liveSessionId: null,
    sessionId,
    runtime: null,
    connection: "disconnected",
    inputEnabled: false,
    waitMessage: null,
    sessionUsage: null,
    turnUsage: null,
    sessionEnded: false,
    fatalError: null,
    items: [],
    itemsVersion: 0,
    subAgents: {},
    lastEventSeq: 0,
  };
}
 
export function getSavedSessionKey(sessionId: string): string {
  return `session:${sessionId}`;
}
 
export function getLiveSessionKey(liveSessionId: string): string {
  return `live:${liveSessionId}`;
}
 
function runtimeFromSession(session: LiveSession): LiveSessionRuntime {
  return {
    provider_id: session.provider_id,
    profile_id: session.profile_id,
    provider: session.provider,
    model: session.model,
    reasoning_effort: session.reasoning_effort,
  };
}
 
function upsertItem(items: TimelineItem[], nextItem: TimelineItem): TimelineItem[] {
  const index = items.findIndex((item) => item.itemId === nextItem.itemId);
  if (index === -1) {
    return [...items, nextItem];
  }
  const updated = [...items];
  updated[index] = nextItem;
  return updated;
}
 
function readString(value: unknown, fallback = ""): string {
  return typeof value === "string" ? value : fallback;
}
 
function readOptionalString(value: unknown): string | undefined {
  return typeof value === "string" ? value : undefined;
}
 
function readTimelineRole(
  value: unknown,
): "user" | "assistant" | "notice" | "error" | "debug" {
  switch (value) {
    case "user":
    case "assistant":
    case "notice":
    case "error":
    case "debug":
      return value;
    default:
      return "assistant";
  }
}
 
function isImageAttachment(value: unknown): value is ImageAttachment {
  if (value === null || typeof value !== "object") {
    return false;
  }
  return "upload_id" in value
    && typeof (value as { upload_id: unknown }).upload_id === "string";
}
 
function mapSnapshotItem(raw: Record<string, unknown>): TimelineItem | null {
  const kind = raw.kind;
  const itemId = typeof raw.itemId === "string" ? raw.itemId : null;
  if (!itemId || typeof kind !== "string") return null;
  if (kind === "message") {
    return {
      kind: "message",
      itemId,
      role: readTimelineRole(raw.role),
      content: readString(raw.content),
      filePaths: Array.isArray(raw.file_paths)
        ? raw.file_paths.filter((value): value is string => typeof value === "string")
        : undefined,
      imageAttachments: Array.isArray(raw.image_attachments)
        ? raw.image_attachments.filter(isImageAttachment)
        : undefined,
      markdown: Boolean(raw.markdown),
      subAgentId: readOptionalString(raw.sub_agent_id),
    };
  }
  if (kind === "thinking") {
    return {
      kind: "thinking",
      itemId,
      title: readString(raw.title, "Thinking"),
      content: readString(raw.content),
      subAgentId: readOptionalString(raw.sub_agent_id),
    };
  }
  if (kind === "tool_group") {
    return {
      kind: "tool_group",
      itemId,
      label: readString(raw.label, "Tool calls"),
      items: Array.isArray(raw.items)
        ? (raw.items as { text: string; classes?: string }[])
        : [],
      subAgentId: readOptionalString(raw.sub_agent_id),
    };
  }
  return null;
}
 
function moveSessionState(
  state: SessionStore,
  fromKey: string,
  toKey: string,
): SessionStore {
  if (fromKey === toKey || !(fromKey in state.sessionsByKey)) {
    return state;
  }
  const sessionState = state.sessionsByKey[fromKey];
  const nextSessionsByKey = { ...state.sessionsByKey };
  delete nextSessionsByKey[fromKey];
  nextSessionsByKey[toKey] = sessionState;
 
  const nextLiveSessionIndex = Object.fromEntries(
    Object.entries(state.liveSessionIndex).map(([id, key]) => [id, key === fromKey ? toKey : key]),
  );
  const nextSessionIndex = Object.fromEntries(
    Object.entries(state.sessionIndex).map(([id, key]) => [id, key === fromKey ? toKey : key]),
  );
 
  return {
    ...state,
    sessionsByKey: nextSessionsByKey,
    liveSessionIndex: nextLiveSessionIndex,
    sessionIndex: nextSessionIndex,
    activeSessionKey: state.activeSessionKey === fromKey ? toKey : state.activeSessionKey,
  };
}
 
export const useSessionStore = create<SessionStore>((set) => ({
  activeSessionKey: null,
  sessionsByKey: {},
  liveSessionIndex: {},
  sessionIndex: {},
  setActiveSession: (sessionKey) => set({ activeSessionKey: sessionKey }),
  hydrateSavedSession: (sessionId, items = [], lastEventSeq) =>
    set((state) => {
      const sessionKey = getSavedSessionKey(sessionId);
      const current = state.sessionsByKey[sessionKey] ?? createEmptySessionState(sessionId);
      return {
        ...state,
        sessionsByKey: {
          ...state.sessionsByKey,
          [sessionKey]: {
            ...current,
            sessionId,
            items,
            itemsVersion: items.length,
            fatalError: null,
            // Reset live-session state so revisiting a saved session
            // does not keep stale liveSessionId / connection / flags
            // from a previously ended session.
            liveSessionId: null,
            connection: "disconnected",
            inputEnabled: false,
            waitMessage: null,
            sessionEnded: false,
            // Set lastEventSeq from the server so the WS snapshot
            // replay skips events already covered by API history.
            // Use the server value directly (not Math.max) because the
            // current value may belong to a previous, ended live session
            // whose seq space is unrelated.
            lastEventSeq: typeof lastEventSeq === "number"
              ? lastEventSeq
              : 0,
          },
        },
        sessionIndex: { ...state.sessionIndex, [sessionId]: sessionKey },
      };
    }),
  attachLiveSession: (sessionKey, session, options = {}) => {
    let resolvedKey = sessionKey;
    set((state) => {
      resolvedKey = session.session_id ? getSavedSessionKey(session.session_id) : sessionKey;
      let nextState = state;
      if (sessionKey !== resolvedKey) {
        nextState = moveSessionState(state, sessionKey, resolvedKey);
      }
      const current =
        nextState.sessionsByKey[resolvedKey]
        ?? createEmptySessionState(session.session_id);
      return {
        ...nextState,
        sessionsByKey: {
          ...nextState.sessionsByKey,
          [resolvedKey]: {
            ...current,
            liveSessionId: session.live_session_id,
            sessionId: session.session_id,
            runtime: runtimeFromSession(session),
            inputEnabled: false,
            waitMessage: null,
            sessionUsage: options.preserveItems ? current.sessionUsage : null,
            turnUsage: options.preserveItems ? current.turnUsage : null,
            sessionEnded: session.status === "ended",
            fatalError: session.fatal_error,
            items: options.preserveItems ? current.items : [],
            itemsVersion: options.preserveItems ? current.itemsVersion : 0,
            subAgents: options.preserveItems ? current.subAgents : {},
            // When reattaching the same live session, carry forward the
            // high-water mark so the WS snapshot replay skips events
            // already covered by API history.  When attaching a *new*
            // live session (seq restarts from 1), reset to the server's
            // value so we don't suppress the new session's events.
            lastEventSeq:
              current.liveSessionId === session.live_session_id
                ? Math.max(
                    current.lastEventSeq,
                    typeof session.last_event_seq === "number" ? session.last_event_seq : 0,
                  )
                : (typeof session.last_event_seq === "number" ? session.last_event_seq : 0),
          },
        },
        liveSessionIndex: {
          ...nextState.liveSessionIndex,
          [session.live_session_id]: resolvedKey,
        },
        sessionIndex: session.session_id
          ? { ...nextState.sessionIndex, [session.session_id]: resolvedKey }
          : nextState.sessionIndex,
      };
    });
    return resolvedKey;
  },
  hydrateLiveSnapshot: (sessionKey, session, snapshot) => {
    let resolvedKey = sessionKey;
    set((state) => {
      resolvedKey = snapshot.session_id ? getSavedSessionKey(snapshot.session_id) : sessionKey;
      let nextState = state;
      if (sessionKey !== resolvedKey) {
        nextState = moveSessionState(state, sessionKey, resolvedKey);
      }
      const current =
        nextState.sessionsByKey[resolvedKey]
        ?? createEmptySessionState(snapshot.session_id);
      const items = snapshot.items
        .map((item) => mapSnapshotItem(item))
        .filter((item): item is TimelineItem => item !== null);
      return {
        ...nextState,
        sessionsByKey: {
          ...nextState.sessionsByKey,
          [resolvedKey]: {
            ...current,
            liveSessionId: session.live_session_id,
            sessionId: snapshot.session_id,
            runtime: runtimeFromSession(session),
            inputEnabled: snapshot.input_enabled,
            waitMessage: snapshot.wait_message,
            sessionUsage: snapshot.session_usage,
            turnUsage: snapshot.turn_usage
              ? {
                  usage: snapshot.turn_usage.usage,
                  elapsedSeconds:
                    typeof snapshot.turn_usage.elapsed_seconds === "number"
                      ? snapshot.turn_usage.elapsed_seconds
                      : undefined,
                }
              : null,
            sessionEnded: snapshot.session_ended,
            fatalError: snapshot.fatal_error,
            items,
            itemsVersion: items.length,
            subAgents: snapshot.sub_agents,
            lastEventSeq: snapshot.last_event_seq,
          },
        },
        liveSessionIndex: {
          ...nextState.liveSessionIndex,
          [session.live_session_id]: resolvedKey,
        },
        sessionIndex: snapshot.session_id
          ? { ...nextState.sessionIndex, [snapshot.session_id]: resolvedKey }
          : nextState.sessionIndex,
      };
    });
    return resolvedKey;
  },
  updateRuntimeFromSession: (sessionKey, session) =>
    set((state) => {
      const current = state.sessionsByKey[sessionKey];
      if (!current) return state;
      return {
        ...state,
        sessionsByKey: {
          ...state.sessionsByKey,
          [sessionKey]: {
            ...current,
            runtime: runtimeFromSession(session),
          },
        },
      };
    }),
  setConnection: (sessionKey, connection) =>
    set((state) => {
      const current = state.sessionsByKey[sessionKey] ?? createEmptySessionState();
      return {
        ...state,
        sessionsByKey: {
          ...state.sessionsByKey,
          [sessionKey]: { ...current, connection },
        },
      };
    }),
  applyEvent: (sessionKey, event) => {
    let resolvedKey = sessionKey;
    set((state) => {
      const payload = event.payload;
      const nextSessionId =
        typeof payload.session_id === "string" ? payload.session_id : null;
      resolvedKey = nextSessionId ? getSavedSessionKey(nextSessionId) : sessionKey;
      let nextState = state;
      if (sessionKey !== resolvedKey) {
        nextState = moveSessionState(state, sessionKey, resolvedKey);
      }
      const current =
        nextState.sessionsByKey[resolvedKey]
        ?? createEmptySessionState(nextSessionId);
      // Skip events already processed — prevents duplicates when the
      // WebSocket reconnects and replays its snapshot over items that
      // were already hydrated from the API (which use different itemIds).
      if (event.seq <= current.lastEventSeq) {
        return nextState;
      }
      const patch: Partial<SessionRuntimeState> = { lastEventSeq: event.seq };
 
      switch (event.type) {
        case "session_reset":
          patch.items = [];
          patch.itemsVersion = 0;
          patch.subAgents = {};
          patch.waitMessage = null;
          patch.turnUsage = null;
          patch.sessionEnded = false;
          patch.fatalError = null;
          break;
        case "session_identity":
          patch.sessionId = nextSessionId;
          break;
        case "input_state":
          patch.inputEnabled = Boolean(payload.enabled);
          break;
        case "wait_state":
          patch.waitMessage = payload.active
            ? readString(payload.message, "Working...")
            : null;
          break;
        case "usage_updated":
          if (payload.scope === "session") {
            patch.sessionUsage = payload.usage as UsagePayload;
          } else {
            patch.turnUsage = {
              usage: payload.usage as UsagePayload,
              elapsedSeconds:
                typeof payload.elapsed_seconds === "number" ? payload.elapsed_seconds : undefined,
            };
          }
          break;
        case "message_added": {
          const item: TimelineItem = {
            kind: "message",
            itemId: String(payload.item_id),
            role: readTimelineRole(payload.role),
            content: readString(payload.content),
            filePaths: Array.isArray(payload.file_paths)
              ? payload.file_paths.filter((value): value is string => typeof value === "string")
              : undefined,
            imageAttachments: Array.isArray(payload.image_attachments)
              ? payload.image_attachments.filter(isImageAttachment)
              : undefined,
            markdown: Boolean(payload.markdown),
            subAgentId: readOptionalString(payload.sub_agent_id),
          };
          patch.items = upsertItem(current.items, item);
          patch.itemsVersion = current.itemsVersion + 1;
          break;
        }
        case "thinking_updated": {
          const item: TimelineItem = {
            kind: "thinking",
            itemId: String(payload.item_id),
            title: readString(payload.title, "Thinking"),
            content: readString(payload.content),
            subAgentId: readOptionalString(payload.sub_agent_id),
          };
          patch.items = upsertItem(current.items, item);
          patch.itemsVersion = current.itemsVersion + 1;
          break;
        }
        case "tool_group_added": {
          const item: TimelineItem = {
            kind: "tool_group",
            itemId: String(payload.item_id),
            label: readString(payload.label, "Tool calls"),
            items: Array.isArray(payload.items)
              ? (payload.items as { text: string; classes?: string }[])
              : [],
            subAgentId: readOptionalString(payload.sub_agent_id),
          };
          patch.items = upsertItem(current.items, item);
          patch.itemsVersion = current.itemsVersion + 1;
          break;
        }
        case "sub_agent_state": {
          const subAgentId = readString(payload.sub_agent_id);
          patch.subAgents = {
            ...current.subAgents,
            [subAgentId]: {
              title: readString(payload.title, "sub_agent"),
              status: readString(payload.status, "running"),
            },
          };
          break;
        }
        case "session_state":
          patch.sessionId = nextSessionId;
          if (payload.state === "ended") {
            patch.sessionEnded = true;
            patch.inputEnabled = false;
            patch.waitMessage = null;
            patch.fatalError =
              typeof payload.fatal_error === "string" ? payload.fatal_error : null;
          } else {
            patch.sessionEnded = false;
            patch.fatalError = null;
          }
          break;
        case "session_runtime_updated":
          if (
            typeof payload.provider === "string"
            && typeof payload.model === "string"
            && typeof payload.reasoning_effort === "string"
          ) {
            patch.runtime = {
              provider_id:
                typeof payload.provider_id === "string" ? payload.provider_id : null,
              profile_id:
                typeof payload.profile_id === "string" ? payload.profile_id : null,
              provider: payload.provider,
              model: payload.model,
              reasoning_effort: payload.reasoning_effort,
            };
          }
          break;
        default:
          break;
      }
 
      const nextSessionState: SessionRuntimeState = {
        ...current,
        ...patch,
        sessionId: patch.sessionId ?? current.sessionId,
      };
 
      const nextLiveSessionIndex = current.liveSessionId
        ? { ...nextState.liveSessionIndex, [current.liveSessionId]: resolvedKey }
        : nextState.liveSessionIndex;
      const nextSessionIndex = nextSessionState.sessionId
        ? { ...nextState.sessionIndex, [nextSessionState.sessionId]: resolvedKey }
        : nextState.sessionIndex;
 
      return {
        ...nextState,
        sessionsByKey: {
          ...nextState.sessionsByKey,
          [resolvedKey]: nextSessionState,
        },
        liveSessionIndex: nextLiveSessionIndex,
        sessionIndex: nextSessionIndex,
      };
    });
    return resolvedKey;
  },
}));