| 1 | export const STREAM_EVENT_NAMES = [ |
| 2 | "thread.started", |
| 3 | "thread.updated", |
| 4 | "thread.forked", |
| 5 | "thread.model_changed", |
| 6 | "thread.permissions_changed", |
| 7 | "thread.plugin_changed", |
| 8 | "turn.started", |
| 9 | "turn.lifecycle", |
| 10 | "turn.usage", |
| 11 | "turn.steered", |
| 12 | "turn.steer_dropped", |
| 13 | "turn.interrupt_requested", |
| 14 | "turn.artifacts", |
| 15 | "turn.workspace_snapshot", |
| 16 | "turn.provider_request", |
| 17 | "turn.completed", |
| 18 | "item.started", |
| 19 | "item.delta", |
| 20 | "item.completed", |
| 21 | "item.canceled", |
| 22 | "item.failed", |
| 23 | "item.interrupted", |
| 24 | "tool.execution_started", |
| 25 | "approval.required", |
| 26 | "approval.decided", |
| 27 | "approval.timeout", |
| 28 | "approval.grant_added", |
| 29 | "approval.grant_revoked", |
| 30 | "user_input.required", |
| 31 | "user_input.answered", |
| 32 | "user_input.canceled", |
| 33 | "sandbox.denied", |
| 34 | "agent.spawned", |
| 35 | "agent.progress", |
| 36 | "agent.completed", |
| 37 | "agent.list", |
| 38 | "tool_call.requested", |
| 39 | "tool_call.resolved", |
| 40 | "tool_call.canceled", |
| 41 | "tool_call.timeout", |
| 42 | ]; |
| 43 | |
| 44 | export function createThreadState(threadId = "") { |
| 45 | return { |
| 46 | threadId, |
| 47 | thread: null, |
| 48 | turns: new Map(), |
| 49 | turnOrder: [], |
| 50 | items: new Map(), |
| 51 | itemOrder: [], |
| 52 | latestSeq: 0, |
| 53 | approvals: new Map(), |
| 54 | userInputs: new Map(), |
| 55 | dynamicToolCalls: new Map(), |
| 56 | }; |
| 57 | } |
| 58 | |
| 59 | export function applySnapshot(state, detail, expectedThreadId = state.threadId) { |
| 60 | if (!detail || !detail.thread || detail.thread.id !== expectedThreadId) { |
| 61 | return false; |
| 62 | } |
| 63 | state.threadId = expectedThreadId; |
| 64 | state.thread = detail.thread; |
| 65 | state.turns = new Map(); |
| 66 | state.turnOrder = []; |
| 67 | for (const turn of Array.isArray(detail.turns) ? detail.turns : []) { |
| 68 | if (!turn || !turn.id) continue; |
| 69 | state.turns.set(turn.id, turn); |
| 70 | state.turnOrder.push(turn.id); |
| 71 | } |
| 72 | state.items = new Map(); |
| 73 | state.itemOrder = []; |
| 74 | for (const item of Array.isArray(detail.items) ? detail.items : []) { |
| 75 | if (!item || !item.id) continue; |
| 76 | state.items.set(item.id, item); |
| 77 | state.itemOrder.push(item.id); |
| 78 | } |
| 79 | state.latestSeq = normalizedSequence(detail.latest_seq); |
| 80 | state.approvals = new Map(); |
| 81 | for (const approval of Array.isArray(detail.pending_approvals) ? detail.pending_approvals : []) { |
| 82 | const approvalId = approval?.approval_id || approval?.id; |
| 83 | if (approvalId) state.approvals.set(approvalId, approval); |
| 84 | } |
| 85 | state.userInputs = new Map(); |
| 86 | for (const input of Array.isArray(detail.pending_user_inputs) ? detail.pending_user_inputs : []) { |
| 87 | const inputId = input?.input_id || input?.id; |
| 88 | if (inputId) state.userInputs.set(inputId, input); |
| 89 | } |
| 90 | state.dynamicToolCalls = new Map(); |
| 91 | for (const call of Array.isArray(detail.pending_dynamic_tool_calls) ? detail.pending_dynamic_tool_calls : []) { |
| 92 | if (call?.call_id) state.dynamicToolCalls.set(call.call_id, call); |
| 93 | } |
| 94 | return true; |
| 95 | } |
| 96 | |
| 97 | export function applyRuntimeEvent(state, envelope) { |
| 98 | if (runtimeEventContinuity(state, envelope) !== "next") { |
| 99 | return false; |
| 100 | } |
| 101 | const sequence = normalizedSequence(envelope.seq); |
| 102 | state.latestSeq = sequence; |
| 103 | |
| 104 | const eventName = envelope.event || envelope.kind || ""; |
| 105 | const payload = envelope.payload && typeof envelope.payload === "object" |
| 106 | ? envelope.payload |
| 107 | : {}; |
| 108 | |
| 109 | if ( |
| 110 | (eventName === "thread.started" || eventName === "thread.updated" || eventName === "thread.forked") |
| 111 | && payload.thread |
| 112 | ) { |
| 113 | state.thread = payload.thread; |
| 114 | } else if (eventName === "turn.started" || eventName === "turn.completed") { |
| 115 | if (payload.turn) upsertTurn(state, payload.turn); |
| 116 | if (eventName === "turn.completed") { |
| 117 | clearTurnAttention(state, envelope.turn_id || payload.turn?.id || ""); |
| 118 | } |
| 119 | } else if (eventName === "turn.lifecycle") { |
| 120 | const turnId = envelope.turn_id; |
| 121 | const turn = turnId ? state.turns.get(turnId) : null; |
| 122 | if (turn && payload.status) { |
| 123 | state.turns.set(turnId, { ...turn, status: payload.status }); |
| 124 | } |
| 125 | } else if (eventName === "turn.interrupt_requested") { |
| 126 | const turnId = envelope.turn_id; |
| 127 | const turn = turnId ? state.turns.get(turnId) : null; |
| 128 | if (turn) state.turns.set(turnId, { ...turn, status: "in_progress" }); |
| 129 | } else if (eventName === "turn.workspace_snapshot") { |
| 130 | // The payload is one restore-point receipt; the turn record keeps them |
| 131 | // in the order the engine took them (`workspace_snapshots`). |
| 132 | const turnId = envelope.turn_id; |
| 133 | const turn = turnId ? state.turns.get(turnId) : null; |
| 134 | if (turn && payload.kind && payload.tree_id) { |
| 135 | const receipts = Array.isArray(turn.workspace_snapshots) ? turn.workspace_snapshots : []; |
| 136 | state.turns.set(turnId, { ...turn, workspace_snapshots: [...receipts, payload] }); |
| 137 | } |
| 138 | } else if ( |
| 139 | eventName === "item.started" |
| 140 | || eventName === "item.completed" |
| 141 | || eventName === "item.canceled" |
| 142 | || eventName === "item.failed" |
| 143 | || eventName === "item.interrupted" |
| 144 | || eventName === "tool.execution_started" |
| 145 | || eventName === "agent.spawned" |
| 146 | || eventName === "agent.progress" |
| 147 | || eventName === "agent.completed" |
| 148 | || eventName === "agent.list" |
| 149 | ) { |
| 150 | if (payload.item) upsertItem(state, payload.item); |
| 151 | } else if (eventName === "item.delta") { |
| 152 | appendItemDelta(state, envelope.item_id, payload); |
| 153 | } else if (eventName === "approval.required") { |
| 154 | const approvalId = payload.approval_id || payload.id; |
| 155 | if (approvalId) { |
| 156 | state.approvals.set(approvalId, { |
| 157 | ...payload, |
| 158 | turn_id: payload.turn_id || envelope.turn_id || "", |
| 159 | }); |
| 160 | } |
| 161 | } else if (eventName === "approval.decided" || eventName === "approval.timeout") { |
| 162 | const approvalId = payload.approval_id || payload.id; |
| 163 | if (approvalId) state.approvals.delete(approvalId); |
| 164 | } else if (eventName === "user_input.required") { |
| 165 | const inputId = payload.id; |
| 166 | if (inputId) { |
| 167 | state.userInputs.set(inputId, { |
| 168 | ...payload, |
| 169 | turn_id: payload.turn_id || envelope.turn_id || "", |
| 170 | }); |
| 171 | } |
| 172 | } else if (eventName === "user_input.answered" || eventName === "user_input.canceled") { |
| 173 | const inputId = payload.input_id || payload.id; |
| 174 | if (inputId) state.userInputs.delete(inputId); |
| 175 | } else if (eventName === "tool_call.requested") { |
| 176 | if (payload.call_id) { |
| 177 | state.dynamicToolCalls.set(payload.call_id, { |
| 178 | ...payload, |
| 179 | turn_id: payload.turn_id || envelope.turn_id || "", |
| 180 | }); |
| 181 | } |
| 182 | } else if ( |
| 183 | eventName === "tool_call.resolved" |
| 184 | || eventName === "tool_call.canceled" |
| 185 | || eventName === "tool_call.timeout" |
| 186 | ) { |
| 187 | if (payload.call_id) state.dynamicToolCalls.delete(payload.call_id); |
| 188 | } |
| 189 | return true; |
| 190 | } |
| 191 | |
| 192 | function clearTurnAttention(state, turnId) { |
| 193 | for (const [id, approval] of state.approvals) { |
| 194 | if (!approval?.turn_id || approval.turn_id === turnId) state.approvals.delete(id); |
| 195 | } |
| 196 | for (const [id, input] of state.userInputs) { |
| 197 | if (!input?.turn_id || input.turn_id === turnId) state.userInputs.delete(id); |
| 198 | } |
| 199 | for (const [id, call] of state.dynamicToolCalls) { |
| 200 | if (!call?.turn_id || call.turn_id === turnId) state.dynamicToolCalls.delete(id); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | export function runtimeEventContinuity(state, envelope) { |
| 205 | if (!envelope || envelope.thread_id !== state.threadId) { |
| 206 | return "ignore"; |
| 207 | } |
| 208 | const sequence = normalizedSequence(envelope.seq); |
| 209 | if (sequence <= state.latestSeq) { |
| 210 | return "ignore"; |
| 211 | } |
| 212 | if (Object.hasOwn(envelope, "previous_seq")) { |
| 213 | const previousSequence = normalizedSequence(envelope.previous_seq); |
| 214 | if (previousSequence !== state.latestSeq) { |
| 215 | return "gap"; |
| 216 | } |
| 217 | } |
| 218 | return "next"; |
| 219 | } |
| 220 | |
| 221 | export async function snapshotThenSubscribe({ |
| 222 | state, |
| 223 | threadId, |
| 224 | loadSnapshot, |
| 225 | subscribe, |
| 226 | isCurrent = () => true, |
| 227 | }) { |
| 228 | const detail = await loadSnapshot(threadId); |
| 229 | if (!isCurrent() || !applySnapshot(state, detail, threadId)) { |
| 230 | return false; |
| 231 | } |
| 232 | if (!isCurrent()) return false; |
| 233 | // A recovery caller may return a stream-open handshake. Await it so a |
| 234 | // replacement snapshot is not called continuous until the replacement SSE |
| 235 | // stream has actually opened. Synchronous subscribers remain supported. |
| 236 | await subscribe(threadId, state.latestSeq); |
| 237 | return true; |
| 238 | } |
| 239 | |
| 240 | export async function recoverSnapshotAndSubscribe(options, onRecovered) { |
| 241 | const subscribed = await snapshotThenSubscribe(options); |
| 242 | if (!subscribed) return false; |
| 243 | onRecovered(); |
| 244 | return true; |
| 245 | } |
| 246 | |
| 247 | // --------------------------------------------------------------------------- |
| 248 | // Typed selection identity (#4397) |
| 249 | // |
| 250 | // The dashboard can have two very different things selected: a *saved session* |
| 251 | // (a recording on disk) or a *live thread* (a running runtime object). Almost |
| 252 | // every safety rule in this slice reduces to "which one is it?", so the answer |
| 253 | // is a typed value rather than a pair of loosely-related string fields that can |
| 254 | // both be set, both be empty, or disagree. |
| 255 | // --------------------------------------------------------------------------- |
| 256 | |
| 257 | // Nothing selected. |
| 258 | export const NO_TARGET = Object.freeze({ kind: "none" }); |
| 259 | |
| 260 | // A saved session: read-only. Peek only, never reply, never approve. |
| 261 | export function sessionTarget(sessionId) { |
| 262 | return Object.freeze({ kind: "session", sessionId: String(sessionId || "") }); |
| 263 | } |
| 264 | |
| 265 | // A live thread: the only thing that can receive a reply or an approval. |
| 266 | export function threadTarget(threadId) { |
| 267 | return Object.freeze({ kind: "thread", threadId: String(threadId || "") }); |
| 268 | } |
| 269 | |
| 270 | // May the composer send to this target? |
| 271 | // |
| 272 | // Only a live thread. A saved session has no runtime to receive a message; |
| 273 | // offering a composer against one would be an affordance with nothing behind |
| 274 | // it, and "resume it silently on send" would attach the user's message to a |
| 275 | // thread they never asked to create. |
| 276 | export function canReply(target) { |
| 277 | return target?.kind === "thread" && Boolean(target.threadId); |
| 278 | } |
| 279 | |
| 280 | // Resolve the id a reply must be POSTed to, or an explicit refusal. |
| 281 | // |
| 282 | // Fails closed on every ambiguity: no target, a session target, or a target |
| 283 | // whose thread is not the one the live stream is following (a stale target — |
| 284 | // the user changed rows while a request was in flight). |
| 285 | export function resolveReplyTarget(target, streamState) { |
| 286 | if (!target || target.kind === "none") { |
| 287 | return { ok: false, reason: "no-target" }; |
| 288 | } |
| 289 | if (target.kind === "session") { |
| 290 | return { ok: false, reason: "session-not-live" }; |
| 291 | } |
| 292 | if (!target.threadId) { |
| 293 | return { ok: false, reason: "no-target" }; |
| 294 | } |
| 295 | if (streamState && streamState.threadId && streamState.threadId !== target.threadId) { |
| 296 | return { ok: false, reason: "stale-target" }; |
| 297 | } |
| 298 | return { ok: true, threadId: target.threadId }; |
| 299 | } |
| 300 | |
| 301 | // Resolve an approval decision to the thread that owns it, or refuse. |
| 302 | // |
| 303 | // An approval is authority: answering the wrong one, or answering one that |
| 304 | // has already been decided elsewhere, is worse than not answering. So the |
| 305 | // approval must be present in the *current* stream state, and that state must |
| 306 | // belong to the selected live thread. |
| 307 | export function resolveApprovalTarget(approvalId, target, streamState) { |
| 308 | const reply = resolveReplyTarget(target, streamState); |
| 309 | if (!reply.ok) return reply; |
| 310 | if (!approvalId) return { ok: false, reason: "no-approval" }; |
| 311 | if (!streamState || streamState.threadId !== reply.threadId) { |
| 312 | return { ok: false, reason: "stale-target" }; |
| 313 | } |
| 314 | if (!streamState.approvals || !streamState.approvals.has(approvalId)) { |
| 315 | // Decided, timed out, or belonging to a thread we are no longer watching. |
| 316 | return { ok: false, reason: "stale-approval" }; |
| 317 | } |
| 318 | return { ok: true, threadId: reply.threadId, approvalId }; |
| 319 | } |
| 320 | |
| 321 | // Resolve a user-input submission to the live thread and pending request that |
| 322 | // own it. User-input answers can resume a paused turn, so a stale card must not |
| 323 | // be able to answer a request from another thread or one already settled by a |
| 324 | // different client. |
| 325 | export function resolveUserInputTarget(inputId, target, streamState) { |
| 326 | const reply = resolveReplyTarget(target, streamState); |
| 327 | if (!reply.ok) return reply; |
| 328 | if (!inputId) return { ok: false, reason: "no-user-input" }; |
| 329 | if (!streamState || streamState.threadId !== reply.threadId) { |
| 330 | return { ok: false, reason: "stale-target" }; |
| 331 | } |
| 332 | if (!streamState.userInputs || !streamState.userInputs.has(inputId)) { |
| 333 | return { ok: false, reason: "stale-user-input" }; |
| 334 | } |
| 335 | return { ok: true, threadId: reply.threadId, inputId }; |
| 336 | } |
| 337 | |
| 338 | function ownAnswerValue(collection, id) { |
| 339 | if (collection instanceof Map) return collection.get(id); |
| 340 | if (collection && typeof collection === "object" && Object.hasOwn(collection, id)) { |
| 341 | return collection[id]; |
| 342 | } |
| 343 | return undefined; |
| 344 | } |
| 345 | |
| 346 | // Build the exact Runtime answer payload from selected options and custom |
| 347 | // text. This keeps single-select questions single, rejects stale/forged option |
| 348 | // values, and preserves the TUI rule that a custom answer is always reachable. |
| 349 | export function answersForUserInput(request, selections = {}, freeText = {}) { |
| 350 | const questions = Array.isArray(request?.questions) ? request.questions : []; |
| 351 | if (questions.length === 0) { |
| 352 | return { ok: false, reason: "invalid-request", question: "the question" }; |
| 353 | } |
| 354 | |
| 355 | const answers = []; |
| 356 | const questionIds = new Set(); |
| 357 | for (const question of questions) { |
| 358 | const id = String(question?.id || ""); |
| 359 | const questionLabel = String(question?.header || question?.question || id || "the question"); |
| 360 | if (!id || questionIds.has(id)) { |
| 361 | return { ok: false, reason: "invalid-request", question: questionLabel }; |
| 362 | } |
| 363 | questionIds.add(id); |
| 364 | |
| 365 | const optionLabels = new Set( |
| 366 | (Array.isArray(question.options) ? question.options : []) |
| 367 | .map((option) => String(option?.label || "")) |
| 368 | .filter((value) => Boolean(value.trim())), |
| 369 | ); |
| 370 | const selectedValue = ownAnswerValue(selections, id); |
| 371 | const selected = Array.isArray(selectedValue) |
| 372 | ? [...new Set(selectedValue.map((value) => String(value)).filter((value) => value.trim()))] |
| 373 | : []; |
| 374 | if (selected.some((value) => !optionLabels.has(value))) { |
| 375 | return { ok: false, reason: "invalid-option", question: questionLabel }; |
| 376 | } |
| 377 | |
| 378 | const otherValue = ownAnswerValue(freeText, id); |
| 379 | const other = String(otherValue || "").trim(); |
| 380 | const count = selected.length + (other ? 1 : 0); |
| 381 | if (count === 0) { |
| 382 | return { ok: false, reason: "missing-answer", question: questionLabel }; |
| 383 | } |
| 384 | if (!question.multi_select && count !== 1) { |
| 385 | return { ok: false, reason: "multiple-answers", question: questionLabel }; |
| 386 | } |
| 387 | |
| 388 | for (const value of selected) answers.push({ id, label: value, value }); |
| 389 | if (other) answers.push({ id, label: "Other", value: other }); |
| 390 | } |
| 391 | return { ok: true, answers }; |
| 392 | } |
| 393 | |
| 394 | // Human-readable reason for a refusal, for the status banner. |
| 395 | export function refusalMessage(reason) { |
| 396 | switch (reason) { |
| 397 | case "session-not-live": |
| 398 | return "This is a saved session, not a live thread — nothing was sent. Resume it first to reply."; |
| 399 | case "stale-target": |
| 400 | return "That thread is no longer the selected one — nothing was sent."; |
| 401 | case "stale-approval": |
| 402 | return "That request was already answered or has expired — nothing was sent."; |
| 403 | case "no-approval": |
| 404 | return "No approval was identified — nothing was sent."; |
| 405 | case "stale-user-input": |
| 406 | return "That question was already answered or has expired — nothing was sent."; |
| 407 | case "no-user-input": |
| 408 | return "No user-input request was identified — nothing was sent."; |
| 409 | default: |
| 410 | return "Select a live thread first — nothing was sent."; |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | // The SSE resume cursor and whether the stream is known to have a gap. |
| 415 | // |
| 416 | // Surfaced rather than kept internal: after a reconnect the user needs to |
| 417 | // know whether what they are reading is continuous or whether events were |
| 418 | // missed and a re-snapshot is pending. |
| 419 | export function streamCursor(state, { gap = false, connected = true } = {}) { |
| 420 | const seq = normalizedSequence(state?.latestSeq); |
| 421 | return { |
| 422 | latestSeq: seq, |
| 423 | gap: Boolean(gap), |
| 424 | connected: Boolean(connected), |
| 425 | label: !connected |
| 426 | ? `Reconnecting — resuming from #${seq}` |
| 427 | : gap |
| 428 | ? `Gap detected — re-syncing from #${seq}` |
| 429 | : `Live — event #${seq}`, |
| 430 | }; |
| 431 | } |
| 432 | |
| 433 | // Keep machine diagnostics available without making them the conversation's |
| 434 | // loudest content. Known transport failures get one calm product sentence; |
| 435 | // the byte-for-byte receipt remains behind the disclosure. |
| 436 | export function receiptPresentation(item = {}) { |
| 437 | const detail = String(item.detail || item.summary || ""); |
| 438 | const raw = String(item.summary || detail || humanize(item.kind)); |
| 439 | const fullRaw = detail && detail !== raw ? `${raw}\n\n${detail}` : raw; |
| 440 | const workflow = workflowReceiptPresentation(item, detail, fullRaw); |
| 441 | if (workflow) return workflow; |
| 442 | const mcpFailure = raw.match(/Failed to connect MCP server ['"]?([^'":\s]+)['"]?/i); |
| 443 | if (mcpFailure) { |
| 444 | const server = mcpFailure[1] || "server"; |
| 445 | return { |
| 446 | label: "MCP · Unavailable", |
| 447 | summary: `${server} could not connect`, |
| 448 | raw, |
| 449 | failed: true, |
| 450 | }; |
| 451 | } |
| 452 | const failed = item.status === "failed" || /^(?:error|failed|failure)\b/i.test(raw); |
| 453 | return { |
| 454 | label: `${humanize(item.kind)} · ${humanize(item.status)}`, |
| 455 | summary: raw, |
| 456 | raw: fullRaw, |
| 457 | failed, |
| 458 | }; |
| 459 | } |
| 460 | |
| 461 | export function workflowReceiptPresentation(item, detail, raw) { |
| 462 | const metadata = item?.metadata && typeof item.metadata === "object" |
| 463 | ? item.metadata |
| 464 | : {}; |
| 465 | let payload = null; |
| 466 | try { |
| 467 | const parsed = JSON.parse(detail); |
| 468 | if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) payload = parsed; |
| 469 | } catch (_error) { |
| 470 | // Non-JSON tool receipts continue through the ordinary presentation path. |
| 471 | } |
| 472 | const looksLikeWorkflow = /^workflow(?:\s|:)/i.test(String(item?.summary || "")) |
| 473 | || Object.hasOwn(metadata, "dispatch_failure_count") |
| 474 | || Boolean(payload && Object.hasOwn(payload, "dispatch_failure_count")); |
| 475 | if (!looksLikeWorkflow) return null; |
| 476 | |
| 477 | const status = String(metadata.status || payload?.status || "").toLowerCase(); |
| 478 | const countValue = metadata.dispatch_failure_count ?? payload?.dispatch_failure_count; |
| 479 | const count = Number(countValue); |
| 480 | const rejected = Number.isSafeInteger(count) && count > 0 ? count : 0; |
| 481 | if (rejected === 0 && status !== "degraded" && status !== "failed") return null; |
| 482 | |
| 483 | const summary = rejected === 1 |
| 484 | ? "1 task dispatch was rejected" |
| 485 | : rejected > 1 |
| 486 | ? `${rejected} task dispatches were rejected` |
| 487 | : status === "failed" |
| 488 | ? "The workflow did not complete" |
| 489 | : "The workflow completed with degraded results"; |
| 490 | return { |
| 491 | label: status === "failed" ? "Workflow · Failed" : "Workflow · Needs attention", |
| 492 | summary, |
| 493 | raw, |
| 494 | failed: true, |
| 495 | }; |
| 496 | } |
| 497 | |
| 498 | export function eventStreamUrl(threadId, latestSeq, ticket = "") { |
| 499 | const url = `/v1/threads/${encodeURIComponent(threadId)}/events?since_seq=${normalizedSequence(latestSeq)}`; |
| 500 | return ticket ? `${url}&web_stream_ticket=${encodeURIComponent(ticket)}` : url; |
| 501 | } |
| 502 | |
| 503 | export function approvalRequestText(input) { |
| 504 | if (input == null) return ""; |
| 505 | if (typeof input === "string") return input; |
| 506 | if (typeof input !== "object") return String(input); |
| 507 | const { command, ...rest } = input; |
| 508 | const parts = []; |
| 509 | if (typeof command === "string") parts.push(command); |
| 510 | const restKeys = Object.keys(rest); |
| 511 | if (restKeys.length > 0 || typeof command !== "string") { |
| 512 | parts.push(JSON.stringify(typeof command === "string" ? rest : input, null, 2)); |
| 513 | } |
| 514 | return parts.join("\n\n"); |
| 515 | } |
| 516 | |
| 517 | export const PEEK_DEFAULT_ENTRIES = 12; |
| 518 | export const PEEK_EXPANDED_ENTRIES = 100; |
| 519 | |
| 520 | export function approvalCardCopy(approval) { |
| 521 | const summary = String(approval?.summary || "").trim(); |
| 522 | const description = String(approval?.description || "").trim(); |
| 523 | if (summary) { |
| 524 | return { lead: summary, detail: description && description !== summary ? description : "" }; |
| 525 | } |
| 526 | if (!description) return { lead: "Codewhale is waiting for permission.", detail: "" }; |
| 527 | const sentence = description.match(/^[\s\S]*?[.!?](?=\s|$)/); |
| 528 | let lead = sentence ? sentence[0] : description; |
| 529 | if (lead.length > 160) lead = `${lead.slice(0, 159).trimEnd()}…`; |
| 530 | return { lead, detail: description !== lead ? description : "" }; |
| 531 | } |
| 532 | |
| 533 | export function peekOmittedLabel(peek) { |
| 534 | const omitted = Number(peek?.omitted_before) || 0; |
| 535 | if (omitted <= 0) return ""; |
| 536 | const shown = Array.isArray(peek?.entries) ? peek.entries.length : 0; |
| 537 | return `Showing the last ${shown} of ${shown + omitted} messages`; |
| 538 | } |
| 539 | |
| 540 | export function peekCanShowEarlier(peek, requestedEntries) { |
| 541 | return (Number(peek?.omitted_before) || 0) > 0 && requestedEntries < PEEK_EXPANDED_ENTRIES; |
| 542 | } |
| 543 | |
| 544 | export function savedSessionNotice() { |
| 545 | return "This is a saved recording, so it is read-only. Resume it to continue in a live thread."; |
| 546 | } |
| 547 | |
| 548 | export function composerPlaceholderFor(target, fallback) { |
| 549 | return target?.kind === "session" |
| 550 | ? "Saved session. Click Resume to continue it." |
| 551 | : fallback; |
| 552 | } |
| 553 | |
| 554 | export function showNoMatchingThreads(summaries, sessionSummaries) { |
| 555 | return summaries.length === 0 && sessionSummaries.length === 0; |
| 556 | } |
| 557 | |
| 558 | export function headerTitleFor({ thread, summary, target, peek }) { |
| 559 | if (thread) return thread.title || summary?.title || "New thread"; |
| 560 | if (summary?.title) return summary.title; |
| 561 | if (target?.kind === "session") return peek?.title || "Saved session"; |
| 562 | return "Choose a thread"; |
| 563 | } |
| 564 | |
| 565 | export function createWebSessionFetch({ location, history, storage, fetch }) { |
| 566 | const key = "codewhale_web_request_proof"; |
| 567 | const fragmentProof = new URLSearchParams(location.hash.slice(1)).get("p"); |
| 568 | if (fragmentProof) history.replaceState(null, "", location.pathname + location.search); |
| 569 | let proof = fragmentProof || ""; |
| 570 | if (proof) { |
| 571 | try { storage().setItem(key, proof); } catch (_) { /* Memory-only session. */ } |
| 572 | } else { |
| 573 | try { proof = storage().getItem(key) || ""; } catch (_) { /* Storage unavailable. */ } |
| 574 | } |
| 575 | return (path, options = {}) => { |
| 576 | const headers = new Headers(options.headers || {}); |
| 577 | headers.set("x-codewhale-web-request", proof); |
| 578 | if (options.body != null && !headers.has("content-type")) { |
| 579 | headers.set("content-type", "application/json"); |
| 580 | } |
| 581 | return fetch(path, { ...options, headers, credentials: "same-origin", cache: "no-store" }); |
| 582 | }; |
| 583 | } |
| 584 | |
| 585 | // One owner for pending ticket requests, EventSources, and reconnect timers. |
| 586 | // Ticket HTTP 401/403 ends retries; EventSource hides HTTP status, so its |
| 587 | // errors retry through a fresh ticket request. Snapshot recovery owns its |
| 588 | // own retry when it requests an open handshake. |
| 589 | export function createStreamConnector({ |
| 590 | app, api, EventSource, receive, setConnection, showStatus, |
| 591 | setTimeout = globalThis.setTimeout, clearTimeout = globalThis.clearTimeout, |
| 592 | }) { |
| 593 | let attempt = 0; |
| 594 | let retryDelay = 900; |
| 595 | function stopStream() { |
| 596 | attempt += 1; |
| 597 | if (app.streamOpenCancel) app.streamOpenCancel(); |
| 598 | app.streamOpenCancel = null; |
| 599 | if (app.stream) app.stream.close(); |
| 600 | app.stream = null; |
| 601 | if (app.reconnectTimer) clearTimeout(app.reconnectTimer); |
| 602 | app.reconnectTimer = null; |
| 603 | } |
| 604 | |
| 605 | async function connectStream(threadId, sequence, generation, waitForOpen = false) { |
| 606 | if (generation !== app.generation || threadId !== app.selectedThreadId) return; |
| 607 | stopStream(); |
| 608 | const currentAttempt = attempt; |
| 609 | const isCurrent = () => currentAttempt === attempt |
| 610 | && generation === app.generation && threadId === app.selectedThreadId; |
| 611 | const reconnect = () => { |
| 612 | if (!isCurrent() || app.stream !== null) return; |
| 613 | setConnection("", "Reconnecting to local runtime…"); |
| 614 | app.reconnectTimer = setTimeout(() => { |
| 615 | app.reconnectTimer = null; |
| 616 | if (!isCurrent() || app.stream !== null) return; |
| 617 | void connectStream(threadId, app.threadState.latestSeq, generation).catch(() => {}); |
| 618 | }, retryDelay); |
| 619 | retryDelay = Math.min(retryDelay * 2, 30_000); |
| 620 | }; |
| 621 | let ticket; |
| 622 | try { |
| 623 | ({ stream_ticket: ticket } = await api("/__codewhale/web/stream-ticket", { method: "POST" })); |
| 624 | } catch (error) { |
| 625 | if (!isCurrent()) return; |
| 626 | showStatus(error.message); |
| 627 | setConnection("error", "Runtime connection failed"); |
| 628 | if (!waitForOpen && error.status !== 401 && error.status !== 403) reconnect(); |
| 629 | throw error; |
| 630 | } |
| 631 | if (!isCurrent() || app.stream !== null) return; |
| 632 | const stream = new EventSource(eventStreamUrl(threadId, sequence, ticket), { withCredentials: true }); |
| 633 | app.stream = stream; |
| 634 | let opened = false; |
| 635 | let resolveOpen; |
| 636 | let rejectOpen; |
| 637 | const openHandshake = waitForOpen |
| 638 | ? new Promise((resolve, reject) => { |
| 639 | resolveOpen = resolve; |
| 640 | rejectOpen = reject; |
| 641 | }) |
| 642 | : undefined; |
| 643 | const cancelOpen = () => { |
| 644 | if (!rejectOpen) return; |
| 645 | const reject = rejectOpen; |
| 646 | resolveOpen = null; |
| 647 | rejectOpen = null; |
| 648 | reject(new Error("Runtime event stream open was cancelled")); |
| 649 | }; |
| 650 | if (waitForOpen) app.streamOpenCancel = cancelOpen; |
| 651 | const clearOpenHandshake = () => { |
| 652 | if (app.streamOpenCancel === cancelOpen) app.streamOpenCancel = null; |
| 653 | }; |
| 654 | stream.onopen = () => { |
| 655 | if (!isCurrent() || app.stream !== stream) { |
| 656 | stream.close(); |
| 657 | return; |
| 658 | } |
| 659 | retryDelay = 900; |
| 660 | opened = true; |
| 661 | setConnection("ready", "Local runtime connected"); |
| 662 | clearOpenHandshake(); |
| 663 | if (resolveOpen) resolveOpen(); |
| 664 | resolveOpen = null; |
| 665 | rejectOpen = null; |
| 666 | }; |
| 667 | for (const name of STREAM_EVENT_NAMES) { |
| 668 | stream.addEventListener(name, (message) => { |
| 669 | if (isCurrent() && app.stream === stream) receive(stream, message, threadId, generation); |
| 670 | }); |
| 671 | } |
| 672 | stream.onerror = () => { |
| 673 | if (app.stream !== stream) { |
| 674 | stream.close(); |
| 675 | return; |
| 676 | } |
| 677 | stream.close(); |
| 678 | app.stream = null; |
| 679 | if (generation !== app.generation || threadId !== app.selectedThreadId) return; |
| 680 | if (waitForOpen && !opened) { |
| 681 | clearOpenHandshake(); |
| 682 | const reject = rejectOpen; |
| 683 | resolveOpen = null; |
| 684 | rejectOpen = null; |
| 685 | reject?.(new Error("Runtime event stream did not reopen")); |
| 686 | return; |
| 687 | } |
| 688 | reconnect(); |
| 689 | }; |
| 690 | return openHandshake; |
| 691 | } |
| 692 | |
| 693 | return { connectStream, stopStream }; |
| 694 | } |
| 695 | |
| 696 | export function saveDraft(drafts, threadId, value) { |
| 697 | if (!threadId) return; |
| 698 | if (value) drafts.set(threadId, value); |
| 699 | else drafts.delete(threadId); |
| 700 | } |
| 701 | |
| 702 | export function restoreDraft(drafts, threadId) { |
| 703 | return drafts.get(threadId) || ""; |
| 704 | } |
| 705 | |
| 706 | export function pendingAttentionCount(summary) { |
| 707 | const count = Number(summary?.pending_attention_count); |
| 708 | return Number.isSafeInteger(count) && count > 0 ? count : 0; |
| 709 | } |
| 710 | |
| 711 | // Preserve the Runtime's newest-first order within each group. The server's |
| 712 | // typed pending-request count is the only attention authority; status prose |
| 713 | // and turn lifecycle strings deliberately do not participate. |
| 714 | export function groupThreadSummaries(summaries) { |
| 715 | const groups = { needsYou: [], recent: [] }; |
| 716 | for (const summary of Array.isArray(summaries) ? summaries : []) { |
| 717 | const group = pendingAttentionCount(summary) > 0 ? groups.needsYou : groups.recent; |
| 718 | group.push(summary); |
| 719 | } |
| 720 | return groups; |
| 721 | } |
| 722 | |
| 723 | export function pendingAttentionLabel(summary) { |
| 724 | const count = pendingAttentionCount(summary); |
| 725 | return count === 1 |
| 726 | ? "1 item needs your attention" |
| 727 | : `${count} items need your attention`; |
| 728 | } |
| 729 | |
| 730 | // Match the CWC composer grammar while keeping the embedded client free of a |
| 731 | // framework dependency: Enter sends, Shift+Enter inserts a newline, and an |
| 732 | // active IME composition is never interrupted. |
| 733 | export function isComposerSubmitKey({ key, shiftKey = false, isComposing = false } = {}) { |
| 734 | return key === "Enter" && !shiftKey && !isComposing; |
| 735 | } |
| 736 | |
| 737 | export function newThreadDefaults(catalog) { |
| 738 | const providers = Array.isArray(catalog?.providers) |
| 739 | ? catalog.providers.filter((provider) => String(provider?.id || "").trim()) |
| 740 | : []; |
| 741 | const current = String(catalog?.current || "").trim(); |
| 742 | const currentProviderId = String(catalog?.current_provider_id || "").trim(); |
| 743 | const provider = providers.find((entry) => entry.id === current |
| 744 | && (!currentProviderId || entry.model_provider_id === currentProviderId)); |
| 745 | const selected = provider || providers.find((entry) => entry.id === current) || providers[0] || null; |
| 746 | return { |
| 747 | providerId: String(selected?.id || "").trim(), |
| 748 | modelProviderId: String(selected?.model_provider_id || "").trim(), |
| 749 | model: String(selected?.default_model || "").trim(), |
| 750 | }; |
| 751 | } |
| 752 | |
| 753 | export function imageInputPresentation(value) { |
| 754 | if (value === "supported") { |
| 755 | return { |
| 756 | state: "supported", |
| 757 | label: "Vision", |
| 758 | description: "This exact provider route supports image input. Browser attachments are not enabled yet.", |
| 759 | }; |
| 760 | } |
| 761 | if (value === "unsupported") { |
| 762 | return { |
| 763 | state: "unsupported", |
| 764 | label: "Text only", |
| 765 | description: "This exact provider route does not support image input.", |
| 766 | }; |
| 767 | } |
| 768 | return { |
| 769 | state: "unknown", |
| 770 | label: "Image support unverified", |
| 771 | description: "Image-input support is not verified for this exact provider route.", |
| 772 | }; |
| 773 | } |
| 774 | |
| 775 | export function modelOptionLabel(model) { |
| 776 | const id = String(model?.id || "").trim(); |
| 777 | return model?.image_input === "supported" ? `${id} · Vision` : id; |
| 778 | } |
| 779 | |
| 780 | export function providerOptionLabel(provider) { |
| 781 | const id = String(provider?.id || "").trim(); |
| 782 | const displayName = String(provider?.display_name || id).trim(); |
| 783 | const exactId = String(provider?.model_provider_id || "").trim(); |
| 784 | return exactId && exactId !== id ? `${displayName} · ${exactId}` : displayName; |
| 785 | } |
| 786 | |
| 787 | export function buildCreateThreadRequest(providerId, model, modelProviderId = "") { |
| 788 | const modelProvider = String(providerId || "").trim(); |
| 789 | const exactProviderId = String(modelProviderId || "").trim(); |
| 790 | const selectedModel = String(model || "").trim(); |
| 791 | if (!modelProvider || !selectedModel) { |
| 792 | throw new Error("Choose both a provider and a model."); |
| 793 | } |
| 794 | const request = { model_provider: modelProvider, model: selectedModel }; |
| 795 | if (exactProviderId) request.model_provider_id = exactProviderId; |
| 796 | return request; |
| 797 | } |
| 798 | |
| 799 | export function threadProviderLabel(thread) { |
| 800 | const exact = String(thread?.model_provider_id || "").trim(); |
| 801 | const generic = String(thread?.model_provider || "").trim(); |
| 802 | return exact || generic; |
| 803 | } |
| 804 | |
| 805 | export function claimInFlight(inFlight, key) { |
| 806 | const action = String(key || "").trim(); |
| 807 | if (!(inFlight instanceof Set) || !action || inFlight.has(action)) return false; |
| 808 | inFlight.add(action); |
| 809 | return true; |
| 810 | } |
| 811 | |
| 812 | export function setSafeText(element, value) { |
| 813 | element.textContent = value == null ? "" : String(value); |
| 814 | return element; |
| 815 | } |
| 816 | |
| 817 | function normalizedSequence(value) { |
| 818 | const sequence = Number(value); |
| 819 | return Number.isSafeInteger(sequence) && sequence > 0 ? sequence : 0; |
| 820 | } |
| 821 | |
| 822 | function upsertTurn(state, turn) { |
| 823 | if (!turn || !turn.id) return; |
| 824 | if (!state.turns.has(turn.id)) state.turnOrder.push(turn.id); |
| 825 | state.turns.set(turn.id, turn); |
| 826 | } |
| 827 | |
| 828 | function upsertItem(state, item) { |
| 829 | if (!item || !item.id) return; |
| 830 | if (!state.items.has(item.id)) state.itemOrder.push(item.id); |
| 831 | state.items.set(item.id, item); |
| 832 | } |
| 833 | |
| 834 | function appendItemDelta(state, itemId, payload) { |
| 835 | if (!itemId) return; |
| 836 | const delta = typeof payload.delta === "string" ? payload.delta : ""; |
| 837 | const existing = state.items.get(itemId) || { |
| 838 | id: itemId, |
| 839 | turn_id: "", |
| 840 | kind: payload.kind || "agent_message", |
| 841 | status: "in_progress", |
| 842 | summary: "", |
| 843 | detail: "", |
| 844 | }; |
| 845 | if (!state.items.has(itemId)) state.itemOrder.push(itemId); |
| 846 | state.items.set(itemId, { |
| 847 | ...existing, |
| 848 | status: "in_progress", |
| 849 | detail: `${existing.detail || ""}${delta}`, |
| 850 | }); |
| 851 | } |
| 852 | |
| 853 | const PROVIDER_MODELS_PAGE_SIZE = 250; |
| 854 | const MAX_PROVIDER_MODELS = 10_000; |
| 855 | const MAX_PROVIDER_MODEL_PAGES = Math.ceil( |
| 856 | MAX_PROVIDER_MODELS / PROVIDER_MODELS_PAGE_SIZE, |
| 857 | ); |
| 858 | |
| 859 | /** |
| 860 | * Load every bounded page of one provider catalog. |
| 861 | * |
| 862 | * `fetchPage` is injected so the browser client can retain its authenticated |
| 863 | * Runtime API boundary and tests can prove catalogs larger than one page are |
| 864 | * not silently truncated. Cursors are opaque and may never repeat. |
| 865 | */ |
| 866 | export async function collectProviderModelPages(providerId, fetchPage, modelProviderId = "") { |
| 867 | const provider = String(providerId || "").trim(); |
| 868 | const exactProviderId = String(modelProviderId || "").trim(); |
| 869 | if (!provider || typeof fetchPage !== "function") { |
| 870 | throw new Error("A provider and page loader are required."); |
| 871 | } |
| 872 | |
| 873 | const entries = []; |
| 874 | const seenCursors = new Set(); |
| 875 | let expectedTotal; |
| 876 | let cursor = ""; |
| 877 | for (let page = 0; page < MAX_PROVIDER_MODEL_PAGES; page += 1) { |
| 878 | const query = new URLSearchParams({ limit: String(PROVIDER_MODELS_PAGE_SIZE) }); |
| 879 | if (exactProviderId) query.set("model_provider_id", exactProviderId); |
| 880 | if (cursor) query.set("cursor", cursor); |
| 881 | const response = await fetchPage( |
| 882 | `/v1/providers/${encodeURIComponent(provider)}/models?${query.toString()}`, |
| 883 | ); |
| 884 | if (String(response?.provider || "") !== provider |
| 885 | || (exactProviderId && String(response?.model_provider_id || "") !== exactProviderId)) { |
| 886 | throw new Error("The Runtime returned a model page for a different provider."); |
| 887 | } |
| 888 | if (!Array.isArray(response?.models) |
| 889 | || response.models.length > PROVIDER_MODELS_PAGE_SIZE |
| 890 | || !Number.isSafeInteger(response.total) |
| 891 | || response.total < 0 |
| 892 | || response.total > MAX_PROVIDER_MODELS) { |
| 893 | throw new Error("The Runtime returned an invalid provider model page."); |
| 894 | } |
| 895 | if (expectedTotal !== undefined && expectedTotal !== response.total) { |
| 896 | throw new Error("The provider catalog changed; restart loading its models."); |
| 897 | } |
| 898 | expectedTotal = response.total; |
| 899 | const pageEntries = response.models; |
| 900 | if (entries.length + pageEntries.length > MAX_PROVIDER_MODELS) { |
| 901 | throw new Error(`The provider catalog exceeds ${MAX_PROVIDER_MODELS} models.`); |
| 902 | } |
| 903 | entries.push(...pageEntries); |
| 904 | |
| 905 | const nextCursor = typeof response?.nextCursor === "string" |
| 906 | ? response.nextCursor.trim() |
| 907 | : ""; |
| 908 | if (!nextCursor) { |
| 909 | if (entries.length !== expectedTotal) { |
| 910 | throw new Error("The Runtime returned an incomplete provider model catalog."); |
| 911 | } |
| 912 | return entries; |
| 913 | } |
| 914 | if (pageEntries.length === 0 || seenCursors.has(nextCursor)) { |
| 915 | throw new Error("The Runtime returned a non-progressing model cursor."); |
| 916 | } |
| 917 | if (entries.length >= expectedTotal) { |
| 918 | throw new Error("The Runtime returned a cursor beyond its provider model catalog."); |
| 919 | } |
| 920 | seenCursors.add(nextCursor); |
| 921 | cursor = nextCursor; |
| 922 | } |
| 923 | throw new Error(`The provider catalog exceeds ${MAX_PROVIDER_MODELS} models.`); |
| 924 | } |
| 925 | |
| 926 | function startBrowserClient() { |
| 927 | const dom = { |
| 928 | shell: document.querySelector("#app-shell"), |
| 929 | rail: document.querySelector("#thread-rail"), |
| 930 | railOpen: document.querySelector("#rail-open"), |
| 931 | railClose: document.querySelector("#rail-close"), |
| 932 | railScrim: document.querySelector("#rail-scrim"), |
| 933 | search: document.querySelector("#thread-search"), |
| 934 | threadList: document.querySelector("#thread-list"), |
| 935 | newThread: document.querySelector("#new-thread"), |
| 936 | newThreadDialog: document.querySelector("#new-thread-dialog"), |
| 937 | newThreadForm: document.querySelector("#new-thread-form"), |
| 938 | newThreadProvider: document.querySelector("#new-thread-provider"), |
| 939 | newThreadModel: document.querySelector("#new-thread-model"), |
| 940 | newThreadModelSelectField: document.querySelector("#new-thread-model-select-field"), |
| 941 | newThreadModelInput: document.querySelector("#new-thread-model-input"), |
| 942 | newThreadModelInputField: document.querySelector("#new-thread-model-input-field"), |
| 943 | newThreadCapability: document.querySelector("#new-thread-capability"), |
| 944 | newThreadStatus: document.querySelector("#new-thread-status"), |
| 945 | newThreadCancel: document.querySelector("#new-thread-cancel"), |
| 946 | newThreadCreate: document.querySelector("#new-thread-create"), |
| 947 | connectionDot: document.querySelector("#connection-dot"), |
| 948 | connectionLabel: document.querySelector("#connection-label"), |
| 949 | runtimeProvenance: document.querySelector("#runtime-provenance"), |
| 950 | kicker: document.querySelector("#session-kicker"), |
| 951 | title: document.querySelector("#session-title"), |
| 952 | facts: document.querySelector("#session-facts"), |
| 953 | rename: document.querySelector("#rename-thread"), |
| 954 | archive: document.querySelector("#archive-thread"), |
| 955 | status: document.querySelector("#status-banner"), |
| 956 | transcript: document.querySelector("#transcript"), |
| 957 | attention: document.querySelector("#attention"), |
| 958 | composer: document.querySelector("#composer"), |
| 959 | composerInput: document.querySelector("#composer-input"), |
| 960 | send: document.querySelector("#send-message"), |
| 961 | interrupt: document.querySelector("#interrupt-turn"), |
| 962 | renameDialog: document.querySelector("#rename-dialog"), |
| 963 | renameForm: document.querySelector("#rename-form"), |
| 964 | renameInput: document.querySelector("#rename-input"), |
| 965 | peek: document.querySelector("#session-peek"), |
| 966 | savedSessions: document.querySelector("#saved-sessions"), |
| 967 | sessionList: document.querySelector("#session-list"), |
| 968 | session: document.querySelector(".session"), |
| 969 | }; |
| 970 | |
| 971 | const composerDefaultPlaceholder = dom.composerInput.getAttribute("placeholder") || ""; |
| 972 | |
| 973 | const app = { |
| 974 | summaries: [], |
| 975 | sessionSummaries: [], |
| 976 | // Typed selection: `none`, a read-only `session`, or a live `thread`. |
| 977 | // Every reply/approval authority check reads this, not a loose id. |
| 978 | target: NO_TARGET, |
| 979 | // Bounded, redacted peek for the selected saved session, or null. |
| 980 | peek: null, |
| 981 | peekEntries: PEEK_DEFAULT_ENTRIES, |
| 982 | // Set when the SSE stream reported a sequence gap and a re-snapshot is |
| 983 | // pending. Surfaced in the connection label rather than hidden. |
| 984 | streamGap: false, |
| 985 | selectedThreadId: "", |
| 986 | threadState: createThreadState(), |
| 987 | workspace: null, |
| 988 | runtimeInfo: null, |
| 989 | drafts: new Map(), |
| 990 | stream: null, |
| 991 | streamOpenCancel: null, |
| 992 | reconnectTimer: null, |
| 993 | generation: 0, |
| 994 | searchTimer: null, |
| 995 | railReturnFocus: null, |
| 996 | inFlightActions: new Set(), |
| 997 | providerCatalog: null, |
| 998 | newThreadModels: [], |
| 999 | newThreadGeneration: 0, |
| 1000 | newThreadLoading: false, |
| 1001 | creatingThread: false, |
| 1002 | }; |
| 1003 | |
| 1004 | const narrowRail = globalThis.matchMedia("(max-width: 800px)"); |
| 1005 | const composerSendAction = "composer-send"; |
| 1006 | |
| 1007 | function element(tag, className, text) { |
| 1008 | const created = document.createElement(tag); |
| 1009 | if (className) created.className = className; |
| 1010 | if (text != null) setSafeText(created, text); |
| 1011 | return created; |
| 1012 | } |
| 1013 | |
| 1014 | function setInert(element, inert) { |
| 1015 | element.inert = inert; |
| 1016 | if (inert) element.setAttribute("inert", ""); |
| 1017 | else element.removeAttribute("inert"); |
| 1018 | } |
| 1019 | |
| 1020 | function applyDesktopRailAccessibility() { |
| 1021 | dom.shell.classList.remove("rail-visible"); |
| 1022 | dom.rail.removeAttribute("aria-hidden"); |
| 1023 | dom.rail.removeAttribute("aria-modal"); |
| 1024 | dom.rail.removeAttribute("role"); |
| 1025 | dom.session.removeAttribute("aria-hidden"); |
| 1026 | setInert(dom.rail, false); |
| 1027 | setInert(dom.session, false); |
| 1028 | dom.railScrim.hidden = true; |
| 1029 | dom.railOpen.setAttribute("aria-expanded", "false"); |
| 1030 | app.railReturnFocus = null; |
| 1031 | } |
| 1032 | |
| 1033 | function applyClosedMobileRailAccessibility() { |
| 1034 | dom.shell.classList.remove("rail-visible"); |
| 1035 | dom.session.removeAttribute("aria-hidden"); |
| 1036 | setInert(dom.session, false); |
| 1037 | dom.rail.setAttribute("role", "dialog"); |
| 1038 | dom.rail.setAttribute("aria-modal", "true"); |
| 1039 | dom.rail.setAttribute("aria-hidden", "true"); |
| 1040 | setInert(dom.rail, true); |
| 1041 | dom.railScrim.hidden = true; |
| 1042 | dom.railOpen.setAttribute("aria-expanded", "false"); |
| 1043 | } |
| 1044 | |
| 1045 | function openRail() { |
| 1046 | if (!narrowRail.matches) return; |
| 1047 | app.railReturnFocus = document.activeElement; |
| 1048 | dom.rail.setAttribute("role", "dialog"); |
| 1049 | dom.rail.setAttribute("aria-modal", "true"); |
| 1050 | dom.rail.setAttribute("aria-hidden", "false"); |
| 1051 | setInert(dom.rail, false); |
| 1052 | dom.railScrim.hidden = false; |
| 1053 | dom.shell.classList.add("rail-visible"); |
| 1054 | dom.railOpen.setAttribute("aria-expanded", "true"); |
| 1055 | dom.railClose.focus({ preventScroll: true }); |
| 1056 | dom.session.setAttribute("aria-hidden", "true"); |
| 1057 | setInert(dom.session, true); |
| 1058 | } |
| 1059 | |
| 1060 | function closeRail({ restoreFocus = true } = {}) { |
| 1061 | if (!narrowRail.matches) { |
| 1062 | applyDesktopRailAccessibility(); |
| 1063 | return; |
| 1064 | } |
| 1065 | dom.session.removeAttribute("aria-hidden"); |
| 1066 | setInert(dom.session, false); |
| 1067 | const returnTarget = app.railReturnFocus?.isConnected |
| 1068 | ? app.railReturnFocus |
| 1069 | : dom.railOpen; |
| 1070 | if (restoreFocus) returnTarget.focus({ preventScroll: true }); |
| 1071 | applyClosedMobileRailAccessibility(); |
| 1072 | app.railReturnFocus = null; |
| 1073 | } |
| 1074 | |
| 1075 | function syncRailAccessibility() { |
| 1076 | if (!narrowRail.matches) { |
| 1077 | applyDesktopRailAccessibility(); |
| 1078 | return; |
| 1079 | } |
| 1080 | if (dom.shell.classList.contains("rail-visible")) { |
| 1081 | dom.rail.setAttribute("role", "dialog"); |
| 1082 | dom.rail.setAttribute("aria-modal", "true"); |
| 1083 | dom.rail.setAttribute("aria-hidden", "false"); |
| 1084 | setInert(dom.rail, false); |
| 1085 | dom.session.setAttribute("aria-hidden", "true"); |
| 1086 | setInert(dom.session, true); |
| 1087 | dom.railScrim.hidden = false; |
| 1088 | dom.railOpen.setAttribute("aria-expanded", "true"); |
| 1089 | return; |
| 1090 | } |
| 1091 | if (dom.rail.contains(document.activeElement)) { |
| 1092 | dom.railOpen.focus({ preventScroll: true }); |
| 1093 | } |
| 1094 | applyClosedMobileRailAccessibility(); |
| 1095 | } |
| 1096 | |
| 1097 | function syncVisualViewport() { |
| 1098 | const viewport = globalThis.visualViewport; |
| 1099 | const height = viewport?.height || globalThis.innerHeight; |
| 1100 | const offsetTop = viewport?.offsetTop || 0; |
| 1101 | if (Number.isFinite(height) && height > 0) { |
| 1102 | dom.shell.style.setProperty("--visual-viewport-height", `${Math.round(height)}px`); |
| 1103 | } |
| 1104 | dom.shell.style.setProperty("--visual-viewport-offset-top", `${Math.max(0, Math.round(offsetTop))}px`); |
| 1105 | } |
| 1106 | |
| 1107 | function focusableWithin(container) { |
| 1108 | return [...container.querySelectorAll( |
| 1109 | 'button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])', |
| 1110 | )].filter((node) => !node.closest("[hidden]") && node.getAttribute("aria-hidden") !== "true"); |
| 1111 | } |
| 1112 | |
| 1113 | function trapFocusWithin(event, container) { |
| 1114 | if (event.key !== "Tab") return false; |
| 1115 | const focusable = focusableWithin(container); |
| 1116 | if (focusable.length === 0) { |
| 1117 | event.preventDefault(); |
| 1118 | container.focus({ preventScroll: true }); |
| 1119 | return true; |
| 1120 | } |
| 1121 | const first = focusable[0]; |
| 1122 | const last = focusable.at(-1); |
| 1123 | const active = document.activeElement; |
| 1124 | if (event.shiftKey && (active === first || !container.contains(active))) { |
| 1125 | event.preventDefault(); |
| 1126 | last.focus({ preventScroll: true }); |
| 1127 | return true; |
| 1128 | } |
| 1129 | if (!event.shiftKey && (active === last || !container.contains(active))) { |
| 1130 | event.preventDefault(); |
| 1131 | first.focus({ preventScroll: true }); |
| 1132 | return true; |
| 1133 | } |
| 1134 | return false; |
| 1135 | } |
| 1136 | |
| 1137 | function trapRailFocus(event) { |
| 1138 | if ( |
| 1139 | event.key !== "Tab" |
| 1140 | || !narrowRail.matches |
| 1141 | || !dom.shell.classList.contains("rail-visible") |
| 1142 | ) return false; |
| 1143 | return trapFocusWithin(event, dom.rail); |
| 1144 | } |
| 1145 | |
| 1146 | function setConnection(kind, message) { |
| 1147 | dom.connectionDot.className = `connection-dot ${kind || ""}`.trim(); |
| 1148 | setSafeText(dom.connectionLabel, message); |
| 1149 | } |
| 1150 | |
| 1151 | function showStatus(message) { |
| 1152 | setSafeText(dom.status, message || ""); |
| 1153 | dom.status.hidden = !message; |
| 1154 | } |
| 1155 | |
| 1156 | const sessionFetch = createWebSessionFetch({ |
| 1157 | location: window.location, |
| 1158 | history: window.history, |
| 1159 | storage: () => window.sessionStorage, |
| 1160 | fetch: (...args) => fetch(...args), |
| 1161 | }); |
| 1162 | |
| 1163 | async function api(path, options = {}) { |
| 1164 | const response = await sessionFetch(path, options); |
| 1165 | if (!response.ok) { |
| 1166 | let message = `${response.status} ${response.statusText}`.trim(); |
| 1167 | try { |
| 1168 | const body = await response.json(); |
| 1169 | message = body?.error?.message || body?.message || message; |
| 1170 | } catch (_error) { |
| 1171 | // The status line is enough when the response is not JSON. |
| 1172 | } |
| 1173 | if (response.status === 401) { |
| 1174 | message = "This browser session is not authenticated. Restart `codewhale web` to open a fresh one-time session."; |
| 1175 | } |
| 1176 | throw Object.assign(new Error(message), { status: response.status }); |
| 1177 | } |
| 1178 | if (response.status === 204) return null; |
| 1179 | const contentType = response.headers.get("content-type") || ""; |
| 1180 | return contentType.includes("application/json") ? response.json() : response.text(); |
| 1181 | } |
| 1182 | |
| 1183 | function renderThreadList() { |
| 1184 | dom.threadList.replaceChildren(); |
| 1185 | if (app.summaries.length === 0) { |
| 1186 | if (showNoMatchingThreads(app.summaries, app.sessionSummaries)) { |
| 1187 | const empty = element("p", "thread-preview", "No matching threads"); |
| 1188 | empty.style.padding = "8px 10px"; |
| 1189 | dom.threadList.append(empty); |
| 1190 | } |
| 1191 | return; |
| 1192 | } |
| 1193 | |
| 1194 | const groups = groupThreadSummaries(app.summaries); |
| 1195 | if (groups.needsYou.length > 0) { |
| 1196 | appendThreadGroup("Needs you", "needs-you", groups.needsYou); |
| 1197 | } |
| 1198 | if (groups.recent.length > 0) { |
| 1199 | appendThreadGroup("Recent", "recent", groups.recent); |
| 1200 | } |
| 1201 | } |
| 1202 | |
| 1203 | function appendThreadGroup(label, idSuffix, summaries) { |
| 1204 | const group = element("section", `thread-group thread-group-${idSuffix}`); |
| 1205 | const headingId = `thread-group-${idSuffix}-title`; |
| 1206 | const heading = element("h2", "rail-section-title thread-group-title", label); |
| 1207 | heading.id = headingId; |
| 1208 | group.setAttribute("aria-labelledby", headingId); |
| 1209 | group.append(heading); |
| 1210 | |
| 1211 | for (const summary of summaries) { |
| 1212 | const row = element("button", "thread-row"); |
| 1213 | row.type = "button"; |
| 1214 | row.dataset.threadId = summary.id; |
| 1215 | row.setAttribute("aria-current", summary.id === app.selectedThreadId ? "true" : "false"); |
| 1216 | const titleRow = element("span", "thread-title-row"); |
| 1217 | titleRow.append(element("span", "thread-title", summary.title || "New thread")); |
| 1218 | const indicators = element("span", "thread-row-indicators"); |
| 1219 | const attentionCount = pendingAttentionCount(summary); |
| 1220 | if (attentionCount > 0) { |
| 1221 | const attention = element("span", "thread-attention-count", String(attentionCount)); |
| 1222 | attention.setAttribute("aria-label", pendingAttentionLabel(summary)); |
| 1223 | indicators.append(attention); |
| 1224 | } |
| 1225 | const status = element("span", `status-pip ${summary.latest_turn_status === "inprogress" || summary.latest_turn_status === "in_progress" ? "running" : summary.latest_turn_status === "failed" ? "failed" : ""}`); |
| 1226 | status.setAttribute("aria-label", summary.latest_turn_status || "idle"); |
| 1227 | indicators.append(status); |
| 1228 | titleRow.append(indicators); |
| 1229 | row.append(titleRow); |
| 1230 | row.append(element("span", "thread-preview", summary.preview || "No messages yet")); |
| 1231 | const branch = summary.branch || basename(summary.workspace) || "local"; |
| 1232 | row.append(element("span", "thread-meta", `${branch} · ${relativeTime(summary.updated_at)}`)); |
| 1233 | row.addEventListener("click", () => selectThread(summary.id)); |
| 1234 | group.append(row); |
| 1235 | } |
| 1236 | dom.threadList.append(group); |
| 1237 | } |
| 1238 | |
| 1239 | async function loadThreads(search = dom.search.value.trim()) { |
| 1240 | const query = new URLSearchParams({ limit: "100" }); |
| 1241 | if (search) query.set("search", search); |
| 1242 | app.summaries = await api(`/v1/threads/summary?${query.toString()}`); |
| 1243 | renderThreadList(); |
| 1244 | return app.summaries; |
| 1245 | } |
| 1246 | |
| 1247 | // Saved sessions are the durable session store the terminal browses. They |
| 1248 | // are rendered with the same row shape as threads because |
| 1249 | // /v1/sessions/summary and /v1/threads/summary are field-compatible |
| 1250 | // projections — one vocabulary, not two. |
| 1251 | function renderSessionList() { |
| 1252 | dom.sessionList.replaceChildren(); |
| 1253 | // The section only exists when the backend actually returned sessions; |
| 1254 | // an affordance for an empty store would imply a capability that has |
| 1255 | // nothing behind it. |
| 1256 | dom.savedSessions.hidden = app.sessionSummaries.length === 0; |
| 1257 | if (app.sessionSummaries.length === 0) return; |
| 1258 | |
| 1259 | for (const summary of app.sessionSummaries) { |
| 1260 | const row = element("button", "thread-row"); |
| 1261 | row.type = "button"; |
| 1262 | row.dataset.sessionId = summary.id; |
| 1263 | const titleRow = element("span", "thread-title-row"); |
| 1264 | titleRow.append(element("span", "thread-title", summary.title || "Untitled session")); |
| 1265 | row.append(titleRow); |
| 1266 | row.append(element("span", "thread-preview", summary.preview || summary.title)); |
| 1267 | const scope = basename(summary.workspace) || "local"; |
| 1268 | row.append( |
| 1269 | element( |
| 1270 | "span", |
| 1271 | "thread-meta", |
| 1272 | `${scope} · ${summary.message_count} msg · ${relativeTime(summary.updated_at)}`, |
| 1273 | ), |
| 1274 | ); |
| 1275 | row.setAttribute( |
| 1276 | "aria-current", |
| 1277 | app.target.kind === "session" && app.target.sessionId === summary.id ? "true" : "false", |
| 1278 | ); |
| 1279 | // Click peeks; resuming is a separate, explicit button inside the peek. |
| 1280 | row.addEventListener("click", () => peekSession(summary.id)); |
| 1281 | dom.sessionList.append(row); |
| 1282 | } |
| 1283 | } |
| 1284 | |
| 1285 | async function loadSessions(search = dom.search.value.trim()) { |
| 1286 | const query = new URLSearchParams({ limit: "50" }); |
| 1287 | if (search) query.set("search", search); |
| 1288 | try { |
| 1289 | app.sessionSummaries = await api(`/v1/sessions/summary?${query.toString()}`); |
| 1290 | } catch (_error) { |
| 1291 | // A runtime without a readable session store is not a broken dashboard; |
| 1292 | // hide the section rather than blocking the thread view behind an error. |
| 1293 | app.sessionSummaries = []; |
| 1294 | } |
| 1295 | renderThreadList(); |
| 1296 | renderSessionList(); |
| 1297 | return app.sessionSummaries; |
| 1298 | } |
| 1299 | |
| 1300 | // Resume goes through the existing endpoint, which seeds a real thread from |
| 1301 | // the saved messages. The dashboard does not reconstruct history itself. |
| 1302 | // Selecting a saved session shows a read-only peek. It does NOT resume: |
| 1303 | // resuming spawns a real thread and an engine, which must be a deliberate |
| 1304 | // act, not a side effect of clicking a row to see what it was about. |
| 1305 | async function peekSession(sessionId, entries = PEEK_DEFAULT_ENTRIES) { |
| 1306 | stopStream(); |
| 1307 | app.peekEntries = entries; |
| 1308 | app.selectedThreadId = ""; |
| 1309 | app.threadState = createThreadState(); |
| 1310 | app.target = sessionTarget(sessionId); |
| 1311 | showStatus(""); |
| 1312 | renderThreadList(); |
| 1313 | renderSessionList(); |
| 1314 | try { |
| 1315 | // `?peek=true` returns a bounded, redacted projection — twelve entries, |
| 1316 | // tool payloads summarised — so the browser never receives the full |
| 1317 | // transcript in order to display a preview of it. |
| 1318 | app.peek = await api( |
| 1319 | `/v1/sessions/${encodeURIComponent(sessionId)}?peek=true&entries=${entries}`, |
| 1320 | ); |
| 1321 | } catch (error) { |
| 1322 | app.peek = null; |
| 1323 | showStatus(error.message); |
| 1324 | } |
| 1325 | renderAll(); |
| 1326 | } |
| 1327 | |
| 1328 | async function resumeSession(sessionId) { |
| 1329 | showStatus(""); |
| 1330 | try { |
| 1331 | const resumed = await api(`/v1/sessions/${encodeURIComponent(sessionId)}/resume-thread`, { |
| 1332 | method: "POST", |
| 1333 | body: "{}", |
| 1334 | }); |
| 1335 | app.peek = null; |
| 1336 | await loadThreads(""); |
| 1337 | // `selectThread` sets the live thread target; only after this can the |
| 1338 | // composer or an approval act. |
| 1339 | await selectThread(resumed.thread_id); |
| 1340 | showStatus(resumed.summary || ""); |
| 1341 | } catch (error) { |
| 1342 | showStatus(error.message); |
| 1343 | } |
| 1344 | } |
| 1345 | |
| 1346 | // Render the read-only peek pane for a selected saved session. |
| 1347 | function renderPeek() { |
| 1348 | if (!dom.peek) return; |
| 1349 | const showing = app.target.kind === "session" && app.peek; |
| 1350 | dom.peek.hidden = !showing; |
| 1351 | if (!showing) { |
| 1352 | dom.peek.replaceChildren(); |
| 1353 | return; |
| 1354 | } |
| 1355 | const peek = app.peek; |
| 1356 | dom.peek.replaceChildren(); |
| 1357 | |
| 1358 | const header = element("div", "peek-header"); |
| 1359 | header.append(element("p", "eyebrow", "Saved session — read only")); |
| 1360 | header.append(element("h2", "", peek.title || "Untitled session")); |
| 1361 | header.append( |
| 1362 | element( |
| 1363 | "p", |
| 1364 | "thread-meta", |
| 1365 | `${basename(peek.workspace) || "local"} · ${peek.message_count} messages · ${relativeTime(peek.updated_at)}${peek.archived ? " · archived" : ""}`, |
| 1366 | ), |
| 1367 | ); |
| 1368 | header.append(element("p", "peek-notice", savedSessionNotice())); |
| 1369 | const resume = element("button", "primary-button", "Resume into a live thread"); |
| 1370 | resume.type = "button"; |
| 1371 | resume.addEventListener("click", () => resumeSession(peek.session_id)); |
| 1372 | header.append(resume); |
| 1373 | dom.peek.append(header); |
| 1374 | |
| 1375 | const omittedLabel = peekOmittedLabel(peek); |
| 1376 | if (omittedLabel) { |
| 1377 | const omitted = element("div", "peek-omitted-row"); |
| 1378 | omitted.append(element("span", "peek-omitted", omittedLabel)); |
| 1379 | if (peekCanShowEarlier(peek, app.peekEntries)) { |
| 1380 | const more = element("button", "quiet-button", "Show earlier messages"); |
| 1381 | more.type = "button"; |
| 1382 | more.addEventListener("click", () => peekSession(peek.session_id, PEEK_EXPANDED_ENTRIES)); |
| 1383 | omitted.append(more); |
| 1384 | } |
| 1385 | dom.peek.append(omitted); |
| 1386 | } |
| 1387 | |
| 1388 | for (const entry of peek.entries || []) { |
| 1389 | const row = element("div", `peek-entry peek-${entry.kind}`); |
| 1390 | if (entry.kind !== "tool") { |
| 1391 | row.append(element("span", "peek-kind", entry.kind === "assistant" ? "Codewhale" : entry.kind === "user" ? "You" : entry.kind)); |
| 1392 | } |
| 1393 | // `element()` assigns via textContent. Peek text is recorded user/model |
| 1394 | // content and must never reach an HTML sink; this is the XSS boundary. |
| 1395 | row.append(element("p", "peek-text", entry.text)); |
| 1396 | if (entry.redacted) row.append(element("span", "peek-flag", "redacted")); |
| 1397 | if (entry.truncated) row.append(element("span", "peek-flag", "truncated")); |
| 1398 | dom.peek.append(row); |
| 1399 | } |
| 1400 | } |
| 1401 | |
| 1402 | const { connectStream, stopStream } = createStreamConnector({ |
| 1403 | app, api, EventSource, setConnection, showStatus, |
| 1404 | receive: (stream, message, threadId, generation) => { |
| 1405 | try { |
| 1406 | const envelope = JSON.parse(message.data); |
| 1407 | if (runtimeEventContinuity(app.threadState, envelope) === "gap") { |
| 1408 | app.streamGap = true; |
| 1409 | renderStreamCursor(); |
| 1410 | showStatus("Runtime event continuity changed; refreshing the thread snapshot…"); |
| 1411 | void recoverProjection(threadId, generation, stream); |
| 1412 | return; |
| 1413 | } |
| 1414 | if (!applyRuntimeEvent(app.threadState, envelope)) return; |
| 1415 | renderAll(true); |
| 1416 | if ( |
| 1417 | envelope.event === "turn.completed" |
| 1418 | || envelope.event === "thread.updated" |
| 1419 | || envelope.event === "approval.required" |
| 1420 | || envelope.event === "approval.decided" |
| 1421 | || envelope.event === "approval.timeout" |
| 1422 | || envelope.event === "user_input.required" |
| 1423 | || envelope.event === "user_input.answered" |
| 1424 | || envelope.event === "user_input.canceled" |
| 1425 | ) { |
| 1426 | loadThreads().catch((error) => showStatus(error.message)); |
| 1427 | } |
| 1428 | } catch (error) { |
| 1429 | showStatus(`Could not read a Runtime event: ${error.message}`); |
| 1430 | } |
| 1431 | }, |
| 1432 | }); |
| 1433 | |
| 1434 | async function selectThread(threadId) { |
| 1435 | if (!threadId) return; |
| 1436 | saveDraft(app.drafts, app.selectedThreadId, dom.composerInput.value); |
| 1437 | stopStream(); |
| 1438 | app.selectedThreadId = threadId; |
| 1439 | // A live thread is now the target: from here the composer and approvals |
| 1440 | // may act. Clear any saved-session peek so the two surfaces are exclusive. |
| 1441 | app.target = threadTarget(threadId); |
| 1442 | app.peek = null; |
| 1443 | app.streamGap = false; |
| 1444 | app.threadState = createThreadState(threadId); |
| 1445 | app.generation += 1; |
| 1446 | const generation = app.generation; |
| 1447 | dom.composerInput.value = restoreDraft(app.drafts, threadId); |
| 1448 | resizeComposer(); |
| 1449 | renderThreadList(); |
| 1450 | renderSessionList(); |
| 1451 | renderAll(); |
| 1452 | closeRailIfNarrow(); |
| 1453 | setConnection("", "Loading thread snapshot…"); |
| 1454 | showStatus(""); |
| 1455 | |
| 1456 | try { |
| 1457 | const subscribed = await snapshotThenSubscribe({ |
| 1458 | state: app.threadState, |
| 1459 | threadId, |
| 1460 | loadSnapshot: (id) => api(`/v1/threads/${encodeURIComponent(id)}`), |
| 1461 | subscribe: (id, sequence) => { |
| 1462 | return connectStream(id, sequence, generation); |
| 1463 | }, |
| 1464 | isCurrent: () => generation === app.generation && threadId === app.selectedThreadId, |
| 1465 | }); |
| 1466 | if (!subscribed) return; |
| 1467 | renderAll(); |
| 1468 | setConnection("ready", "Local runtime connected"); |
| 1469 | } catch (error) { |
| 1470 | if (generation !== app.generation) return; |
| 1471 | showStatus(error.message); |
| 1472 | setConnection("error", "Runtime connection failed"); |
| 1473 | } |
| 1474 | } |
| 1475 | |
| 1476 | async function recoverProjection(threadId, generation, sourceStream = null) { |
| 1477 | if ( |
| 1478 | generation !== app.generation |
| 1479 | || threadId !== app.selectedThreadId |
| 1480 | || (sourceStream && app.stream !== sourceStream) |
| 1481 | ) return; |
| 1482 | |
| 1483 | stopStream(); |
| 1484 | setConnection("", "Refreshing thread snapshot…"); |
| 1485 | |
| 1486 | try { |
| 1487 | const subscribed = await recoverSnapshotAndSubscribe({ |
| 1488 | state: app.threadState, |
| 1489 | threadId, |
| 1490 | loadSnapshot: (id) => api(`/v1/threads/${encodeURIComponent(id)}`), |
| 1491 | subscribe: (id, sequence) => connectStream(id, sequence, generation, true), |
| 1492 | isCurrent: () => generation === app.generation && threadId === app.selectedThreadId, |
| 1493 | }, () => { |
| 1494 | // A gap is continuous again only after both the replacement snapshot |
| 1495 | // and the replacement EventSource open handshake have succeeded. |
| 1496 | app.streamGap = false; |
| 1497 | }); |
| 1498 | if (!subscribed) return; |
| 1499 | renderAll(); |
| 1500 | showStatus(""); |
| 1501 | setConnection("ready", "Local runtime connected"); |
| 1502 | } catch (error) { |
| 1503 | if (generation !== app.generation || threadId !== app.selectedThreadId) return; |
| 1504 | showStatus(`Could not refresh the thread snapshot: ${error.message}`); |
| 1505 | setConnection("error", "Runtime recovery failed"); |
| 1506 | if (error.status !== 401 && error.status !== 403) { |
| 1507 | app.reconnectTimer = setTimeout( |
| 1508 | () => recoverProjection(threadId, generation), |
| 1509 | 900, |
| 1510 | ); |
| 1511 | } |
| 1512 | } |
| 1513 | } |
| 1514 | |
| 1515 | function renderAll(preserveScroll = false) { |
| 1516 | renderHeader(); |
| 1517 | renderPeek(); |
| 1518 | renderTranscript(preserveScroll); |
| 1519 | renderAttention(); |
| 1520 | renderComposer(); |
| 1521 | renderStreamCursor(); |
| 1522 | } |
| 1523 | |
| 1524 | // Show the SSE resume cursor so "am I reading everything?" is answerable. |
| 1525 | function renderStreamCursor() { |
| 1526 | if (app.target.kind !== "thread") return; |
| 1527 | const cursor = streamCursor(app.threadState, { |
| 1528 | gap: app.streamGap, |
| 1529 | connected: Boolean(app.stream), |
| 1530 | }); |
| 1531 | setConnection(cursor.gap ? "error" : cursor.connected ? "ready" : "", cursor.label); |
| 1532 | } |
| 1533 | |
| 1534 | function renderHeader() { |
| 1535 | const thread = app.threadState.thread; |
| 1536 | const summary = app.summaries.find((item) => item.id === app.selectedThreadId); |
| 1537 | const title = headerTitleFor({ thread, summary, target: app.target, peek: app.peek }); |
| 1538 | setSafeText(dom.title, title); |
| 1539 | setSafeText( |
| 1540 | dom.kicker, |
| 1541 | thread ? "Local Runtime thread" : app.target.kind === "session" ? "Saved session" : "Local Runtime", |
| 1542 | ); |
| 1543 | dom.rename.disabled = !thread; |
| 1544 | dom.archive.disabled = !thread; |
| 1545 | dom.facts.replaceChildren(); |
| 1546 | if (!thread) return; |
| 1547 | |
| 1548 | const workspace = summary?.workspace || thread.workspace || app.workspace?.workspace; |
| 1549 | const branch = summary?.branch || app.workspace?.branch; |
| 1550 | dom.facts.append(factChip("Workspace", basename(workspace) || "local")); |
| 1551 | if (branch) dom.facts.append(factChip("Branch", branch)); |
| 1552 | const provider = threadProviderLabel(thread); |
| 1553 | if (provider) dom.facts.append(factChip("Provider", provider)); |
| 1554 | dom.facts.append(factChip("Model", thread.model || "Runtime default")); |
| 1555 | dom.facts.append(factChip("Mode", modeLabel(thread.mode))); |
| 1556 | dom.facts.append(factChip("Permission", permissionLabel(thread))); |
| 1557 | } |
| 1558 | |
| 1559 | function factChip(label, value) { |
| 1560 | const chip = element("span", "fact-chip"); |
| 1561 | chip.dataset.fact = String(label || "").toLowerCase(); |
| 1562 | chip.append(element("span", "", label)); |
| 1563 | chip.append(element("strong", "", value)); |
| 1564 | return chip; |
| 1565 | } |
| 1566 | |
| 1567 | function renderTranscript(preserveScroll) { |
| 1568 | const wasNearBottom = dom.transcript.scrollHeight - dom.transcript.scrollTop - dom.transcript.clientHeight < 120; |
| 1569 | if (!app.threadState.thread) { |
| 1570 | renderTranscriptEmpty( |
| 1571 | "choose-thread", |
| 1572 | "Your local agent, in the browser.", |
| 1573 | "Create a thread or choose one from the rail. This client uses the same Runtime as the terminal.", |
| 1574 | ); |
| 1575 | return; |
| 1576 | } |
| 1577 | if (app.threadState.itemOrder.length === 0) { |
| 1578 | renderTranscriptEmpty( |
| 1579 | "ready", |
| 1580 | "Ready for a task.", |
| 1581 | "Send a message below. Model, mode, and permission posture come from the Runtime and are shown read-only above.", |
| 1582 | ); |
| 1583 | return; |
| 1584 | } |
| 1585 | |
| 1586 | const selection = captureTranscriptSelection(); |
| 1587 | const existing = new Map( |
| 1588 | [...dom.transcript.children] |
| 1589 | .filter((node) => node.dataset.itemId) |
| 1590 | .map((node) => [node.dataset.itemId, node]), |
| 1591 | ); |
| 1592 | const desired = []; |
| 1593 | for (const itemId of app.threadState.itemOrder) { |
| 1594 | const item = app.threadState.items.get(itemId); |
| 1595 | if (!item) continue; |
| 1596 | let node = existing.get(itemId); |
| 1597 | if (!node || !updateItemNode(node, item)) node = renderItem(item); |
| 1598 | desired.push(node); |
| 1599 | } |
| 1600 | reconcileChildren(dom.transcript, desired); |
| 1601 | restoreTranscriptSelection(selection); |
| 1602 | if (!preserveScroll || wasNearBottom) { |
| 1603 | requestAnimationFrame(() => { |
| 1604 | dom.transcript.scrollTop = dom.transcript.scrollHeight; |
| 1605 | }); |
| 1606 | } |
| 1607 | } |
| 1608 | |
| 1609 | function renderTranscriptEmpty(kind, title, description) { |
| 1610 | const current = dom.transcript.children.length === 1 |
| 1611 | ? dom.transcript.firstElementChild |
| 1612 | : null; |
| 1613 | if (current?.dataset.emptyState === kind) return; |
| 1614 | const empty = emptyState(title, description); |
| 1615 | empty.dataset.emptyState = kind; |
| 1616 | reconcileChildren(dom.transcript, [empty]); |
| 1617 | } |
| 1618 | |
| 1619 | function reconcileChildren(container, desired) { |
| 1620 | const keep = new Set(desired); |
| 1621 | let cursor = container.firstElementChild; |
| 1622 | for (const node of desired) { |
| 1623 | if (node === cursor) { |
| 1624 | cursor = cursor.nextElementSibling; |
| 1625 | } else { |
| 1626 | container.insertBefore(node, cursor); |
| 1627 | } |
| 1628 | } |
| 1629 | for (const child of [...container.children]) { |
| 1630 | if (!keep.has(child)) child.remove(); |
| 1631 | } |
| 1632 | } |
| 1633 | |
| 1634 | function emptyState(title, description) { |
| 1635 | const empty = element("div", "empty-state"); |
| 1636 | const mark = document.createElement("img"); |
| 1637 | mark.className = "empty-mark"; |
| 1638 | mark.src = "/assets/codewhale-192.png"; |
| 1639 | mark.alt = ""; |
| 1640 | empty.append(mark); |
| 1641 | empty.append(element("h2", "", title)); |
| 1642 | empty.append(element("p", "", description)); |
| 1643 | return empty; |
| 1644 | } |
| 1645 | |
| 1646 | function renderItem(item) { |
| 1647 | let card; |
| 1648 | if (item.kind === "user_message" || item.kind === "agent_message") { |
| 1649 | const role = item.kind === "user_message" ? "user" : "agent"; |
| 1650 | card = element("article", `message ${role}`); |
| 1651 | const label = element("div", "message-label"); |
| 1652 | label.dataset.itemPart = "label"; |
| 1653 | const body = element("div", "message-body"); |
| 1654 | body.dataset.itemPart = "body"; |
| 1655 | card.append(label, body); |
| 1656 | } else if (item.kind === "agent_reasoning") { |
| 1657 | card = element("article", "reasoning"); |
| 1658 | const disclosure = element("details"); |
| 1659 | const summary = element("summary"); |
| 1660 | summary.dataset.itemPart = "summary"; |
| 1661 | const detail = element("pre"); |
| 1662 | detail.dataset.itemPart = "detail"; |
| 1663 | disclosure.append(summary, detail); |
| 1664 | card.append(disclosure); |
| 1665 | } else { |
| 1666 | card = element("article", "receipt"); |
| 1667 | card.append(element("span", "receipt-dot")); |
| 1668 | const copy = element("span", "receipt-copy"); |
| 1669 | const label = element("strong"); |
| 1670 | label.dataset.itemPart = "label"; |
| 1671 | const summary = element("span", "receipt-summary"); |
| 1672 | summary.dataset.itemPart = "summary"; |
| 1673 | copy.append(label, summary); |
| 1674 | card.append(copy); |
| 1675 | } |
| 1676 | card.dataset.itemId = item.id; |
| 1677 | card.dataset.itemKind = item.kind; |
| 1678 | updateItemNode(card, item); |
| 1679 | return card; |
| 1680 | } |
| 1681 | |
| 1682 | function updateItemNode(card, item) { |
| 1683 | if (card.dataset.itemKind !== item.kind) return false; |
| 1684 | const detail = item.detail || item.summary || ""; |
| 1685 | if (item.kind === "user_message" || item.kind === "agent_message") { |
| 1686 | const role = item.kind === "user_message" ? "user" : "agent"; |
| 1687 | card.className = `message ${role} ${item.status === "in_progress" ? "in-progress" : ""}`.trim(); |
| 1688 | setTextIfChanged(card.querySelector('[data-item-part="label"]'), role === "user" ? "You" : "Codewhale"); |
| 1689 | setTextIfChanged(card.querySelector('[data-item-part="body"]'), detail); |
| 1690 | return true; |
| 1691 | } |
| 1692 | if (item.kind === "agent_reasoning") { |
| 1693 | setTextIfChanged( |
| 1694 | card.querySelector('[data-item-part="summary"]'), |
| 1695 | item.status === "in_progress" ? "Reasoning…" : "Reasoning", |
| 1696 | ); |
| 1697 | setTextIfChanged(card.querySelector('[data-item-part="detail"]'), detail); |
| 1698 | return true; |
| 1699 | } |
| 1700 | |
| 1701 | const presentation = receiptPresentation(item); |
| 1702 | card.className = `receipt ${presentation.failed ? "failed" : ""}`.trim(); |
| 1703 | setTextIfChanged(card.querySelector('[data-item-part="label"]'), presentation.label); |
| 1704 | setTextIfChanged(card.querySelector('[data-item-part="summary"]'), presentation.summary); |
| 1705 | const copy = card.querySelector(".receipt-copy"); |
| 1706 | let disclosure = copy.querySelector("details"); |
| 1707 | if (presentation.raw && presentation.raw !== presentation.summary) { |
| 1708 | if (!disclosure) { |
| 1709 | disclosure = element("details"); |
| 1710 | const summary = element("summary", "", "Show receipt"); |
| 1711 | const raw = element("pre"); |
| 1712 | raw.dataset.itemPart = "raw"; |
| 1713 | disclosure.append(summary, raw); |
| 1714 | copy.append(disclosure); |
| 1715 | } |
| 1716 | setTextIfChanged(disclosure.querySelector('[data-item-part="raw"]'), presentation.raw); |
| 1717 | } else if (disclosure) { |
| 1718 | disclosure.remove(); |
| 1719 | } |
| 1720 | return true; |
| 1721 | } |
| 1722 | |
| 1723 | function setTextIfChanged(target, value) { |
| 1724 | const next = value == null ? "" : String(value); |
| 1725 | if (target.textContent !== next) setSafeText(target, next); |
| 1726 | } |
| 1727 | |
| 1728 | function captureTranscriptSelection() { |
| 1729 | const selection = globalThis.getSelection?.(); |
| 1730 | if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null; |
| 1731 | const range = selection.getRangeAt(0); |
| 1732 | const start = transcriptSelectionEndpoint(range.startContainer, range.startOffset); |
| 1733 | const end = transcriptSelectionEndpoint(range.endContainer, range.endOffset); |
| 1734 | return start && end ? { start, end } : null; |
| 1735 | } |
| 1736 | |
| 1737 | function transcriptSelectionEndpoint(node, offset) { |
| 1738 | const elementNode = node.nodeType === 1 ? node : node.parentElement; |
| 1739 | const item = elementNode?.closest?.("[data-item-id]"); |
| 1740 | if (!item || !dom.transcript.contains(item)) return null; |
| 1741 | const prefix = document.createRange(); |
| 1742 | prefix.selectNodeContents(item); |
| 1743 | try { |
| 1744 | prefix.setEnd(node, offset); |
| 1745 | } catch (_error) { |
| 1746 | return null; |
| 1747 | } |
| 1748 | return { itemId: item.dataset.itemId, offset: prefix.toString().length }; |
| 1749 | } |
| 1750 | |
| 1751 | function restoreTranscriptSelection(captured) { |
| 1752 | if (!captured) return; |
| 1753 | const startRoot = [...dom.transcript.children] |
| 1754 | .find((node) => node.dataset.itemId === captured.start.itemId); |
| 1755 | const endRoot = [...dom.transcript.children] |
| 1756 | .find((node) => node.dataset.itemId === captured.end.itemId); |
| 1757 | if (!startRoot || !endRoot) return; |
| 1758 | const start = textPointAt(startRoot, captured.start.offset); |
| 1759 | const end = textPointAt(endRoot, captured.end.offset); |
| 1760 | if (!start || !end) return; |
| 1761 | const range = document.createRange(); |
| 1762 | try { |
| 1763 | range.setStart(start.node, start.offset); |
| 1764 | range.setEnd(end.node, end.offset); |
| 1765 | } catch (_error) { |
| 1766 | return; |
| 1767 | } |
| 1768 | const selection = globalThis.getSelection?.(); |
| 1769 | if (!selection) return; |
| 1770 | selection.removeAllRanges(); |
| 1771 | selection.addRange(range); |
| 1772 | } |
| 1773 | |
| 1774 | function textPointAt(root, requestedOffset) { |
| 1775 | const walker = document.createTreeWalker( |
| 1776 | root, |
| 1777 | globalThis.NodeFilter?.SHOW_TEXT || 4, |
| 1778 | ); |
| 1779 | let remaining = Math.max(0, requestedOffset); |
| 1780 | let last = null; |
| 1781 | for (let node = walker.nextNode(); node; node = walker.nextNode()) { |
| 1782 | last = node; |
| 1783 | const length = node.data.length; |
| 1784 | if (remaining <= length) return { node, offset: remaining }; |
| 1785 | remaining -= length; |
| 1786 | } |
| 1787 | return last ? { node: last, offset: last.data.length } : null; |
| 1788 | } |
| 1789 | |
| 1790 | function renderAttention() { |
| 1791 | const existing = new Map( |
| 1792 | [...dom.attention.children] |
| 1793 | .filter((node) => node.dataset.attentionKey) |
| 1794 | .map((node) => [node.dataset.attentionKey, node]), |
| 1795 | ); |
| 1796 | const desired = []; |
| 1797 | for (const [approvalId, approval] of app.threadState.approvals) { |
| 1798 | const key = `approval:${approvalId}`; |
| 1799 | const card = existing.get(key) || renderApproval(approvalId, approval); |
| 1800 | card.dataset.attentionKey = key; |
| 1801 | setAttentionCardBusyNode(card, app.inFlightActions.has(key)); |
| 1802 | desired.push(card); |
| 1803 | } |
| 1804 | for (const [inputId, input] of app.threadState.userInputs) { |
| 1805 | const key = `input:${inputId}`; |
| 1806 | const card = existing.get(key) || renderUserInput(inputId, input); |
| 1807 | card.dataset.attentionKey = key; |
| 1808 | setAttentionCardBusyNode(card, app.inFlightActions.has(key)); |
| 1809 | desired.push(card); |
| 1810 | } |
| 1811 | reconcileChildren(dom.attention, desired); |
| 1812 | dom.attention.hidden = desired.length === 0; |
| 1813 | } |
| 1814 | |
| 1815 | function setAttentionCardBusy(key, busy) { |
| 1816 | const card = [...dom.attention.children] |
| 1817 | .find((node) => node.dataset.attentionKey === key); |
| 1818 | if (card) setAttentionCardBusyNode(card, busy); |
| 1819 | } |
| 1820 | |
| 1821 | function setAttentionCardBusyNode(card, busy) { |
| 1822 | card.setAttribute("aria-busy", busy ? "true" : "false"); |
| 1823 | for (const control of card.querySelectorAll("button, input, textarea, select")) { |
| 1824 | control.disabled = busy; |
| 1825 | } |
| 1826 | } |
| 1827 | |
| 1828 | function renderApproval(approvalId, approval) { |
| 1829 | const card = element("article", "attention-card"); |
| 1830 | const titleId = `attention-approval-${safeDomId(approvalId)}`; |
| 1831 | card.setAttribute("role", "group"); |
| 1832 | card.setAttribute("aria-labelledby", titleId); |
| 1833 | card.append(element("p", "eyebrow", "Approval required")); |
| 1834 | const title = element("h2", "", approval.tool_name || "Tool request"); |
| 1835 | title.id = titleId; |
| 1836 | card.append(title); |
| 1837 | const copy = approvalCardCopy(approval); |
| 1838 | card.append(element("p", "approval-reason", copy.lead)); |
| 1839 | const actions = element("div", "attention-actions"); |
| 1840 | const rememberLabel = element("label", "remember-field"); |
| 1841 | const remember = document.createElement("input"); |
| 1842 | remember.type = "checkbox"; |
| 1843 | rememberLabel.append(remember, document.createTextNode("Remember for this thread")); |
| 1844 | const deny = element("button", "quiet-button danger", "Deny"); |
| 1845 | deny.type = "button"; |
| 1846 | deny.addEventListener("click", () => resolveApproval(approvalId, "deny", remember.checked)); |
| 1847 | const allow = element("button", "primary-button", "Allow"); |
| 1848 | allow.type = "button"; |
| 1849 | allow.addEventListener("click", () => resolveApproval(approvalId, "allow", remember.checked)); |
| 1850 | actions.append(rememberLabel, deny, allow); |
| 1851 | card.append(actions); |
| 1852 | const request = approvalRequestText(approval.input); |
| 1853 | if (request) card.append(element("pre", "approval-request", request)); |
| 1854 | if (approval.intent_summary) { |
| 1855 | card.append(element("p", "approval-claim", `The model says: ${approval.intent_summary}`)); |
| 1856 | } |
| 1857 | if (copy.detail) { |
| 1858 | const more = element("details", "approval-detail"); |
| 1859 | more.append(element("summary", "", "Tool instructions")); |
| 1860 | more.append(element("p", "", copy.detail)); |
| 1861 | card.append(more); |
| 1862 | } |
| 1863 | return card; |
| 1864 | } |
| 1865 | |
| 1866 | async function resolveApproval(approvalId, decision, remember) { |
| 1867 | // Authority check before authority action. The approval must belong to the |
| 1868 | // thread we are actually watching, and that thread must be the selected |
| 1869 | // live target — never a saved-session peek, never a row the user has since |
| 1870 | // moved off. Refusals are loud and send nothing. |
| 1871 | const resolved = resolveApprovalTarget(approvalId, app.target, app.threadState); |
| 1872 | if (!resolved.ok) { |
| 1873 | showStatus(refusalMessage(resolved.reason)); |
| 1874 | renderAttention(); |
| 1875 | return; |
| 1876 | } |
| 1877 | const action = `approval:${approvalId}`; |
| 1878 | if (!claimInFlight(app.inFlightActions, action)) return; |
| 1879 | setAttentionCardBusy(action, true); |
| 1880 | try { |
| 1881 | await api(`/v1/approvals/${encodeURIComponent(resolved.approvalId)}`, { |
| 1882 | method: "POST", |
| 1883 | body: JSON.stringify({ decision, remember, client: "web" }), |
| 1884 | }); |
| 1885 | app.threadState.approvals.delete(approvalId); |
| 1886 | showStatus(""); |
| 1887 | renderAttention(); |
| 1888 | } catch (error) { |
| 1889 | showStatus(error.message); |
| 1890 | } finally { |
| 1891 | app.inFlightActions.delete(action); |
| 1892 | setAttentionCardBusy(action, false); |
| 1893 | } |
| 1894 | } |
| 1895 | |
| 1896 | function renderUserInput(inputId, envelope) { |
| 1897 | const card = element("form", "attention-card"); |
| 1898 | const titleId = `attention-input-${safeDomId(inputId)}`; |
| 1899 | card.setAttribute("role", "group"); |
| 1900 | card.setAttribute("aria-labelledby", titleId); |
| 1901 | card.append(element("p", "eyebrow", "Input required")); |
| 1902 | const title = element("h2", "", "Codewhale has a question"); |
| 1903 | title.id = titleId; |
| 1904 | card.append(title); |
| 1905 | const questions = Array.isArray(envelope.request?.questions) ? envelope.request.questions : []; |
| 1906 | const groups = []; |
| 1907 | for (const question of questions) { |
| 1908 | const fieldset = element("fieldset", "question-fieldset"); |
| 1909 | fieldset.append(element("legend", "", question.question || question.header || "Choose an option")); |
| 1910 | const controls = []; |
| 1911 | for (const option of Array.isArray(question.options) ? question.options : []) { |
| 1912 | const label = element("label", "answer-option"); |
| 1913 | const input = document.createElement("input"); |
| 1914 | input.type = question.multi_select ? "checkbox" : "radio"; |
| 1915 | input.name = `question-${inputId}-${question.id}`; |
| 1916 | input.value = option.label || ""; |
| 1917 | label.append(input); |
| 1918 | const copy = element("span", "", option.label || "Option"); |
| 1919 | if (option.description) copy.append(element("small", "", option.description)); |
| 1920 | label.append(copy); |
| 1921 | fieldset.append(label); |
| 1922 | controls.push({ input, label: option.label || "", value: option.label || "" }); |
| 1923 | } |
| 1924 | // Match the terminal surface: a custom answer stays available even when |
| 1925 | // an older request omitted or disabled the legacy allow_free_text hint. |
| 1926 | const other = document.createElement("input"); |
| 1927 | other.className = "other-answer"; |
| 1928 | other.type = "text"; |
| 1929 | other.placeholder = "Other response"; |
| 1930 | other.setAttribute("aria-label", `${question.header || "Question"} other response`); |
| 1931 | if (!question.multi_select) { |
| 1932 | other.addEventListener("input", () => { |
| 1933 | if (other.value.trim()) { |
| 1934 | for (const control of controls) control.input.checked = false; |
| 1935 | } |
| 1936 | }); |
| 1937 | for (const control of controls) { |
| 1938 | control.input.addEventListener("change", () => { |
| 1939 | if (control.input.checked) other.value = ""; |
| 1940 | }); |
| 1941 | } |
| 1942 | } |
| 1943 | fieldset.append(other); |
| 1944 | card.append(fieldset); |
| 1945 | groups.push({ question, controls, other }); |
| 1946 | } |
| 1947 | const actions = element("div", "attention-actions"); |
| 1948 | const submit = element("button", "primary-button", "Submit answers"); |
| 1949 | submit.type = "submit"; |
| 1950 | actions.append(submit); |
| 1951 | card.append(actions); |
| 1952 | card.addEventListener("submit", async (event) => { |
| 1953 | event.preventDefault(); |
| 1954 | const selections = new Map(); |
| 1955 | const freeText = new Map(); |
| 1956 | for (const group of groups) { |
| 1957 | const selected = []; |
| 1958 | for (const control of group.controls) { |
| 1959 | if (control.input.checked) selected.push(control.value); |
| 1960 | } |
| 1961 | selections.set(group.question.id, selected); |
| 1962 | freeText.set(group.question.id, group.other.value); |
| 1963 | } |
| 1964 | const resolved = resolveUserInputTarget(inputId, app.target, app.threadState); |
| 1965 | if (!resolved.ok) { |
| 1966 | showStatus(refusalMessage(resolved.reason)); |
| 1967 | renderAttention(); |
| 1968 | return; |
| 1969 | } |
| 1970 | const built = answersForUserInput(envelope.request, selections, freeText); |
| 1971 | if (!built.ok) { |
| 1972 | const message = built.reason === "missing-answer" |
| 1973 | ? `Choose an answer for ${built.question}.` |
| 1974 | : built.reason === "multiple-answers" |
| 1975 | ? `Choose one answer for ${built.question}.` |
| 1976 | : `That question changed before it could be submitted — nothing was sent.`; |
| 1977 | showStatus(message); |
| 1978 | return; |
| 1979 | } |
| 1980 | const action = `input:${inputId}`; |
| 1981 | if (!claimInFlight(app.inFlightActions, action)) return; |
| 1982 | setAttentionCardBusy(action, true); |
| 1983 | try { |
| 1984 | await api(`/v1/user-input/${encodeURIComponent(resolved.threadId)}/${encodeURIComponent(resolved.inputId)}`, { |
| 1985 | method: "POST", |
| 1986 | body: JSON.stringify({ answers: built.answers }), |
| 1987 | }); |
| 1988 | app.threadState.userInputs.delete(inputId); |
| 1989 | showStatus(""); |
| 1990 | renderAttention(); |
| 1991 | } catch (error) { |
| 1992 | showStatus(error.message); |
| 1993 | } finally { |
| 1994 | app.inFlightActions.delete(action); |
| 1995 | setAttentionCardBusy(action, false); |
| 1996 | } |
| 1997 | }); |
| 1998 | return card; |
| 1999 | } |
| 2000 | |
| 2001 | function safeDomId(value) { |
| 2002 | return String(value || "item").replace(/[^a-zA-Z0-9_-]/g, "-"); |
| 2003 | } |
| 2004 | |
| 2005 | function latestTurn() { |
| 2006 | const id = app.threadState.turnOrder.at(-1); |
| 2007 | return id ? app.threadState.turns.get(id) : null; |
| 2008 | } |
| 2009 | |
| 2010 | function activeTurn() { |
| 2011 | const turn = latestTurn(); |
| 2012 | return turn && (turn.status === "in_progress" || turn.status === "queued") ? turn : null; |
| 2013 | } |
| 2014 | |
| 2015 | function renderComposer() { |
| 2016 | const ready = Boolean(app.threadState.thread); |
| 2017 | const active = activeTurn(); |
| 2018 | const sending = app.inFlightActions.has(composerSendAction); |
| 2019 | dom.composerInput.disabled = sending || !ready; |
| 2020 | dom.composerInput.placeholder = composerPlaceholderFor(app.target, composerDefaultPlaceholder); |
| 2021 | dom.send.disabled = sending || !ready || !dom.composerInput.value.trim(); |
| 2022 | dom.composer.setAttribute("aria-busy", sending ? "true" : "false"); |
| 2023 | dom.interrupt.hidden = !active; |
| 2024 | setSafeText(dom.send, sending ? (active ? "Steering…" : "Sending…") : active ? "Steer" : "Send"); |
| 2025 | } |
| 2026 | |
| 2027 | function selectedNewThreadProvider() { |
| 2028 | return app.providerCatalog?.providers?.[dom.newThreadProvider.selectedIndex] || null; |
| 2029 | } |
| 2030 | |
| 2031 | function selectedNewThreadModel() { |
| 2032 | const provider = selectedNewThreadProvider(); |
| 2033 | return provider?.has_model_catalog |
| 2034 | ? dom.newThreadModel.value |
| 2035 | : dom.newThreadModelInput.value.trim(); |
| 2036 | } |
| 2037 | |
| 2038 | function setNewThreadStatus(message, state = "") { |
| 2039 | setSafeText(dom.newThreadStatus, message || ""); |
| 2040 | dom.newThreadStatus.dataset.state = state; |
| 2041 | } |
| 2042 | |
| 2043 | function renderNewThreadCapability() { |
| 2044 | const provider = selectedNewThreadProvider(); |
| 2045 | const modelId = selectedNewThreadModel(); |
| 2046 | if (!provider || !modelId) { |
| 2047 | setSafeText(dom.newThreadCapability, ""); |
| 2048 | dom.newThreadCapability.dataset.state = "unknown"; |
| 2049 | return; |
| 2050 | } |
| 2051 | const model = provider.has_model_catalog |
| 2052 | ? app.newThreadModels.find((entry) => entry.id === modelId) |
| 2053 | : null; |
| 2054 | const presentation = imageInputPresentation(model?.image_input); |
| 2055 | dom.newThreadCapability.dataset.state = presentation.state; |
| 2056 | setSafeText( |
| 2057 | dom.newThreadCapability, |
| 2058 | `${presentation.label} — ${presentation.description}`, |
| 2059 | ); |
| 2060 | } |
| 2061 | |
| 2062 | function syncNewThreadControls() { |
| 2063 | const provider = selectedNewThreadProvider(); |
| 2064 | const hasCatalog = Boolean(provider?.has_model_catalog); |
| 2065 | const busy = app.newThreadLoading || app.creatingThread; |
| 2066 | dom.newThreadProvider.disabled = app.creatingThread || !app.providerCatalog?.providers?.length; |
| 2067 | dom.newThreadModel.disabled = busy || !hasCatalog || app.newThreadModels.length === 0; |
| 2068 | dom.newThreadModelInput.disabled = busy || !provider || hasCatalog; |
| 2069 | dom.newThreadCancel.disabled = app.creatingThread; |
| 2070 | dom.newThreadCreate.disabled = busy || !provider || !selectedNewThreadModel(); |
| 2071 | renderNewThreadCapability(); |
| 2072 | } |
| 2073 | |
| 2074 | function setNewThreadModelSurface(provider) { |
| 2075 | const hasCatalog = Boolean(provider?.has_model_catalog); |
| 2076 | dom.newThreadModelSelectField.hidden = !hasCatalog; |
| 2077 | dom.newThreadModelInputField.hidden = hasCatalog; |
| 2078 | } |
| 2079 | |
| 2080 | async function loadNewThreadModels(provider, preferredModel, generation) { |
| 2081 | if (generation !== app.newThreadGeneration || !dom.newThreadDialog.open) return; |
| 2082 | app.newThreadModels = []; |
| 2083 | dom.newThreadModel.replaceChildren(); |
| 2084 | dom.newThreadModelInput.value = ""; |
| 2085 | setNewThreadModelSurface(provider); |
| 2086 | if (!provider) { |
| 2087 | app.newThreadLoading = false; |
| 2088 | setNewThreadStatus("Choose a provider.", "error"); |
| 2089 | syncNewThreadControls(); |
| 2090 | return; |
| 2091 | } |
| 2092 | |
| 2093 | const modelDefault = String(preferredModel || provider.default_model || "").trim(); |
| 2094 | if (!provider.has_model_catalog) { |
| 2095 | dom.newThreadModelInput.value = modelDefault; |
| 2096 | app.newThreadLoading = false; |
| 2097 | setNewThreadStatus(""); |
| 2098 | syncNewThreadControls(); |
| 2099 | return; |
| 2100 | } |
| 2101 | |
| 2102 | app.newThreadLoading = true; |
| 2103 | setNewThreadStatus("Loading models…"); |
| 2104 | syncNewThreadControls(); |
| 2105 | try { |
| 2106 | const modelEntries = await collectProviderModelPages(provider.id, async (path) => { |
| 2107 | const page = await api(path); |
| 2108 | if (generation !== app.newThreadGeneration || !dom.newThreadDialog.open) { |
| 2109 | throw new Error("The model request was superseded."); |
| 2110 | } |
| 2111 | return page; |
| 2112 | }, provider.model_provider_id); |
| 2113 | if (generation !== app.newThreadGeneration || !dom.newThreadDialog.open) return; |
| 2114 | const seen = new Set(); |
| 2115 | const models = []; |
| 2116 | for (const entry of modelEntries) { |
| 2117 | const id = String(entry?.id || "").trim(); |
| 2118 | const key = id.toLowerCase(); |
| 2119 | if (!id || seen.has(key)) continue; |
| 2120 | seen.add(key); |
| 2121 | models.push({ |
| 2122 | id, |
| 2123 | image_input: ["supported", "unsupported", "unknown"].includes(entry?.image_input) |
| 2124 | ? entry.image_input |
| 2125 | : "unknown", |
| 2126 | }); |
| 2127 | } |
| 2128 | if (modelDefault && !seen.has(modelDefault.toLowerCase())) { |
| 2129 | models.unshift({ id: modelDefault, image_input: "unknown" }); |
| 2130 | } |
| 2131 | app.newThreadModels = models; |
| 2132 | for (const model of models) { |
| 2133 | const option = document.createElement("option"); |
| 2134 | option.value = model.id; |
| 2135 | setSafeText(option, modelOptionLabel(model)); |
| 2136 | dom.newThreadModel.append(option); |
| 2137 | } |
| 2138 | const selectedDefault = models.find( |
| 2139 | (model) => model.id.toLowerCase() === modelDefault.toLowerCase(), |
| 2140 | ); |
| 2141 | if (selectedDefault) dom.newThreadModel.value = selectedDefault.id; |
| 2142 | app.newThreadLoading = false; |
| 2143 | setNewThreadStatus( |
| 2144 | models.length ? "" : "No models are available for this provider.", |
| 2145 | models.length ? "" : "error", |
| 2146 | ); |
| 2147 | syncNewThreadControls(); |
| 2148 | } catch (error) { |
| 2149 | if (generation !== app.newThreadGeneration || !dom.newThreadDialog.open) return; |
| 2150 | app.newThreadLoading = false; |
| 2151 | setNewThreadStatus(`Could not load models: ${error.message}`, "error"); |
| 2152 | syncNewThreadControls(); |
| 2153 | } |
| 2154 | } |
| 2155 | |
| 2156 | async function openNewThreadDialog() { |
| 2157 | if (dom.newThreadDialog.open || app.creatingThread) return; |
| 2158 | dom.newThreadDialog.showModal(); |
| 2159 | dom.newThreadCancel.focus({ preventScroll: true }); |
| 2160 | const generation = ++app.newThreadGeneration; |
| 2161 | app.providerCatalog = null; |
| 2162 | app.newThreadModels = []; |
| 2163 | app.newThreadLoading = true; |
| 2164 | dom.newThreadProvider.replaceChildren(); |
| 2165 | dom.newThreadModel.replaceChildren(); |
| 2166 | dom.newThreadModelInput.value = ""; |
| 2167 | setNewThreadStatus("Loading providers…"); |
| 2168 | renderNewThreadCapability(); |
| 2169 | syncNewThreadControls(); |
| 2170 | try { |
| 2171 | const catalog = await api("/v1/providers"); |
| 2172 | if (generation !== app.newThreadGeneration || !dom.newThreadDialog.open) return; |
| 2173 | const providers = Array.isArray(catalog?.providers) |
| 2174 | ? catalog.providers.filter((provider) => String(provider?.id || "").trim()) |
| 2175 | : []; |
| 2176 | if (providers.length === 0) throw new Error("The Runtime returned no providers."); |
| 2177 | app.providerCatalog = { ...catalog, providers }; |
| 2178 | for (const [index, provider] of providers.entries()) { |
| 2179 | const option = document.createElement("option"); |
| 2180 | option.value = String(index); |
| 2181 | setSafeText(option, providerOptionLabel(provider)); |
| 2182 | dom.newThreadProvider.append(option); |
| 2183 | } |
| 2184 | const defaults = newThreadDefaults(app.providerCatalog); |
| 2185 | const defaultIndex = providers.findIndex((provider) => provider.id === defaults.providerId |
| 2186 | && (provider.model_provider_id || "") === defaults.modelProviderId); |
| 2187 | dom.newThreadProvider.selectedIndex = Math.max(defaultIndex, 0); |
| 2188 | dom.newThreadProvider.disabled = false; |
| 2189 | dom.newThreadProvider.focus({ preventScroll: true }); |
| 2190 | await loadNewThreadModels(selectedNewThreadProvider(), defaults.model, generation); |
| 2191 | } catch (error) { |
| 2192 | if (generation !== app.newThreadGeneration || !dom.newThreadDialog.open) return; |
| 2193 | app.newThreadLoading = false; |
| 2194 | setNewThreadStatus(`Could not load providers: ${error.message}`, "error"); |
| 2195 | syncNewThreadControls(); |
| 2196 | } |
| 2197 | } |
| 2198 | |
| 2199 | async function submitNewThread(event) { |
| 2200 | event.preventDefault(); |
| 2201 | const provider = selectedNewThreadProvider(); |
| 2202 | let request; |
| 2203 | try { |
| 2204 | request = buildCreateThreadRequest( |
| 2205 | provider?.id, |
| 2206 | selectedNewThreadModel(), |
| 2207 | provider?.model_provider_id, |
| 2208 | ); |
| 2209 | } catch (error) { |
| 2210 | setNewThreadStatus(error.message, "error"); |
| 2211 | return; |
| 2212 | } |
| 2213 | app.creatingThread = true; |
| 2214 | setNewThreadStatus("Creating thread…"); |
| 2215 | dom.newThreadDialog.focus({ preventScroll: true }); |
| 2216 | syncNewThreadControls(); |
| 2217 | const thread = await createThread( |
| 2218 | request, |
| 2219 | (message) => setNewThreadStatus(message, message ? "error" : ""), |
| 2220 | ); |
| 2221 | app.creatingThread = false; |
| 2222 | if (thread) { |
| 2223 | dom.newThreadDialog.close(); |
| 2224 | dom.composerInput.focus(); |
| 2225 | return; |
| 2226 | } |
| 2227 | syncNewThreadControls(); |
| 2228 | dom.newThreadProvider.focus({ preventScroll: true }); |
| 2229 | } |
| 2230 | |
| 2231 | async function createThread(request = {}, reportError = showStatus) { |
| 2232 | showStatus(""); |
| 2233 | reportError(""); |
| 2234 | try { |
| 2235 | const thread = await api("/v1/threads", { |
| 2236 | method: "POST", |
| 2237 | body: JSON.stringify(request), |
| 2238 | }); |
| 2239 | await loadThreads(""); |
| 2240 | await selectThread(thread.id); |
| 2241 | dom.composerInput.focus(); |
| 2242 | return thread; |
| 2243 | } catch (error) { |
| 2244 | reportError(error.message); |
| 2245 | return null; |
| 2246 | } |
| 2247 | } |
| 2248 | |
| 2249 | async function sendMessage() { |
| 2250 | const prompt = dom.composerInput.value.trim(); |
| 2251 | if (!prompt) return; |
| 2252 | // A reply goes to a live thread or nowhere. A saved-session peek must not |
| 2253 | // silently resume-and-send: that would attach the user's message to a |
| 2254 | // thread they never asked to create. |
| 2255 | if (app.target.kind === "session") { |
| 2256 | showStatus(refusalMessage("session-not-live")); |
| 2257 | return; |
| 2258 | } |
| 2259 | if (!claimInFlight(app.inFlightActions, composerSendAction)) return; |
| 2260 | renderComposer(); |
| 2261 | showStatus(""); |
| 2262 | try { |
| 2263 | let threadId = app.selectedThreadId; |
| 2264 | if (!threadId) { |
| 2265 | const thread = await createThread(); |
| 2266 | if (!thread) return; |
| 2267 | threadId = thread.id; |
| 2268 | } |
| 2269 | const resolved = resolveReplyTarget(threadTarget(threadId), app.threadState); |
| 2270 | if (!resolved.ok) { |
| 2271 | showStatus(refusalMessage(resolved.reason)); |
| 2272 | return; |
| 2273 | } |
| 2274 | threadId = resolved.threadId; |
| 2275 | const turn = activeTurn(); |
| 2276 | if (turn) { |
| 2277 | await api(`/v1/threads/${encodeURIComponent(threadId)}/turns/${encodeURIComponent(turn.id)}/steer`, { |
| 2278 | method: "POST", |
| 2279 | body: JSON.stringify({ prompt }), |
| 2280 | }); |
| 2281 | } else { |
| 2282 | await api(`/v1/threads/${encodeURIComponent(threadId)}/turns`, { |
| 2283 | method: "POST", |
| 2284 | body: JSON.stringify({ prompt }), |
| 2285 | }); |
| 2286 | } |
| 2287 | saveDraft(app.drafts, threadId, ""); |
| 2288 | dom.composerInput.value = ""; |
| 2289 | resizeComposer(); |
| 2290 | renderComposer(); |
| 2291 | loadThreads().catch((error) => showStatus(error.message)); |
| 2292 | } catch (error) { |
| 2293 | showStatus(error.message); |
| 2294 | } finally { |
| 2295 | app.inFlightActions.delete(composerSendAction); |
| 2296 | renderComposer(); |
| 2297 | } |
| 2298 | } |
| 2299 | |
| 2300 | async function interruptTurn() { |
| 2301 | const turn = activeTurn(); |
| 2302 | if (!turn || !app.selectedThreadId) return; |
| 2303 | dom.interrupt.disabled = true; |
| 2304 | try { |
| 2305 | await api(`/v1/threads/${encodeURIComponent(app.selectedThreadId)}/turns/${encodeURIComponent(turn.id)}/interrupt`, { method: "POST" }); |
| 2306 | } catch (error) { |
| 2307 | showStatus(error.message); |
| 2308 | } finally { |
| 2309 | dom.interrupt.disabled = false; |
| 2310 | } |
| 2311 | } |
| 2312 | |
| 2313 | async function archiveThread() { |
| 2314 | if (!app.selectedThreadId) return; |
| 2315 | if (!globalThis.confirm("Archive this thread? You can still access it through the Runtime API.")) return; |
| 2316 | try { |
| 2317 | await api(`/v1/threads/${encodeURIComponent(app.selectedThreadId)}`, { |
| 2318 | method: "PATCH", |
| 2319 | body: JSON.stringify({ archived: true }), |
| 2320 | }); |
| 2321 | saveDraft(app.drafts, app.selectedThreadId, ""); |
| 2322 | stopStream(); |
| 2323 | app.selectedThreadId = ""; |
| 2324 | app.threadState = createThreadState(); |
| 2325 | await loadThreads(); |
| 2326 | if (app.summaries[0]) await selectThread(app.summaries[0].id); |
| 2327 | else renderAll(); |
| 2328 | } catch (error) { |
| 2329 | showStatus(error.message); |
| 2330 | } |
| 2331 | } |
| 2332 | |
| 2333 | function openRenameDialog() { |
| 2334 | if (!app.threadState.thread) return; |
| 2335 | dom.renameInput.value = app.threadState.thread.title || ""; |
| 2336 | dom.renameDialog.showModal(); |
| 2337 | dom.renameInput.focus(); |
| 2338 | dom.renameInput.select(); |
| 2339 | } |
| 2340 | |
| 2341 | async function submitRename(event) { |
| 2342 | event.preventDefault(); |
| 2343 | const action = event.submitter?.value; |
| 2344 | if (action !== "save") { |
| 2345 | dom.renameDialog.close(); |
| 2346 | return; |
| 2347 | } |
| 2348 | const title = dom.renameInput.value.trim(); |
| 2349 | if (!title || !app.selectedThreadId) return; |
| 2350 | try { |
| 2351 | const thread = await api(`/v1/threads/${encodeURIComponent(app.selectedThreadId)}`, { |
| 2352 | method: "PATCH", |
| 2353 | body: JSON.stringify({ title }), |
| 2354 | }); |
| 2355 | app.threadState.thread = thread; |
| 2356 | dom.renameDialog.close(); |
| 2357 | await loadThreads(); |
| 2358 | renderHeader(); |
| 2359 | } catch (error) { |
| 2360 | showStatus(error.message); |
| 2361 | } |
| 2362 | } |
| 2363 | |
| 2364 | function resizeComposer() { |
| 2365 | dom.composerInput.style.height = "auto"; |
| 2366 | dom.composerInput.style.height = `${Math.min(dom.composerInput.scrollHeight, 220)}px`; |
| 2367 | } |
| 2368 | |
| 2369 | function closeRailIfNarrow() { |
| 2370 | if (globalThis.matchMedia("(max-width: 800px)").matches) closeRail(); |
| 2371 | } |
| 2372 | |
| 2373 | dom.railOpen.addEventListener("click", openRail); |
| 2374 | dom.railClose.addEventListener("click", closeRail); |
| 2375 | dom.railScrim.addEventListener("click", closeRail); |
| 2376 | dom.newThread.addEventListener("click", () => void openNewThreadDialog()); |
| 2377 | dom.newThreadForm.addEventListener("submit", submitNewThread); |
| 2378 | dom.newThreadProvider.addEventListener("change", () => { |
| 2379 | const provider = selectedNewThreadProvider(); |
| 2380 | const generation = ++app.newThreadGeneration; |
| 2381 | void loadNewThreadModels(provider, provider?.default_model || "", generation); |
| 2382 | }); |
| 2383 | dom.newThreadModel.addEventListener("change", syncNewThreadControls); |
| 2384 | dom.newThreadModelInput.addEventListener("input", syncNewThreadControls); |
| 2385 | dom.newThreadCancel.addEventListener("click", () => { |
| 2386 | if (!app.creatingThread) dom.newThreadDialog.close(); |
| 2387 | }); |
| 2388 | dom.newThreadDialog.addEventListener("cancel", (event) => { |
| 2389 | if (app.creatingThread) event.preventDefault(); |
| 2390 | }); |
| 2391 | dom.newThreadDialog.addEventListener("keydown", (event) => { |
| 2392 | trapFocusWithin(event, dom.newThreadDialog); |
| 2393 | }); |
| 2394 | dom.newThreadDialog.addEventListener("close", () => { |
| 2395 | app.newThreadGeneration += 1; |
| 2396 | app.newThreadLoading = false; |
| 2397 | setNewThreadStatus(""); |
| 2398 | }); |
| 2399 | dom.rename.addEventListener("click", openRenameDialog); |
| 2400 | dom.archive.addEventListener("click", archiveThread); |
| 2401 | dom.renameForm.addEventListener("submit", submitRename); |
| 2402 | dom.interrupt.addEventListener("click", interruptTurn); |
| 2403 | dom.composer.addEventListener("submit", (event) => { |
| 2404 | event.preventDefault(); |
| 2405 | sendMessage(); |
| 2406 | }); |
| 2407 | dom.composerInput.addEventListener("input", () => { |
| 2408 | saveDraft(app.drafts, app.selectedThreadId, dom.composerInput.value); |
| 2409 | resizeComposer(); |
| 2410 | renderComposer(); |
| 2411 | }); |
| 2412 | dom.composerInput.addEventListener("keydown", (event) => { |
| 2413 | if (!isComposerSubmitKey(event)) return; |
| 2414 | event.preventDefault(); |
| 2415 | sendMessage(); |
| 2416 | }); |
| 2417 | dom.search.addEventListener("input", () => { |
| 2418 | if (app.searchTimer) clearTimeout(app.searchTimer); |
| 2419 | app.searchTimer = setTimeout(() => { |
| 2420 | loadThreads().catch((error) => showStatus(error.message)); |
| 2421 | loadSessions().catch(() => {}); |
| 2422 | }, 180); |
| 2423 | }); |
| 2424 | document.addEventListener("keydown", (event) => { |
| 2425 | if (dom.newThreadDialog.open) return; |
| 2426 | if (trapRailFocus(event)) return; |
| 2427 | if (event.key === "Escape" && narrowRail.matches && dom.shell.classList.contains("rail-visible")) { |
| 2428 | event.preventDefault(); |
| 2429 | closeRail(); |
| 2430 | } |
| 2431 | }); |
| 2432 | narrowRail.addEventListener("change", syncRailAccessibility); |
| 2433 | globalThis.visualViewport?.addEventListener("resize", syncVisualViewport); |
| 2434 | globalThis.visualViewport?.addEventListener("scroll", syncVisualViewport); |
| 2435 | globalThis.addEventListener("resize", syncVisualViewport); |
| 2436 | globalThis.addEventListener("beforeunload", stopStream); |
| 2437 | |
| 2438 | async function initialize() { |
| 2439 | syncVisualViewport(); |
| 2440 | syncRailAccessibility(); |
| 2441 | try { |
| 2442 | [app.runtimeInfo, app.workspace] = await Promise.all([ |
| 2443 | api("/v1/runtime/info"), |
| 2444 | api("/v1/workspace/status"), |
| 2445 | ]); |
| 2446 | renderRuntimeProvenance(dom.runtimeProvenance, app.runtimeInfo); |
| 2447 | setConnection("ready", "Local runtime connected"); |
| 2448 | await loadThreads(); |
| 2449 | await loadSessions(); |
| 2450 | if (app.summaries[0]) await selectThread(app.summaries[0].id); |
| 2451 | else renderAll(); |
| 2452 | } catch (error) { |
| 2453 | setConnection("error", "Runtime connection failed"); |
| 2454 | showStatus(error.message); |
| 2455 | renderAll(); |
| 2456 | } |
| 2457 | } |
| 2458 | |
| 2459 | initialize(); |
| 2460 | } |
| 2461 | |
| 2462 | function basename(path) { |
| 2463 | if (!path) return ""; |
| 2464 | const normalized = String(path).replaceAll("\\", "/").replace(/\/$/, ""); |
| 2465 | return normalized.split("/").at(-1) || normalized; |
| 2466 | } |
| 2467 | |
| 2468 | function humanize(value) { |
| 2469 | if (!value) return "Status"; |
| 2470 | return String(value) |
| 2471 | .replaceAll("_", " ") |
| 2472 | .replace(/\b\w/g, (letter) => letter.toUpperCase()); |
| 2473 | } |
| 2474 | |
| 2475 | export function modeLabel(mode) { |
| 2476 | if (mode === "agent") return "Work"; |
| 2477 | if (mode === "plan") return "Plan"; |
| 2478 | if (mode === "operate") return "Operate"; |
| 2479 | return humanize(mode || "Runtime default"); |
| 2480 | } |
| 2481 | |
| 2482 | export function formatRuntimeProvenance(runtimeInfo) { |
| 2483 | const version = String( |
| 2484 | runtimeInfo?.codewhale_version || runtimeInfo?.version || "", |
| 2485 | ).trim() || "version unknown"; |
| 2486 | const commit = String(runtimeInfo?.codewhale_commit || "").trim(); |
| 2487 | const source = /^[0-9a-f]{40}$/i.test(commit) |
| 2488 | ? commit.slice(0, 12) |
| 2489 | : "source unknown"; |
| 2490 | return `${version} · ${source}`; |
| 2491 | } |
| 2492 | |
| 2493 | export function renderRuntimeProvenance(element, runtimeInfo) { |
| 2494 | return setSafeText(element, formatRuntimeProvenance(runtimeInfo)); |
| 2495 | } |
| 2496 | |
| 2497 | function permissionLabel(thread) { |
| 2498 | if (thread.trust_mode) return "Full Access"; |
| 2499 | if (thread.auto_approve) return "Auto-Review"; |
| 2500 | return "Ask"; |
| 2501 | } |
| 2502 | |
| 2503 | function relativeTime(value) { |
| 2504 | const timestamp = Date.parse(value); |
| 2505 | if (!Number.isFinite(timestamp)) return "recent"; |
| 2506 | const seconds = Math.max(0, Math.round((Date.now() - timestamp) / 1000)); |
| 2507 | if (seconds < 60) return "now"; |
| 2508 | if (seconds < 3600) return `${Math.floor(seconds / 60)}m`; |
| 2509 | if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`; |
| 2510 | return `${Math.floor(seconds / 86400)}d`; |
| 2511 | } |
| 2512 | |
| 2513 | if (typeof document !== "undefined") { |
| 2514 | startBrowserClient(); |
| 2515 | } |
| 2516 |