| 1 | <!doctype html> |
| 2 | <html lang="en"> |
| 3 | <head> |
| 4 | <meta charset="utf-8"> |
| 5 | <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> |
| 6 | <title>Codewhale Mobile</title> |
| 7 | <style> |
| 8 | :root { |
| 9 | color-scheme: dark; |
| 10 | --bg: #101214; |
| 11 | --panel: #181b1f; |
| 12 | --panel-2: #20242a; |
| 13 | --line: #323840; |
| 14 | --text: #f4f1e8; |
| 15 | --muted: #a8a49a; |
| 16 | --accent: #48c2a8; |
| 17 | --accent-2: #c89543; |
| 18 | --danger: #e86458; |
| 19 | --ok: #76c46b; |
| 20 | } |
| 21 | * { box-sizing: border-box; } |
| 22 | html, body { min-height: 100%; } |
| 23 | body { |
| 24 | margin: 0; |
| 25 | background: var(--bg); |
| 26 | color: var(--text); |
| 27 | font: 15px/1.45 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; |
| 28 | letter-spacing: 0; |
| 29 | } |
| 30 | header { |
| 31 | position: sticky; |
| 32 | top: 0; |
| 33 | z-index: 4; |
| 34 | display: flex; |
| 35 | align-items: center; |
| 36 | justify-content: space-between; |
| 37 | gap: 12px; |
| 38 | padding: calc(12px + env(safe-area-inset-top)) 14px 12px; |
| 39 | background: rgba(16, 18, 20, 0.96); |
| 40 | border-bottom: 1px solid var(--line); |
| 41 | backdrop-filter: blur(12px); |
| 42 | } |
| 43 | h1 { |
| 44 | margin: 0; |
| 45 | font-size: 18px; |
| 46 | font-weight: 740; |
| 47 | } |
| 48 | main { |
| 49 | display: grid; |
| 50 | gap: 12px; |
| 51 | padding: 12px 12px calc(14px + env(safe-area-inset-bottom)); |
| 52 | } |
| 53 | section { |
| 54 | border: 1px solid var(--line); |
| 55 | background: var(--panel); |
| 56 | border-radius: 8px; |
| 57 | overflow: hidden; |
| 58 | } |
| 59 | .head { |
| 60 | display: flex; |
| 61 | align-items: center; |
| 62 | justify-content: space-between; |
| 63 | gap: 8px; |
| 64 | padding: 10px 12px; |
| 65 | border-bottom: 1px solid var(--line); |
| 66 | min-height: 46px; |
| 67 | } |
| 68 | .body { padding: 12px; } |
| 69 | .grid { display: grid; gap: 10px; } |
| 70 | .row { display: flex; align-items: center; gap: 8px; } |
| 71 | .row > * { flex: 1; min-width: 0; } |
| 72 | button, input, textarea, select { |
| 73 | color: var(--text); |
| 74 | background: var(--panel-2); |
| 75 | border: 1px solid var(--line); |
| 76 | border-radius: 8px; |
| 77 | font: inherit; |
| 78 | letter-spacing: 0; |
| 79 | } |
| 80 | button { |
| 81 | min-height: 40px; |
| 82 | padding: 8px 11px; |
| 83 | font-weight: 680; |
| 84 | cursor: pointer; |
| 85 | } |
| 86 | button.primary { |
| 87 | background: #173d36; |
| 88 | border-color: #2a8b77; |
| 89 | } |
| 90 | button.warn { |
| 91 | background: #3c2b14; |
| 92 | border-color: #8b682b; |
| 93 | } |
| 94 | button.danger { |
| 95 | background: #421f1d; |
| 96 | border-color: #9b4038; |
| 97 | } |
| 98 | button:disabled { |
| 99 | cursor: not-allowed; |
| 100 | opacity: 0.55; |
| 101 | } |
| 102 | input, textarea, select { |
| 103 | width: 100%; |
| 104 | padding: 10px; |
| 105 | } |
| 106 | textarea { |
| 107 | min-height: 96px; |
| 108 | resize: vertical; |
| 109 | } |
| 110 | label.toggle { |
| 111 | display: flex; |
| 112 | align-items: center; |
| 113 | gap: 8px; |
| 114 | min-height: 40px; |
| 115 | padding: 8px 10px; |
| 116 | color: var(--muted); |
| 117 | background: var(--panel-2); |
| 118 | border: 1px solid var(--line); |
| 119 | border-radius: 8px; |
| 120 | font-size: 13px; |
| 121 | } |
| 122 | label.toggle input { width: auto; } |
| 123 | .status { |
| 124 | min-height: 38px; |
| 125 | padding: 9px 10px; |
| 126 | border-radius: 8px; |
| 127 | background: #121518; |
| 128 | border: 1px solid var(--line); |
| 129 | color: var(--muted); |
| 130 | overflow-wrap: anywhere; |
| 131 | } |
| 132 | .status.ok { color: var(--ok); } |
| 133 | .status.bad { color: var(--danger); } |
| 134 | .status.warn { color: var(--accent-2); } |
| 135 | #threads { |
| 136 | display: grid; |
| 137 | gap: 8px; |
| 138 | max-height: 260px; |
| 139 | overflow: auto; |
| 140 | } |
| 141 | .thread { |
| 142 | width: 100%; |
| 143 | padding: 10px; |
| 144 | text-align: left; |
| 145 | border-radius: 8px; |
| 146 | background: var(--panel-2); |
| 147 | } |
| 148 | .thread.active { border-color: var(--accent); } |
| 149 | .thread-title { |
| 150 | font-weight: 720; |
| 151 | white-space: nowrap; |
| 152 | overflow: hidden; |
| 153 | text-overflow: ellipsis; |
| 154 | } |
| 155 | .meta { |
| 156 | margin-top: 3px; |
| 157 | color: var(--muted); |
| 158 | font-size: 12px; |
| 159 | overflow-wrap: anywhere; |
| 160 | } |
| 161 | #active-title { |
| 162 | flex: 1; |
| 163 | min-width: 0; |
| 164 | overflow: hidden; |
| 165 | text-overflow: ellipsis; |
| 166 | white-space: nowrap; |
| 167 | } |
| 168 | #turn-usage { |
| 169 | margin-top: 0; |
| 170 | font-variant-numeric: tabular-nums; |
| 171 | white-space: nowrap; |
| 172 | } |
| 173 | #turn-usage.live { color: var(--accent); } |
| 174 | #events { |
| 175 | display: grid; |
| 176 | gap: 8px; |
| 177 | max-height: 54vh; |
| 178 | overflow: auto; |
| 179 | padding-right: 2px; |
| 180 | } |
| 181 | .event { |
| 182 | padding: 9px 10px; |
| 183 | border: 1px solid var(--line); |
| 184 | border-radius: 8px; |
| 185 | background: #121518; |
| 186 | white-space: pre-wrap; |
| 187 | overflow-wrap: anywhere; |
| 188 | } |
| 189 | .event.agent { border-color: #357969; } |
| 190 | .event.tool { border-color: #8b682b; } |
| 191 | .event.error { border-color: #9b4038; } |
| 192 | .event.ok { border-color: #4d8048; } |
| 193 | .approval-actions { |
| 194 | display: flex; |
| 195 | flex-wrap: wrap; |
| 196 | gap: 8px; |
| 197 | margin-top: 9px; |
| 198 | } |
| 199 | .approval-actions button { |
| 200 | flex: 0 0 auto; |
| 201 | min-width: 84px; |
| 202 | } |
| 203 | .empty { |
| 204 | color: var(--muted); |
| 205 | font-size: 13px; |
| 206 | } |
| 207 | #agents-section[hidden] { display: none; } |
| 208 | .agent-row { |
| 209 | display: grid; |
| 210 | grid-template-columns: minmax(0, auto) auto; |
| 211 | gap: 2px 8px; |
| 212 | padding: 6px 0; |
| 213 | border-bottom: 1px solid var(--line); |
| 214 | font-size: 13px; |
| 215 | } |
| 216 | .agent-row:last-child { border-bottom: 0; } |
| 217 | .agent-name { font-weight: 600; overflow-wrap: anywhere; } |
| 218 | .agent-state { color: var(--muted); text-align: right; } |
| 219 | .agent-action { |
| 220 | grid-column: 1 / -1; |
| 221 | color: var(--muted); |
| 222 | overflow-wrap: anywhere; |
| 223 | } |
| 224 | @media (min-width: 900px) { |
| 225 | main { |
| 226 | grid-template-columns: 330px minmax(0, 1fr); |
| 227 | align-items: start; |
| 228 | } |
| 229 | section.chat { |
| 230 | grid-column: 2; |
| 231 | grid-row: 1 / span 3; |
| 232 | } |
| 233 | #threads { max-height: 420px; } |
| 234 | #events { max-height: calc(100vh - 150px); } |
| 235 | } |
| 236 | </style> |
| 237 | </head> |
| 238 | <body> |
| 239 | <header> |
| 240 | <h1>Codewhale Mobile</h1> |
| 241 | <button id="refresh" title="Refresh threads">Refresh</button> |
| 242 | </header> |
| 243 | |
| 244 | <main> |
| 245 | <section> |
| 246 | <div class="head"> |
| 247 | <strong>Connection</strong> |
| 248 | <button id="save-token">Connect</button> |
| 249 | </div> |
| 250 | <div class="body grid"> |
| 251 | <input id="token" autocomplete="off" spellcheck="false" placeholder="Runtime token (used once)"> |
| 252 | <div id="conn" class="status">Not connected</div> |
| 253 | </div> |
| 254 | </section> |
| 255 | |
| 256 | <section> |
| 257 | <div class="head"> |
| 258 | <strong>Threads</strong> |
| 259 | <button id="new-thread" class="primary">New</button> |
| 260 | </div> |
| 261 | <div class="body"><div id="threads"></div></div> |
| 262 | </section> |
| 263 | |
| 264 | <section id="agents-section" hidden> |
| 265 | <div class="head"> |
| 266 | <strong>Agents</strong> |
| 267 | <span id="agent-count" class="meta"></span> |
| 268 | </div> |
| 269 | <div class="body"><div id="agents"></div></div> |
| 270 | </section> |
| 271 | |
| 272 | <section class="chat"> |
| 273 | <div class="head"> |
| 274 | <strong id="active-title">No thread selected</strong> |
| 275 | <span id="turn-usage" class="meta" hidden></span> |
| 276 | <span id="event-count" class="meta">0 events</span> |
| 277 | </div> |
| 278 | <div class="body"><div id="events"></div></div> |
| 279 | </section> |
| 280 | |
| 281 | <section> |
| 282 | <div class="head"> |
| 283 | <strong>Composer</strong> |
| 284 | <button id="interrupt" class="danger">Interrupt</button> |
| 285 | </div> |
| 286 | <div class="body grid"> |
| 287 | <textarea id="prompt" spellcheck="true" placeholder="Message"></textarea> |
| 288 | <div class="row"> |
| 289 | <label class="toggle"><input id="allow-shell" type="checkbox"> shell</label> |
| 290 | <label class="toggle"><input id="auto-approve" type="checkbox"> auto</label> |
| 291 | <label class="toggle"><input id="remember-approval" type="checkbox"> remember</label> |
| 292 | </div> |
| 293 | <div class="row"> |
| 294 | <button id="send" class="primary">Send</button> |
| 295 | <button id="steer" class="warn">Steer</button> |
| 296 | </div> |
| 297 | </div> |
| 298 | </section> |
| 299 | </main> |
| 300 | |
| 301 | <script> |
| 302 | const streamMessages = __CODEWHALE_STREAM_MESSAGES__; |
| 303 | const $ = (id) => document.getElementById(id); |
| 304 | const MAX_VISIBLE_EVENTS = 100; |
| 305 | const LEGACY_RUNTIME_TOKEN_STORAGE_KEY = "codewhale_runtime_token"; |
| 306 | const LEGACY_RUNTIME_TOKEN_COOKIE = "codewhale_runtime_token"; |
| 307 | const SESSION_STORAGE_KEY = "codewhale_mobile_session_proof"; |
| 308 | const MOBILE_REQUEST_HEADER = "X-Codewhale-Mobile-Request"; |
| 309 | const MOBILE_STREAM_TICKET_QUERY = "mobile_stream_ticket"; |
| 310 | const state = { |
| 311 | threadId: "", |
| 312 | activeTurnId: "", |
| 313 | source: null, |
| 314 | // Seq of the last journal event shown for this thread: the resume |
| 315 | // cursor. Frames at or below it are replays and are skipped. |
| 316 | lastSeq: 0, |
| 317 | retryDelay: 750, |
| 318 | openedAt: 0, |
| 319 | eventCount: 0, |
| 320 | requestProof: "", |
| 321 | streamTicket: "", |
| 322 | // Sub-agents of the open thread, by agent id: rebuilt from the |
| 323 | // agent.* events the stream replays, so a reconnect restores it. |
| 324 | agents: new Map(), |
| 325 | turnUsage: emptyTurnUsage(), |
| 326 | turnUsageByThread: new Map() |
| 327 | }; |
| 328 | |
| 329 | function emptyTurnUsage() { |
| 330 | return { |
| 331 | input: 0, output: 0, usd: 0, cny: 0, |
| 332 | usdPriced: false, cnyPriced: false, live: false, |
| 333 | turnId: "", lastSeq: 0 |
| 334 | }; |
| 335 | } |
| 336 | |
| 337 | function turnUsageFor(threadId) { |
| 338 | if (!threadId) return state.turnUsage; |
| 339 | let figure = state.turnUsageByThread.get(threadId); |
| 340 | if (!figure) { |
| 341 | figure = emptyTurnUsage(); |
| 342 | state.turnUsageByThread.set(threadId, figure); |
| 343 | } |
| 344 | return figure; |
| 345 | } |
| 346 | |
| 347 | function formatTokens(count) { |
| 348 | if (!Number.isFinite(count) || count <= 0) return "0"; |
| 349 | if (count < 1000) return String(count); |
| 350 | if (count < 1000000) return (count / 1000).toFixed(count < 10000 ? 1 : 0) + "K"; |
| 351 | return (count / 1000000).toFixed(1) + "M"; |
| 352 | } |
| 353 | |
| 354 | function setStatus(message, tone = "") { |
| 355 | const el = $("conn"); |
| 356 | el.textContent = message; |
| 357 | el.className = "status" + (tone ? " " + tone : ""); |
| 358 | } |
| 359 | |
| 360 | function token() { |
| 361 | return $("token").value.trim(); |
| 362 | } |
| 363 | |
| 364 | function clearLegacyRuntimeToken() { |
| 365 | localStorage.removeItem(LEGACY_RUNTIME_TOKEN_STORAGE_KEY); |
| 366 | document.cookie = LEGACY_RUNTIME_TOKEN_COOKIE + "=; Max-Age=0; Path=/; SameSite=Strict"; |
| 367 | } |
| 368 | |
| 369 | function saveMobileSession() { |
| 370 | if (!state.requestProof) { |
| 371 | sessionStorage.removeItem(SESSION_STORAGE_KEY); |
| 372 | return; |
| 373 | } |
| 374 | sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify({ |
| 375 | requestProof: state.requestProof, |
| 376 | streamTicket: state.streamTicket |
| 377 | })); |
| 378 | } |
| 379 | |
| 380 | function clearMobileSession() { |
| 381 | state.requestProof = ""; |
| 382 | state.streamTicket = ""; |
| 383 | sessionStorage.removeItem(SESSION_STORAGE_KEY); |
| 384 | } |
| 385 | |
| 386 | function loadMobileSession() { |
| 387 | try { |
| 388 | const stored = JSON.parse(sessionStorage.getItem(SESSION_STORAGE_KEY) || "null"); |
| 389 | if (stored && typeof stored.requestProof === "string") { |
| 390 | state.requestProof = stored.requestProof; |
| 391 | state.streamTicket = typeof stored.streamTicket === "string" ? stored.streamTicket : ""; |
| 392 | } |
| 393 | } catch (_) { |
| 394 | clearMobileSession(); |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | function useMobileSession(session) { |
| 399 | if (!session || typeof session.request_proof !== "string") { |
| 400 | throw new Error("Mobile session bootstrap was incomplete"); |
| 401 | } |
| 402 | state.requestProof = session.request_proof; |
| 403 | state.streamTicket = typeof session.stream_ticket === "string" ? session.stream_ticket : ""; |
| 404 | saveMobileSession(); |
| 405 | } |
| 406 | |
| 407 | function takeMobileSessionFromUrl() { |
| 408 | const hash = location.hash.startsWith("#") ? location.hash.slice(1) : ""; |
| 409 | const params = new URLSearchParams(hash); |
| 410 | const requestProof = params.get("request_proof"); |
| 411 | const streamTicket = params.get("stream_ticket"); |
| 412 | if (!requestProof || !streamTicket) return; |
| 413 | useMobileSession({ request_proof: requestProof, stream_ticket: streamTicket }); |
| 414 | params.delete("request_proof"); |
| 415 | params.delete("stream_ticket"); |
| 416 | const nextHash = params.toString(); |
| 417 | history.replaceState( |
| 418 | null, |
| 419 | "", |
| 420 | location.pathname + location.search + (nextHash ? "#" + nextHash : "") |
| 421 | ); |
| 422 | } |
| 423 | |
| 424 | function headers(extra = {}) { |
| 425 | const out = Object.assign({ "Content-Type": "application/json" }, extra); |
| 426 | if (state.requestProof) out[MOBILE_REQUEST_HEADER] = state.requestProof; |
| 427 | return out; |
| 428 | } |
| 429 | |
| 430 | async function api(path, options = {}) { |
| 431 | const res = await fetch(path, Object.assign({}, options, { |
| 432 | credentials: "same-origin", |
| 433 | headers: headers(options.headers || {}) |
| 434 | })); |
| 435 | if (!res.ok) { |
| 436 | if (res.status === 401) clearMobileSession(); |
| 437 | let detail = await res.text(); |
| 438 | try { |
| 439 | const parsed = JSON.parse(detail); |
| 440 | detail = parsed.error?.message || detail; |
| 441 | } catch (_) {} |
| 442 | throw new Error(detail || ("HTTP " + res.status)); |
| 443 | } |
| 444 | if (res.status === 204) return null; |
| 445 | return res.json(); |
| 446 | } |
| 447 | |
| 448 | async function connectMobileSession() { |
| 449 | const runtimeToken = token(); |
| 450 | if (!runtimeToken) throw new Error("Enter a Runtime token to connect once"); |
| 451 | let res; |
| 452 | try { |
| 453 | res = await fetch("/__codewhale/mobile/session", { |
| 454 | method: "POST", |
| 455 | credentials: "same-origin", |
| 456 | headers: { "Authorization": "Bearer " + runtimeToken } |
| 457 | }); |
| 458 | } finally { |
| 459 | $("token").value = ""; |
| 460 | } |
| 461 | if (!res.ok) { |
| 462 | let detail = await res.text(); |
| 463 | try { |
| 464 | const parsed = JSON.parse(detail); |
| 465 | detail = parsed.error?.message || detail; |
| 466 | } catch (_) {} |
| 467 | throw new Error(detail || ("HTTP " + res.status)); |
| 468 | } |
| 469 | useMobileSession(await res.json()); |
| 470 | } |
| 471 | |
| 472 | async function refreshStreamTicket() { |
| 473 | const result = await api("/__codewhale/mobile/stream-ticket", { |
| 474 | method: "POST", |
| 475 | body: "{}" |
| 476 | }); |
| 477 | if (!result || typeof result.stream_ticket !== "string") { |
| 478 | throw new Error("Mobile stream ticket was unavailable"); |
| 479 | } |
| 480 | state.streamTicket = result.stream_ticket; |
| 481 | saveMobileSession(); |
| 482 | return state.streamTicket; |
| 483 | } |
| 484 | |
| 485 | async function takeStreamTicket() { |
| 486 | if (!state.requestProof) return ""; |
| 487 | const ticket = state.streamTicket || await refreshStreamTicket(); |
| 488 | state.streamTicket = ""; |
| 489 | saveMobileSession(); |
| 490 | return ticket; |
| 491 | } |
| 492 | |
| 493 | function escapeHtml(raw) { |
| 494 | return String(raw).replace(/[&<>"']/g, (char) => ({ |
| 495 | "&": "&", |
| 496 | "<": "<", |
| 497 | ">": ">", |
| 498 | "\"": """, |
| 499 | "'": "'" |
| 500 | }[char])); |
| 501 | } |
| 502 | |
| 503 | function eventPayload(data) { |
| 504 | return data && typeof data === "object" && "payload" in data ? data.payload : data; |
| 505 | } |
| 506 | |
| 507 | // The name every Codewhale surface shows for an agent (its workflow |
| 508 | // label or dispatch name), never its internal id. Hosts that predate the |
| 509 | // name get an ordinal instead. |
| 510 | function agentName(payload) { |
| 511 | const known = state.agents.get(payload.agent_id); |
| 512 | if (payload.agent_name) return payload.agent_name; |
| 513 | if (known && known.name) return known.name; |
| 514 | return "agent " + (known ? known.order : state.agents.size + 1); |
| 515 | } |
| 516 | |
| 517 | // The first line of prose in a result summary, not its heading. |
| 518 | function resultHeadline(text) { |
| 519 | const summary = String(text || "").replace(/^Sub-agent .*? (completed|failed|cancelled|interrupted|budget_exhausted|settled \(outcome unconfirmed\)): /, ""); |
| 520 | const line = summary.split("\n").map((part) => part.trim()) |
| 521 | .find((part) => part && !part.startsWith("#") && !part.startsWith("<codewhale:")); |
| 522 | return line || ""; |
| 523 | } |
| 524 | |
| 525 | function noteAgentEvent(name, data) { |
| 526 | if (!name.startsWith("agent.")) return; |
| 527 | const payload = eventPayload(data) || {}; |
| 528 | const id = payload.agent_id; |
| 529 | if (!id) return; |
| 530 | let agent = state.agents.get(id); |
| 531 | if (!agent) { |
| 532 | agent = { name: "", state: "", action: "", order: state.agents.size + 1 }; |
| 533 | state.agents.set(id, agent); |
| 534 | } |
| 535 | if (payload.agent_name) agent.name = payload.agent_name; |
| 536 | if (name === "agent.spawned") { |
| 537 | agent.state = "running"; |
| 538 | agent.action = "starting"; |
| 539 | } else if (name === "agent.progress") { |
| 540 | agent.state = "running"; |
| 541 | agent.action = [String(payload.worker_status || "").replace(/_/g, " "), |
| 542 | payload.step ? "step " + payload.step : ""].filter(Boolean).join(" · "); |
| 543 | } else if (name === "agent.completed") { |
| 544 | agent.state = String(payload.worker_status || "settled").replace(/_/g, " "); |
| 545 | agent.action = resultHeadline((payload.item || {}).summary); |
| 546 | } |
| 547 | renderAgents(); |
| 548 | } |
| 549 | |
| 550 | function renderAgents() { |
| 551 | const list = $("agents"); |
| 552 | list.innerHTML = ""; |
| 553 | let running = 0; |
| 554 | for (const [id, agent] of state.agents) { |
| 555 | if (agent.state === "running") running += 1; |
| 556 | const row = document.createElement("div"); |
| 557 | row.className = "agent-row"; |
| 558 | row.innerHTML = |
| 559 | "<span class='agent-name'>" + escapeHtml(agentName({ agent_id: id })) + "</span>" + |
| 560 | "<span class='agent-state'>" + escapeHtml(agent.state) + "</span>" + |
| 561 | (agent.action ? "<span class='agent-action'>" + escapeHtml(agent.action) + "</span>" : ""); |
| 562 | list.appendChild(row); |
| 563 | } |
| 564 | $("agents-section").hidden = state.agents.size === 0; |
| 565 | $("agent-count").textContent = state.agents.size |
| 566 | ? running + " running · " + state.agents.size + " total" |
| 567 | : ""; |
| 568 | } |
| 569 | |
| 570 | function eventText(name, data) { |
| 571 | const payload = eventPayload(data) || {}; |
| 572 | if (name === "agent.spawned") return agentName(payload) + " started"; |
| 573 | if (name === "agent.progress") { |
| 574 | return agentName(payload) + ": " + String(payload.worker_status || "working").replace(/_/g, " ") + |
| 575 | (payload.step ? " · step " + payload.step : ""); |
| 576 | } |
| 577 | if (name === "agent.completed") { |
| 578 | const headline = resultHeadline((payload.item || {}).summary); |
| 579 | return agentName(payload) + " " + String(payload.worker_status || "settled").replace(/_/g, " ") + |
| 580 | (headline ? ": " + headline : ""); |
| 581 | } |
| 582 | if (name === "item.delta") return payload.delta || ""; |
| 583 | if (name === "item.started") { |
| 584 | const tool = payload.tool; |
| 585 | if (tool) { |
| 586 | const label = (payload.item || {}).status === "queued" ? "Tool queued: " : "Tool started: "; |
| 587 | return label + tool.name + "\n" + JSON.stringify(tool.input || {}, null, 2); |
| 588 | } |
| 589 | } |
| 590 | if (name === "tool.execution_started") return "Tool started: " + ((payload.item || {}).summary || ""); |
| 591 | if (name === "item.completed" || name === "item.failed") { |
| 592 | const item = payload.item || {}; |
| 593 | return (name === "item.completed" ? "Completed: " : "Failed: ") + (item.summary || item.kind || ""); |
| 594 | } |
| 595 | if (name === "approval.required") { |
| 596 | return "Approval required: " + (payload.tool_name || "") + "\n" + (payload.description || ""); |
| 597 | } |
| 598 | if (name === "approval.decided") { |
| 599 | return "Approval " + (payload.decision || "decided") + ": " + (payload.approval_id || ""); |
| 600 | } |
| 601 | if (name === "approval.timeout") { |
| 602 | return "Approval timed out: " + (payload.approval_id || ""); |
| 603 | } |
| 604 | if (name === "sandbox.denied") { |
| 605 | return "Sandbox denied: " + (payload.tool_name || "") + "\n" + (payload.reason || ""); |
| 606 | } |
| 607 | if (name === "turn.lifecycle") return "Turn status: " + (payload.status || ""); |
| 608 | if (name === "turn.completed") return "Turn completed"; |
| 609 | if (name === "turn.usage") return ""; |
| 610 | return JSON.stringify(payload, null, 2); |
| 611 | } |
| 612 | |
| 613 | function noteTurnUsage(name, data) { |
| 614 | if (name !== "turn.started" && name !== "turn.usage" && name !== "turn.completed") return; |
| 615 | const payload = eventPayload(data) || {}; |
| 616 | const turnId = String((data && data.turn_id) || (payload.turn || {}).id || ""); |
| 617 | if (!turnId) return; |
| 618 | let figure = turnUsageFor(state.threadId); |
| 619 | const seq = Number(data && data.seq); |
| 620 | if (Number.isSafeInteger(seq) && seq > 0) { |
| 621 | if (seq <= figure.lastSeq) return; |
| 622 | figure.lastSeq = seq; |
| 623 | } |
| 624 | if (figure.turnId !== turnId) { |
| 625 | figure = Object.assign(emptyTurnUsage(), { turnId, lastSeq: figure.lastSeq }); |
| 626 | if (state.threadId) state.turnUsageByThread.set(state.threadId, figure); |
| 627 | } |
| 628 | state.turnUsage = figure; |
| 629 | if (name === "turn.started") { |
| 630 | figure.live = true; |
| 631 | } else if (name === "turn.usage") { |
| 632 | const usage = payload.usage || {}; |
| 633 | figure.input += Number(usage.input_tokens || 0) || 0; |
| 634 | figure.output += Number(usage.output_tokens || 0) || 0; |
| 635 | const cost = payload.cost; |
| 636 | if (cost && cost.usd_priced === true && Number.isFinite(Number(cost.usd))) { |
| 637 | figure.usd += Number(cost.usd); |
| 638 | figure.usdPriced = true; |
| 639 | } |
| 640 | if (cost && cost.cny_priced === true && Number.isFinite(Number(cost.cny))) { |
| 641 | figure.cny += Number(cost.cny); |
| 642 | figure.cnyPriced = true; |
| 643 | } |
| 644 | figure.live = true; |
| 645 | } else { |
| 646 | const usage = (payload.turn || {}).usage; |
| 647 | if (usage) { |
| 648 | figure.input = Number(usage.input_tokens || 0) || 0; |
| 649 | figure.output = Number(usage.output_tokens || 0) || 0; |
| 650 | } |
| 651 | figure.live = false; |
| 652 | } |
| 653 | renderTurnUsage(); |
| 654 | } |
| 655 | |
| 656 | function renderTurnUsage() { |
| 657 | const el = $("turn-usage"); |
| 658 | if (!el) return; |
| 659 | const figure = state.turnUsage; |
| 660 | if (!figure.input && !figure.output && !figure.usdPriced && !figure.cnyPriced) { |
| 661 | el.hidden = true; |
| 662 | el.textContent = ""; |
| 663 | el.className = "meta"; |
| 664 | return; |
| 665 | } |
| 666 | const parts = ["\u2191" + formatTokens(figure.input), "\u2193" + formatTokens(figure.output)]; |
| 667 | if (figure.cnyPriced) parts.push("~\u00a5" + figure.cny.toFixed(figure.cny < 0.01 ? 4 : 2) + " partial"); |
| 668 | else if (figure.usdPriced) parts.push("~$" + figure.usd.toFixed(figure.usd < 0.01 ? 4 : 2) + " partial"); |
| 669 | el.textContent = parts.join(" "); |
| 670 | el.className = figure.live ? "meta live" : "meta"; |
| 671 | el.title = (figure.live ? "This turn so far" : "Last turn") + |
| 672 | "; cost is a partial estimate from priced calls, excluding unpriced, child and compaction work"; |
| 673 | el.hidden = false; |
| 674 | } |
| 675 | |
| 676 | function approvalInfo(name, data) { |
| 677 | if (name !== "approval.required") return null; |
| 678 | const payload = eventPayload(data) || {}; |
| 679 | const approvalId = payload.approval_id || payload.id; |
| 680 | if (!approvalId) return null; |
| 681 | return { id: approvalId }; |
| 682 | } |
| 683 | |
| 684 | function retireApproval(name, data) { |
| 685 | if (name !== "approval.decided" && name !== "approval.timeout") return; |
| 686 | const payload = eventPayload(data) || {}; |
| 687 | const approvalId = payload.approval_id || payload.id; |
| 688 | if (!approvalId) return; |
| 689 | const label = name === "approval.timeout" |
| 690 | ? "Timed out" |
| 691 | : payload.cancelled ? "Cancelled" : "Decided: " + (payload.decision || "decided"); |
| 692 | for (const actions of document.querySelectorAll(".approval-actions")) { |
| 693 | if (actions.dataset.approvalId !== String(approvalId)) continue; |
| 694 | actions.innerHTML = "<span class='meta'>" + escapeHtml(label) + "</span>"; |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | function pruneVisibleEvents() { |
| 699 | const events = $("events"); |
| 700 | while (events.childElementCount > MAX_VISIBLE_EVENTS) { |
| 701 | events.firstElementChild.remove(); |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | async function decideApproval(approvalId, decision, container) { |
| 706 | for (const button of container.querySelectorAll("button")) button.disabled = true; |
| 707 | const remember = $("remember-approval").checked; |
| 708 | try { |
| 709 | const result = await api("/v1/approvals/" + encodeURIComponent(approvalId), { |
| 710 | method: "POST", |
| 711 | body: JSON.stringify({ decision, remember, client: "phone" }) |
| 712 | }); |
| 713 | const decided = result?.decision ?? decision; |
| 714 | container.innerHTML = "<span class='meta'>Decision sent: " + escapeHtml(decided) + "</span>"; |
| 715 | } catch (err) { |
| 716 | for (const button of container.querySelectorAll("button")) button.disabled = false; |
| 717 | throw err; |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | function appendEvent(name, data) { |
| 722 | noteAgentEvent(name, data); |
| 723 | retireApproval(name, data); |
| 724 | noteTurnUsage(name, data); |
| 725 | const text = eventText(name, data); |
| 726 | if (!text) return; |
| 727 | const item = document.createElement("div"); |
| 728 | item.className = "event"; |
| 729 | if (name === "item.delta") item.classList.add("agent"); |
| 730 | if (name === "item.started" || name.includes("tool")) item.classList.add("tool"); |
| 731 | if (name.includes("failed") || name.includes("denied") || name.includes("timeout")) item.classList.add("error"); |
| 732 | if (name === "turn.completed" || name === "approval.decided") item.classList.add("ok"); |
| 733 | if (name.startsWith("agent.")) item.classList.add("tool"); |
| 734 | item.innerHTML = "<div class='meta'>" + escapeHtml(name) + "</div>" + escapeHtml(text); |
| 735 | |
| 736 | const approval = approvalInfo(name, data); |
| 737 | if (approval) { |
| 738 | const actions = document.createElement("div"); |
| 739 | actions.className = "approval-actions"; |
| 740 | actions.dataset.approvalId = String(approval.id); |
| 741 | const allow = document.createElement("button"); |
| 742 | allow.className = "primary"; |
| 743 | allow.textContent = "Allow"; |
| 744 | allow.onclick = () => decideApproval(approval.id, "allow", actions) |
| 745 | .catch((err) => setStatus(err.message, "bad")); |
| 746 | const deny = document.createElement("button"); |
| 747 | deny.className = "danger"; |
| 748 | deny.textContent = "Deny"; |
| 749 | deny.onclick = () => decideApproval(approval.id, "deny", actions) |
| 750 | .catch((err) => setStatus(err.message, "bad")); |
| 751 | actions.appendChild(allow); |
| 752 | actions.appendChild(deny); |
| 753 | item.appendChild(actions); |
| 754 | } |
| 755 | |
| 756 | $("events").appendChild(item); |
| 757 | pruneVisibleEvents(); |
| 758 | state.eventCount += 1; |
| 759 | const visible = Math.min(state.eventCount, MAX_VISIBLE_EVENTS); |
| 760 | $("event-count").textContent = visible + " of " + state.eventCount + " events"; |
| 761 | $("events").scrollTop = $("events").scrollHeight; |
| 762 | } |
| 763 | |
| 764 | async function loadThreads() { |
| 765 | const threads = await api("/v1/threads/summary?limit=60&include_archived=false"); |
| 766 | const list = $("threads"); |
| 767 | list.innerHTML = ""; |
| 768 | if (!threads || !threads.length) { |
| 769 | list.innerHTML = "<div class='empty'>No active threads.</div>"; |
| 770 | return; |
| 771 | } |
| 772 | for (const thread of threads) { |
| 773 | const el = document.createElement("button"); |
| 774 | el.className = "thread" + (thread.id === state.threadId ? " active" : ""); |
| 775 | el.innerHTML = |
| 776 | "<div class='thread-title'>" + escapeHtml(thread.title || thread.id) + "</div>" + |
| 777 | "<div class='meta'>" + escapeHtml(thread.mode || "") + " / " + |
| 778 | escapeHtml(thread.model || "") + "</div>"; |
| 779 | el.onclick = () => selectThread(thread.id, thread.title || thread.id); |
| 780 | list.appendChild(el); |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | async function newThread() { |
| 785 | const thread = await api("/v1/threads", { |
| 786 | method: "POST", |
| 787 | body: JSON.stringify({ |
| 788 | mode: "agent", |
| 789 | allow_shell: $("allow-shell").checked, |
| 790 | trust_mode: false, |
| 791 | auto_approve: $("auto-approve").checked |
| 792 | }) |
| 793 | }); |
| 794 | await loadThreads(); |
| 795 | selectThread(thread.id, thread.title || thread.id); |
| 796 | } |
| 797 | |
| 798 | async function selectThread(id, title) { |
| 799 | state.threadId = id; |
| 800 | state.activeTurnId = ""; |
| 801 | state.lastSeq = 0; |
| 802 | state.retryDelay = 750; |
| 803 | state.openedAt = 0; |
| 804 | state.eventCount = 0; |
| 805 | $("event-count").textContent = "0 events"; |
| 806 | state.turnUsage = turnUsageFor(id); |
| 807 | renderTurnUsage(); |
| 808 | $("active-title").textContent = title || id; |
| 809 | $("events").innerHTML = ""; |
| 810 | state.agents.clear(); |
| 811 | renderAgents(); |
| 812 | if (state.source) state.source.close(); |
| 813 | await openThreadEvents(id); |
| 814 | await loadThreads(); |
| 815 | } |
| 816 | |
| 817 | // What the Runtime said when it ended the stream on purpose (`stream.end`). |
| 818 | function streamEndStatus(reason) { |
| 819 | switch (reason) { |
| 820 | case "replay_failed": |
| 821 | return streamMessages.replay_failed; |
| 822 | case "catch_up_failed": |
| 823 | return streamMessages.catch_up_failed; |
| 824 | case "runtime_shutdown": |
| 825 | return streamMessages.runtime_shutdown; |
| 826 | default: |
| 827 | return streamMessages.ended; |
| 828 | } |
| 829 | } |
| 830 | |
| 831 | // Reconnect from `cursor` (undefined: nothing shown yet, open fresh) after |
| 832 | // a bounded backoff. The backoff resets only after a stream stayed open a |
| 833 | // while: a Runtime that opens and at once ends the stream (a history it |
| 834 | // cannot read) is retried ever more slowly, not hammered. A Runtime that is not |
| 835 | // reachable yet fails the stream-ticket fetch itself (a network TypeError): |
| 836 | // keep trying. An HTTP refusal (for example an expired session) is final. |
| 837 | function scheduleResume(id, cursor) { |
| 838 | if (state.openedAt && Date.now() - state.openedAt > 10000) state.retryDelay = 750; |
| 839 | state.openedAt = 0; |
| 840 | const delay = state.retryDelay; |
| 841 | state.retryDelay = Math.min(state.retryDelay * 2, 15000); |
| 842 | window.setTimeout(() => { |
| 843 | if (state.threadId !== id) return; |
| 844 | openThreadEvents(id, cursor).catch((err) => { |
| 845 | if (state.threadId !== id) return; |
| 846 | if (err instanceof TypeError) { |
| 847 | setStatus(streamMessages.reconnecting, "warn"); |
| 848 | scheduleResume(id, cursor); |
| 849 | } else { |
| 850 | setStatus(err.message, "bad"); |
| 851 | } |
| 852 | }); |
| 853 | }, delay); |
| 854 | } |
| 855 | |
| 856 | // `resumeFrom` undefined opens the newest tail; a number resumes after it, |
| 857 | // so a reconnect never replays (and duplicates) what is already shown. |
| 858 | async function openThreadEvents(id, resumeFrom) { |
| 859 | const streamTicket = await takeStreamTicket(); |
| 860 | const query = new URLSearchParams( |
| 861 | resumeFrom === undefined |
| 862 | ? { since_seq: "0", replay_limit: String(MAX_VISIBLE_EVENTS) } |
| 863 | : { since_seq: String(resumeFrom) } |
| 864 | ); |
| 865 | if (streamTicket) query.set(MOBILE_STREAM_TICKET_QUERY, streamTicket); |
| 866 | const source = new EventSource( |
| 867 | "/v1/threads/" + encodeURIComponent(id) + "/events?" + query.toString() |
| 868 | ); |
| 869 | state.source = source; |
| 870 | const names = [ |
| 871 | "thread.started", |
| 872 | "turn.started", |
| 873 | "turn.lifecycle", |
| 874 | "turn.usage", |
| 875 | "turn.steered", |
| 876 | "turn.interrupt_requested", |
| 877 | "turn.completed", |
| 878 | "item.started", |
| 879 | "item.delta", |
| 880 | "item.completed", |
| 881 | "item.failed", |
| 882 | "tool.execution_started", |
| 883 | "approval.required", |
| 884 | "approval.decided", |
| 885 | "approval.timeout", |
| 886 | "sandbox.denied", |
| 887 | "agent.spawned", |
| 888 | "agent.progress", |
| 889 | "agent.completed" |
| 890 | ]; |
| 891 | for (const name of names) { |
| 892 | source.addEventListener(name, (ev) => { |
| 893 | if (state.source !== source) return; |
| 894 | let data = {}; |
| 895 | try { data = JSON.parse(ev.data || "{}"); } catch (_) {} |
| 896 | if (Number.isSafeInteger(data.seq)) { |
| 897 | if (data.seq <= state.lastSeq) return; |
| 898 | state.lastSeq = data.seq; |
| 899 | } |
| 900 | if (data.turn_id) state.activeTurnId = data.turn_id; |
| 901 | appendEvent(name, data); |
| 902 | }); |
| 903 | } |
| 904 | // The Runtime ended the stream on purpose; `last_seq` is where to resume. |
| 905 | source.addEventListener("stream.end", (ev) => { |
| 906 | if (state.source !== source || state.threadId !== id) return; |
| 907 | source.close(); |
| 908 | let data = {}; |
| 909 | try { data = JSON.parse(ev.data || "{}"); } catch (_) {} |
| 910 | if (Number.isSafeInteger(data.last_seq)) { |
| 911 | state.lastSeq = Math.max(state.lastSeq, data.last_seq); |
| 912 | } |
| 913 | if (data.retryable !== true) { |
| 914 | setStatus(streamMessages.closed, "bad"); |
| 915 | return; |
| 916 | } |
| 917 | setStatus(streamEndStatus(data.reason), "warn"); |
| 918 | scheduleResume(id, state.lastSeq); |
| 919 | }); |
| 920 | // A Runtime that cannot serve this thread answers and at once ends the |
| 921 | // stream; claim "Connected" only once the stream has stayed open. |
| 922 | source.onopen = () => { |
| 923 | state.openedAt = Date.now(); |
| 924 | window.setTimeout(() => { |
| 925 | if (state.source === source && source.readyState === EventSource.OPEN) { |
| 926 | setStatus(streamMessages.connected, "ok"); |
| 927 | } |
| 928 | }, 400); |
| 929 | }; |
| 930 | // No `stream.end`: the connection dropped (network, proxy, or a Runtime |
| 931 | // that exited without warning). Resume from what is already shown. |
| 932 | source.onerror = () => { |
| 933 | if (state.source !== source || state.threadId !== id) return; |
| 934 | source.close(); |
| 935 | setStatus(streamMessages.reconnecting, "warn"); |
| 936 | scheduleResume(id, state.lastSeq > 0 ? state.lastSeq : resumeFrom); |
| 937 | }; |
| 938 | } |
| 939 | |
| 940 | async function sendPrompt() { |
| 941 | if (!state.threadId) await newThread(); |
| 942 | const prompt = $("prompt").value.trim(); |
| 943 | if (!prompt) return; |
| 944 | const res = await api("/v1/threads/" + encodeURIComponent(state.threadId) + "/turns", { |
| 945 | method: "POST", |
| 946 | body: JSON.stringify({ |
| 947 | prompt, |
| 948 | allow_shell: $("allow-shell").checked, |
| 949 | trust_mode: false, |
| 950 | auto_approve: $("auto-approve").checked |
| 951 | }) |
| 952 | }); |
| 953 | state.activeTurnId = res.turn?.id || state.activeTurnId; |
| 954 | $("prompt").value = ""; |
| 955 | await loadThreads(); |
| 956 | } |
| 957 | |
| 958 | async function steerTurn() { |
| 959 | if (!state.threadId || !state.activeTurnId) throw new Error("No active turn"); |
| 960 | const prompt = $("prompt").value.trim(); |
| 961 | if (!prompt) return; |
| 962 | await api( |
| 963 | "/v1/threads/" + encodeURIComponent(state.threadId) + |
| 964 | "/turns/" + encodeURIComponent(state.activeTurnId) + "/steer", |
| 965 | { method: "POST", body: JSON.stringify({ prompt }) } |
| 966 | ); |
| 967 | $("prompt").value = ""; |
| 968 | } |
| 969 | |
| 970 | async function interruptTurn() { |
| 971 | if (!state.threadId || !state.activeTurnId) throw new Error("No active turn"); |
| 972 | await api( |
| 973 | "/v1/threads/" + encodeURIComponent(state.threadId) + |
| 974 | "/turns/" + encodeURIComponent(state.activeTurnId) + "/interrupt", |
| 975 | { method: "POST", body: "{}" } |
| 976 | ); |
| 977 | } |
| 978 | |
| 979 | async function boot() { |
| 980 | clearLegacyRuntimeToken(); |
| 981 | loadMobileSession(); |
| 982 | takeMobileSessionFromUrl(); |
| 983 | $("save-token").onclick = async () => { |
| 984 | await connectMobileSession(); |
| 985 | await loadThreads().catch((err) => setStatus(err.message, "bad")); |
| 986 | }; |
| 987 | $("refresh").onclick = () => loadThreads().catch((err) => setStatus(err.message, "bad")); |
| 988 | $("new-thread").onclick = () => newThread().catch((err) => setStatus(err.message, "bad")); |
| 989 | $("send").onclick = () => sendPrompt().catch((err) => setStatus(err.message, "bad")); |
| 990 | $("steer").onclick = () => steerTurn().catch((err) => setStatus(err.message, "bad")); |
| 991 | $("interrupt").onclick = () => interruptTurn().catch((err) => setStatus(err.message, "bad")); |
| 992 | await loadThreads(); |
| 993 | setStatus(streamMessages.connected, "ok"); |
| 994 | } |
| 995 | |
| 996 | boot().catch((err) => setStatus(err.message, "bad")); |
| 997 | </script> |
| 998 | </body> |
| 999 | </html> |
| 1000 |