@clagentic/console 1.9.0-beta.1 → 1.9.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/bin/cli.js +23 -1
  2. package/lib/agents.js +13 -3
  3. package/lib/build-sha.json +2 -2
  4. package/lib/cli/ipc-subcommands.js +84 -4
  5. package/lib/daemon.js +111 -7
  6. package/lib/effective-protocol.js +82 -0
  7. package/lib/project-connection.js +21 -8
  8. package/lib/project-filesystem.js +4 -4
  9. package/lib/project-http.js +4 -4
  10. package/lib/project-loop.js +49 -5
  11. package/lib/project-sessions.js +166 -68
  12. package/lib/project-user-mention.js +7 -7
  13. package/lib/project-user-message.js +81 -14
  14. package/lib/project.js +28 -22
  15. package/lib/public/app.js +18 -4
  16. package/lib/public/css/base.css +14 -0
  17. package/lib/public/css/filebrowser.css +6 -0
  18. package/lib/public/css/home-hub.css +28 -8
  19. package/lib/public/css/icon-strip.css +17 -0
  20. package/lib/public/css/messages.css +11 -0
  21. package/lib/public/css/mobile-nav.css +22 -0
  22. package/lib/public/css/server-settings.css +9 -0
  23. package/lib/public/css/sidebar.css +15 -0
  24. package/lib/public/css/title-bar.css +10 -1
  25. package/lib/public/index.html +9 -2
  26. package/lib/public/modules/activity-latch.js +45 -0
  27. package/lib/public/modules/activity-state.js +195 -0
  28. package/lib/public/modules/app-connection.js +31 -6
  29. package/lib/public/modules/app-favicon.js +75 -1
  30. package/lib/public/modules/app-home-hub.js +14 -11
  31. package/lib/public/modules/app-loop-ui.js +86 -2
  32. package/lib/public/modules/app-messages.js +178 -54
  33. package/lib/public/modules/app-panels.js +91 -32
  34. package/lib/public/modules/app-projects.js +46 -9
  35. package/lib/public/modules/app-rate-limit.js +13 -1
  36. package/lib/public/modules/server-settings.js +256 -21
  37. package/lib/public/modules/sidebar-mobile.js +32 -22
  38. package/lib/public/modules/sidebar-projects.js +42 -14
  39. package/lib/public/modules/sidebar-sessions.js +168 -48
  40. package/lib/public/modules/theme.js +2 -2
  41. package/lib/public/modules/tools.js +11 -39
  42. package/lib/sdk-bridge.js +375 -33
  43. package/lib/sdk-message-processor.js +98 -15
  44. package/lib/sdk-skill-discovery.js +46 -6
  45. package/lib/sdk-slash-enrichment.js +5 -2
  46. package/lib/server-dm.js +5 -5
  47. package/lib/server-hub-sessions.js +70 -0
  48. package/lib/server.js +78 -43
  49. package/lib/session-activity.js +9 -2
  50. package/lib/sessions.js +64 -18
  51. package/lib/smtp.js +10 -1
  52. package/lib/terminal-manager.js +6 -6
  53. package/lib/ws-schema.js +16 -0
  54. package/lib/yoke/adapters/claude.js +7 -1
  55. package/lib/yoke/adapters/codex.js +219 -31
  56. package/package.json +2 -2
  57. package/scripts/check-test-count.js +397 -0
  58. package/scripts/test-file-completion-reporter.js +43 -0
  59. package/scripts/verify-installed-build.js +242 -15
  60. package/lib/model-context-windows.js +0 -74
  61. package/lib/public/modules/model-context-windows.js +0 -71
@@ -35,7 +35,7 @@ import { handleAgentsList, handleAgentFavoriteToggled } from './agent-picker.js'
35
35
  import { handleProjectAgentsList, requestProjectAgents } from './at-agents.js';
36
36
  import { handleFindInSessionResults } from './session-search.js';
37
37
  import { handleInputSync, autoResize, resetAutoResize, builtinCommands, setScheduleBtnDisabled } from './input.js';
38
- import { startThinking, appendThinking, stopThinking, resetThinkingGroup, createToolItem, updateToolExecuting, updateToolResult, markAllToolsDone, closeToolGroup, removeToolFromGroup, resetToolState, getTools, getPlanContent, setPlanContent, renderPlanBanner, renderPlanCard, getTodoTools, handleTodoWrite, handleTaskCreate, handleTaskUpdate, applyDeadSessionTodoCompaction, isPlanFilePath, enableMainInput, addTurnMeta, updateSubagentActivity, addSubagentToolEntry, markSubagentDone, initSubagentStop, updateSubagentProgress, updateSubagentTaskStatus, hasActiveSubagents, renderAskUserQuestion, markAskUserAnswered, renderPermissionRequest, markPermissionCancelled, markPermissionResolved, renderElicitationRequest, markElicitationResolved } from './tools.js';
38
+ import { startThinking, appendThinking, stopThinking, resetThinkingGroup, createToolItem, updateToolExecuting, updateToolResult, markAllToolsDone, closeToolGroup, removeToolFromGroup, resetToolState, getTools, getPlanContent, setPlanContent, renderPlanBanner, renderPlanCard, getTodoTools, handleTodoWrite, handleTaskCreate, handleTaskUpdate, applyDeadSessionTodoCompaction, isPlanFilePath, enableMainInput, addTurnMeta, updateSubagentActivity, addSubagentToolEntry, markSubagentDone, initSubagentStop, updateSubagentProgress, updateSubagentTaskStatus, renderAskUserQuestion, markAskUserAnswered, renderPermissionRequest, markPermissionCancelled, markPermissionResolved, renderElicitationRequest, markElicitationResolved } from './tools.js';
39
39
  import { showDoneNotification, playDoneSound, isNotifAlertEnabled, isNotifSoundEnabled } from './notifications.js';
40
40
  import { handleFsRead, refreshIfOpen } from './filebrowser.js';
41
41
  import { isProjectSettingsOpen, refreshProjectSettingsModels, handleInstructionsRead, handleInstructionsWrite, handleProjectEnv, handleProjectEnvSaved, handleProjectSharedEnv, handleProjectSharedEnvSaved, handleProjectOwnerChanged, updateLiteVisibility, handleLiteProjectStatus, handleLiteEnrollResult, handleLiteUnenrollResult } from './project-settings.js';
@@ -53,7 +53,7 @@ import { handleLoopRegistryUpdated, handleScheduleRunStarted, handleScheduleRunF
53
53
 
54
54
  // --- App module imports ---
55
55
  import { scrollToBottom, addToMessages, addUserMessage, addSystemMessage, appendDelta, finalizeAssistantBlock, addConflictMessage, addContextOverflowMessage, showSuggestionChips, removePreThinking } from './app-rendering.js';
56
- import { setActivity, startUrgentBlink, stopUrgentBlink, blinkSessionDot, updateCrossProjectBlink } from './app-favicon.js';
56
+ import { startUrgentBlink, stopUrgentBlink, blinkSessionDot, updateCrossProjectBlink, reconcileActivityFooter } from './app-favicon.js';
57
57
  import { setStatus } from './app-connection.js';
58
58
  import { getModelEffortLevels, accumulateUsage, setSessionUsage, updateUsagePanel, accumulateContext, updateContextPanel, renderCtxPopover, updateStatusPanel } from './app-panels.js';
59
59
  import { updateProjectList, resetClientState, showUpdateAvailable, handleRemoveProjectCheckResult, handleRemoveProjectResult, handleBrowseDirResult, handleAddProjectResult, handleCloneProgress } from './app-projects.js';
@@ -69,6 +69,8 @@ import { handleMentionStart, handleMentionActivity, handleMentionStream, handleM
69
69
  import { handleTeamState, handleTeamMemberUpdate, handleTeamTaskUpdate, handleTeamMessage as handleTeamMsg, handleTeamGone } from './team-panel.js';
70
70
  import { addDiagnostic } from './diagnostics.js';
71
71
  import { handleHistoryMeta, handleHistoryDone } from './app-history-replay.js';
72
+ import { shouldApplyActivityEdge } from './activity-latch.js';
73
+ import { deriveSessionListProcessing } from './activity-state.js';
72
74
 
73
75
  // --- DOM refs (cached once, stable for page lifetime) ---
74
76
  var messagesEl = document.getElementById("messages");
@@ -378,6 +380,58 @@ registerHandlers({
378
380
  session_list: function (msg) {
379
381
  renderSessionList(msg.sessions || []);
380
382
  handlePaletteSessionSwitch();
383
+ // lr-5edd64: 'processing' (the transcript footer's field) is now a pure
384
+ // PROJECTION of server-authoritative per-session state — nothing writes
385
+ // it independently anymore (see activity-latch.js's header comment for
386
+ // what this replaced). session_list already carries per-session
387
+ // isProcessing to EVERY client regardless of which session that client
388
+ // has focused (lib/sessions.js broadcastSessionList/mapSessionForClient
389
+ // is not scoped by ws._clagenticActiveSession the way status/done/
390
+ // auth_required sends are) — this is what makes re-deriving here, on
391
+ // every list broadcast, correct for a session whose activity edge this
392
+ // client's own WS connection never received (MILLER lr-5edd64 comment
393
+ // #3, candidate 1: the server-side ws._clagenticActiveSession send filter,
394
+ // not the client-side latch, was dropping the edge before it ever
395
+ // arrived). The other query/snapshot half of the projection is
396
+ // session_switched (below), covering reconnect/switch/hydration.
397
+ // Bounded to the entry matching activeSessionId; store.set() and the
398
+ // footer's own subscriber both already no-op on an unchanged value
399
+ // (lr-9bcd7b's changed-flag bounding), so this cannot introduce a
400
+ // spurious render on every roster broadcast.
401
+ //
402
+ // { ignoreUnread: true } (PEACHES finding 2, lr-5edd64 8th recurrence):
403
+ // the transcript footer is a "a turn is running" indicator, not an
404
+ // unread-alert surface — it has no unread badge affordance of its own,
405
+ // unlike the sidebar/hub dots this same sessionActivity() call also
406
+ // drives. Without this, sessionActivity()'s alert>processing precedence
407
+ // (activity-state.js's LOCKED rule) makes .active true whenever
408
+ // unread>0 REGARDLESS of isProcessing, so a session with isProcessing
409
+ // false and unread>0 pins the footer on with no turn running — the
410
+ // exact "processing dot when idle" symptom this task's operator
411
+ // report described. session_switched's own projection (below) reads
412
+ // sessionIsProcessing directly, which is already immune to this
413
+ // conflation; this call site now matches it. This narrows
414
+ // activity-state.js's documented ignoreUnread contract ("session-level
415
+ // dots never set this" — see its header) for this ONE session-level
416
+ // consumer, since the footer is a processing indicator, not a dot with
417
+ // its own alert affordance; see that header comment for the updated
418
+ // contract.
419
+ // Derivation itself lives in activity-state.js's deriveSessionListProcessing
420
+ // (extracted, not inlined here) specifically so a test can import and
421
+ // exercise this exact production logic directly — app-messages.js is
422
+ // not importable under plain Node (see that function's own doc comment
423
+ // for why), so leaving this inline would leave only a hand-copied
424
+ // reimplementation testable, not the shipped code.
425
+ var _projection = deriveSessionListProcessing(msg.sessions || [], store.get('activeSessionId'));
426
+ if (_projection.found) {
427
+ store.set({ processing: _projection.active });
428
+ // lr-5edd64 (9th recurrence): reconcile the footer's DOM ref
429
+ // unconditionally, not only when store.set() actually changed the
430
+ // value — see app-favicon.js's reconcileActivityFooter() doc for why
431
+ // an unchanged-but-still-true value can otherwise leave a ref nulled
432
+ // by resetClientState() permanently unrepaired.
433
+ reconcileActivityFooter();
434
+ }
381
435
  // Drain pending hub cross-project session switch (set by handleHubRecentSessions
382
436
  // when switching to a session in a different project). Fires here because
383
437
  // session_list is the first reliable post-connect message that guarantees
@@ -442,7 +496,22 @@ registerHandlers({
442
496
  } else if (_prevSid) {
443
497
  delete store.get('sessionDrafts')[_prevSid];
444
498
  }
499
+ // Reconcile the footer's edge-latch field from the server-authoritative
500
+ // snapshot on every session switch/hydration, not only
501
+ // sessionIsProcessing. 'processing' (the field app-favicon.js's
502
+ // initActivityFooter subscribes to) was a pure client-local edge latch
503
+ // with no reconciliation path — missing a single 1->0 done edge (e.g. a
504
+ // cross-session race, see the session-scoping fix in the status/done/
505
+ // auth_required handlers below) left it stuck true forever.
506
+ // session_switched now always carries msg.isProcessing
507
+ // (project-connection.js's hydration path previously omitted it —
508
+ // sessions.js's own switchSession() send already had it).
445
509
  store.set({ activeSessionId: msg.id, cliSessionId: msg.cliSessionId || null, vendorCapabilities: msg.capabilities || {}, sessionIsProcessing: !!msg.isProcessing });
510
+ // NOTE: the 'processing' projection itself is applied further down,
511
+ // AFTER resetClientState() (PEACHES finding 1, lr-5edd64 8th
512
+ // recurrence) — see the comment down there for why the ordering
513
+ // matters. Do not move this store.set({ processing: ... }) back up
514
+ // here without re-reading that comment.
446
515
  if (msg.vendor) {
447
516
  if (!store.get('vendorSelectionLocked') || msg.hasHistory) {
448
517
  store.set({ currentVendor: msg.vendor });
@@ -481,6 +550,37 @@ registerHandlers({
481
550
  // Session presence is now tracked server-side (user-presence.json)
482
551
  clearRemoteCursors();
483
552
  resetClientState();
553
+ // Re-derive 'processing' from sessionIsProcessing (set above), NOT from
554
+ // a second raw msg.isProcessing read — this file's CI invariant test
555
+ // locks .isProcessing reads to exactly the one documented site above,
556
+ // so every switch/reconnect/hydration re-derives 'processing' from that
557
+ // already-read, already-reconciled value instead of trusting whatever
558
+ // the client-local latch happened to be left at.
559
+ //
560
+ // Applied HERE, AFTER resetClientState(), not right after
561
+ // sessionIsProcessing is set above (PEACHES finding 1, lr-5edd64 8th
562
+ // recurrence): resetClientState() calls setActivityEl(null), nulling the
563
+ // footer widget's DOM ref, and wipes the transcript DOM outright. Running
564
+ // the projection after the reset means the incoming session's own
565
+ // transcript DOM already exists by the time the footer is (re)rendered.
566
+ //
567
+ // The render call itself is UNCONDITIONAL (lr-5edd64, 9th recurrence —
568
+ // PEACHES BLOCKING on PR #410 + HOLDEN's trace), not left to
569
+ // initActivityFooter's ['processing'] value-change subscriber: on a
570
+ // true->true session switch (outgoing session processing, incoming
571
+ // session also processing) store.set() below does not change the value,
572
+ // so a value-change subscriber alone would never fire and the ref
573
+ // resetClientState() just nulled would never get repaired — stuck OFF
574
+ // forever, the exact inverse of the stuck-ON failure this redesign
575
+ // exists to close (see finding 1's fix above, which fixed false->true
576
+ // and left true->true broken this same way). reconcileActivityFooter()
577
+ // renders unconditionally from current store.processing instead of
578
+ // depending on a transition firing — see its doc comment in
579
+ // app-favicon.js. This does not defeat lr-9bcd7b's changed-flag
580
+ // bounding on store.set()/the subscriber, which still exists and still
581
+ // suppresses spurious renders on unrelated store updates.
582
+ store.set({ processing: store.get('sessionIsProcessing') });
583
+ reconcileActivityFooter();
484
584
  // lr-0827ba: redraw the incoming session's own armed rate-limit /
485
585
  // scheduled-message state (arming happens per-session in the
486
586
  // background regardless of focus — see rate-limit-state.js) instead
@@ -605,26 +705,43 @@ registerHandlers({
605
705
  },
606
706
 
607
707
  status: function (msg) {
708
+ // lr-5edd64: this handler no longer writes 'processing' (the transcript
709
+ // footer's field) — that is now a pure projection derived from
710
+ // session_list/session_switched (see those handlers). Session-scoping
711
+ // still gates the OTHER, non-render side effects below (sessionIsProcessing
712
+ // for dead-session-todo-compaction, and the pre-thinking-dots clear),
713
+ // mirroring the lr-0827ba pattern already used by scheduled_message_*
714
+ // handlers (msg.localId == null || msg.localId === activeSessionId) —
715
+ // a background session's status:"processing" must not touch state
716
+ // scoped to the FOCUSED session. msg.localId is always populated
717
+ // server-side (see sessions.js stampActivityLocalId / project.js
718
+ // sendToSession); a missing localId (e.g. an older server) falls back
719
+ // to applying unconditionally, same as before this fix.
608
720
  if (msg.status === "processing") {
609
- setStatus("processing");
610
- // Session became live — undo any dead-session todo compaction
611
- // applied at history_done time.
612
- store.set({ sessionIsProcessing: true });
613
- applyDeadSessionTodoCompaction();
614
- if (!store.get('dmMode')) {
615
- removePreThinking(); // drop pre-thinking dots before showing activity indicator
616
- setActivity("thinking");
721
+ if (shouldApplyActivityEdge(msg.localId, store.get('activeSessionId'))) {
722
+ // Session became live — undo any dead-session todo compaction
723
+ // applied at history_done time.
724
+ store.set({ sessionIsProcessing: true });
725
+ applyDeadSessionTodoCompaction();
726
+ if (!store.get('dmMode')) {
727
+ removePreThinking(); // drop pre-thinking dots before showing activity indicator
728
+ }
617
729
  }
618
730
  }
619
731
  },
620
732
 
621
- compacting: function (msg) {
622
- if (msg.active) {
623
- setActivity("compacting");
624
- } else if (!store.get('dmMode')) {
625
- setActivity("thinking");
626
- }
627
- },
733
+ // lr-66c118: setActivity("thinking"/"compacting") re-raise removed here.
734
+ // setActivity collapses to ONE optimistic raise (input.js, on send) — the
735
+ // widget's job is to bridge the gap before the FIRST real server signal
736
+ // arrives; once real streaming UI exists (thinking block, tool items,
737
+ // delta text) that IS the activity indicator, so re-raising the bubble
738
+ // widget mid-turn only risked stacking it on top of the real UI.
739
+ // lr-3af675: the context meter itself no longer needs anything here either
740
+ // — the server re-reads vendor usage on the compacting -> not-compacting
741
+ // transition and pushes a fresh 'context_usage' message (see the 'status'
742
+ // handler in sdk-message-processor.js), which the context_usage handler
743
+ // below already applies to the meter.
744
+ compacting: function (msg) {},
628
745
 
629
746
  thinking_start: function (msg) {
630
747
  removePreThinking();
@@ -637,9 +754,6 @@ registerHandlers({
637
754
 
638
755
  thinking_stop: function (msg) {
639
756
  stopThinking(msg.duration);
640
- if (!store.get('dmMode')) {
641
- setActivity("thinking");
642
- }
643
757
  },
644
758
 
645
759
  delta: function (msg) {
@@ -647,14 +761,12 @@ registerHandlers({
647
761
  removePreThinking();
648
762
  stopThinking();
649
763
  resetThinkingGroup();
650
- // lr-1317b8 (Defect 2): this was an ungated clear-site, missed by the
651
- // lr-255e clear-site audit. Any parent-turn assistant text delta after a
652
- // subagent dispatch (e.g. the model narrating between tool calls) killed
653
- // the indicator while the subagent was still genuinely running. Same
654
- // guard as the 'result'/'done' handlers below.
655
- if (!hasActiveSubagents()) {
656
- setActivity(null);
657
- }
764
+ // lr-66c118: the setActivity clear-call removed here (was gated on
765
+ // hasActiveSubagents() per lr-1317b8 Defect 2 — that gate is now moot,
766
+ // there is nothing left to clear here). setActivity collapses to ONE
767
+ // optimistic raise (input.js); real streaming text arriving is itself
768
+ // the strongest possible "not idle" signal, so there is no risk of a
769
+ // stuck indicator from removing this clear.
658
770
  appendDelta(msg.text);
659
771
  },
660
772
 
@@ -806,16 +918,11 @@ registerHandlers({
806
918
  },
807
919
 
808
920
  result: function (msg) {
809
- // lr-255e: the parent turn's SDK stream ends with a normal 'result' as
810
- // soon as a Task tool call is dispatched -- the Task itself keeps
811
- // running as a background subagent. Clearing the activity indicator
812
- // unconditionally here made the "thinking dots" vanish while a
813
- // dispatched subagent was still genuinely working. Only clear it if no
814
- // subagent is currently live; markSubagentDone() clears it once the
815
- // last live subagent actually finishes.
816
- if (!hasActiveSubagents()) {
817
- setActivity(null);
818
- }
921
+ // lr-66c118: the lr-255e hasActiveSubagents()-gated setActivity clear
922
+ // call is removed — setActivity collapses to ONE optimistic raise
923
+ // (input.js) with no manual clears anywhere. The subagent-liveness
924
+ // tracking itself (activeSubagentToolIds, markSubagentDone) is untouched
925
+ // and still governs the real per-tool subagent UI.
819
926
  stopThinking();
820
927
  markAllToolsDone();
821
928
  closeToolGroup();
@@ -832,23 +939,22 @@ registerHandlers({
832
939
  }
833
940
  },
834
941
 
942
+ // lr-5edd64: this handler no longer writes 'processing' — it is now a
943
+ // pure projection derived from session_list/session_switched (see those
944
+ // handlers). Every cleanup call below is unconditional: it targets
945
+ // DOM/tool state for whatever session this client's own WS connection is
946
+ // bound to server-side (ws._clagenticActiveSession), so it is never
947
+ // cross-session — there was no other session-scoped state to guard here
948
+ // once the store-wide latch write is gone.
835
949
  done: function (msg) {
836
950
  removePreThinking();
837
- // lr-255e: 'done' can also fire while a backgrounded Task subagent is
838
- // still genuinely running (task-stop/error/abort paths that bypass the
839
- // 'result' handler never clear activeTaskToolIds). Same rule as the
840
- // 'result' handler: don't kill the indicator out from under a live
841
- // subagent. resetToolState() below intentionally still clears all
842
- // per-turn tool tracking (including subagent liveness) once this
843
- // handler is done deciding whether to clear the indicator.
844
- if (!hasActiveSubagents()) {
845
- setActivity(null);
846
- }
951
+ // lr-66c118: the setActivity clear call is removed here too — see the
952
+ // 'result' handler above. resetToolState() below still clears all
953
+ // per-turn tool tracking (including subagent liveness) unconditionally.
847
954
  stopThinking();
848
955
  markAllToolsDone();
849
956
  closeToolGroup();
850
957
  finalizeAssistantBlock();
851
- setStatus("connected");
852
958
  // Re-enable input unless this is one of the loop's own sessions (coder/judge).
853
959
  // A loop running in a separate session must not suppress input here.
854
960
  var _doneLoopSid = store.get('loopCurrentSessionId');
@@ -867,9 +973,11 @@ registerHandlers({
867
973
  addSystemMessage(msg.text, false);
868
974
  },
869
975
 
976
+ // lr-66c118: setActivity clear calls removed below (error,
977
+ // process_conflict, context_overflow, auth_required) — setActivity
978
+ // collapses to ONE optimistic raise (input.js) with no manual clears.
870
979
  error: function (msg) {
871
980
  removePreThinking();
872
- setActivity(null);
873
981
  addSystemMessage(msg.text, true);
874
982
  },
875
983
 
@@ -883,24 +991,23 @@ registerHandlers({
883
991
 
884
992
  process_conflict: function (msg) {
885
993
  removePreThinking();
886
- setActivity(null);
887
994
  addConflictMessage(msg);
888
995
  },
889
996
 
890
997
  context_overflow: function (msg) {
891
998
  removePreThinking();
892
- setActivity(null);
893
999
  addContextOverflowMessage(msg);
894
1000
  },
895
1001
 
1002
+ // lr-5edd64: no longer session-scope-guards a 'processing' write here —
1003
+ // that field is now a pure projection (see session_list/session_switched
1004
+ // handlers), and nothing else in this handler was gated by the guard.
896
1005
  auth_required: function (msg) {
897
1006
  removePreThinking();
898
- setActivity(null);
899
1007
  stopThinking();
900
1008
  markAllToolsDone();
901
1009
  closeToolGroup();
902
1010
  appendDelta((msg.text || "Authentication required.") + "\n");
903
- setStatus("connected");
904
1011
  var _authLoopSid = store.get('loopCurrentSessionId');
905
1012
  if (!store.get('loopActive') || !_authLoopSid || store.get('activeSessionId') !== _authLoopSid) {
906
1013
  enableMainInput();
@@ -1240,6 +1347,20 @@ registerHandlers({
1240
1347
  // loop's own session — updateLoopInputVisibility() already switched
1241
1348
  // it into queue mode so a human message is queued for the next
1242
1349
  // iteration boundary rather than dropped or blocked outright.
1350
+ //
1351
+ // lr-fd38ac follow-up: loopCurrentSessionId (set just above) is what
1352
+ // makes updateLoopInputVisibility()'s gate condition
1353
+ // (loopCurrentSessionId === activeSessionId) newly true when a
1354
+ // client is already viewing the loop's new session — the
1355
+ // session_switched broadcast that forced every client onto this
1356
+ // session fired earlier with loop: null (session.loop is assigned
1357
+ // server-side only after createSession() returns; see
1358
+ // project-loop.js runNextIteration()), so that call armed nothing.
1359
+ // The re-invocation itself lives in app-loop-ui.js's reactive
1360
+ // store.subscribe(), keyed on loopActive/loopCurrentSessionId, so
1361
+ // every writer of those two fields (this handler, loop_judging,
1362
+ // loop_finished) gets the re-check for free instead of each call
1363
+ // site having to remember to do it.
1243
1364
  },
1244
1365
 
1245
1366
  loop_judging: function (msg) {
@@ -1248,6 +1369,9 @@ registerHandlers({
1248
1369
  updateLoopBanner(_ljs.loopIteration, _ljs.loopMaxIterations, "judging");
1249
1370
  addSystemMessage("Judging iteration #" + msg.iteration + "...", false);
1250
1371
  // lr-e31b: composer stays enabled in queue mode (see loop_iteration above).
1372
+ // lr-fd38ac follow-up: same re-arm requirement as loop_iteration —
1373
+ // loopCurrentSessionId changes to the judge session here, and the
1374
+ // reactive subscriber in app-loop-ui.js re-checks the gate.
1251
1375
  },
1252
1376
 
1253
1377
  loop_verdict: function (msg) {
@@ -6,7 +6,6 @@ import { escapeHtml, showToast } from "./utils.js";
6
6
  import { store } from './store.js';
7
7
  import { getWs } from './ws-ref.js';
8
8
  import { VENDOR_NAMES } from './app-rendering.js';
9
- import { KNOWN_CONTEXT_WINDOWS, resolveModelContextWindow as _resolveModelContextWindowCore } from './model-context-windows.js';
10
9
  import { splitModelsByTier } from './settings-defaults.js';
11
10
  import { isSonnetModel } from './model-families.js';
12
11
 
@@ -14,7 +13,7 @@ import { isSonnetModel } from './model-families.js';
14
13
  // sessionUsage.context = last-turn context fill (lastStreamInputTokens) — not cumulative,
15
14
  // just the most recent value. Correct for display without any accumulation issues.
16
15
  var sessionUsage = { cost: 0, context: 0, output: 0, cacheWrite: 0, turns: 0 };
17
- var contextData = { contextWindow: 0, maxOutputTokens: 0, model: "-", cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
16
+ var contextData = { contextWindow: 0, maxOutputTokens: 0, model: "-", cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoningOutput: 0, turns: 0 };
18
17
  var ctxPopoverEl = null;
19
18
  var ctxHoverTimer = null;
20
19
  var statusRefreshTimer = null;
@@ -77,6 +76,7 @@ var contextCacheWriteEl = null;
77
76
  var contextModelEl = null;
78
77
  var contextCostEl = null;
79
78
  var contextTurnsEl = null;
79
+ var contextReasoningEl = null;
80
80
  var contextMini = null;
81
81
  var contextMiniFill = null;
82
82
  var contextMiniLabel = null;
@@ -109,7 +109,6 @@ var CODEX_WEBSEARCH_OPTIONS = [
109
109
  { value: "cached", label: "Cached" },
110
110
  { value: "live", label: "Live" },
111
111
  ];
112
- // KNOWN_CONTEXT_WINDOWS imported from ./model-context-windows.js (lr-336f shared source of truth)
113
112
  // Categories to hide from the legend (noise, not actionable)
114
113
  var CTX_HIDDEN_CATS = { "Free space": 1, "Autocompact buffer": 1 };
115
114
 
@@ -565,6 +564,7 @@ export function initPanels() {
565
564
  contextModelEl = $("context-model");
566
565
  contextCostEl = $("context-cost");
567
566
  contextTurnsEl = $("context-turns");
567
+ contextReasoningEl = $("context-reasoning");
568
568
  contextMini = $("context-mini");
569
569
  contextMiniFill = $("context-mini-fill");
570
570
  contextMiniLabel = $("context-mini-label");
@@ -773,13 +773,15 @@ export function accumulateUsage(cost, usage, lastStreamInputTokens) {
773
773
  // context: current context window fill from the last message_start event.
774
774
  // This is the same value used by the context bar. Assign (not sum) — it represents
775
775
  // the current state of the context window, not a cumulative total.
776
- // Prefer lastStreamInputTokens (accurate per-call); fall back to input+cache_read.
776
+ // Prefer lastStreamInputTokens (accurate per-call); fall back to input+cache_read+cache_creation
777
+ // (lr-3af675: the three usage fields are disjoint and all occupy the window).
777
778
  if (lastStreamInputTokens) {
778
779
  sessionUsage.context = lastStreamInputTokens;
779
780
  } else if (usage) {
780
781
  var directIn = usage.input_tokens || usage.inputTokens || 0;
781
782
  var cacheIn = usage.cache_read_input_tokens || usage.cacheReadInputTokens || 0;
782
- if (directIn + cacheIn > 0) sessionUsage.context = directIn + cacheIn;
783
+ var cacheCreate = usage.cache_creation_input_tokens || usage.cacheCreationInputTokens || 0;
784
+ if (directIn + cacheIn + cacheCreate > 0) sessionUsage.context = directIn + cacheIn + cacheCreate;
783
785
  }
784
786
  sessionUsage.turns++;
785
787
  if (!store.get('replayingHistory')) updateUsagePanel();
@@ -855,44 +857,73 @@ export function toggleStatusPanel() {
855
857
 
856
858
  // --- Context panel ---
857
859
 
858
- export function resolveContextWindow(model, sdkValue) {
859
- // Build the active betas array from store so we can delegate to the shared
860
- // core (lr-336f) which is store-agnostic and usable on both backend and frontend.
861
- var activeBetas = store.get('currentBetas') || [];
862
- // Delegate to shared core: beta-first, then [1m] suffix, then map lookup.
863
- // Core returns 0 for unknown models; apply frontend-specific fallbacks here.
864
- var coreResult = _resolveModelContextWindowCore(model, activeBetas);
865
- if (coreResult > 0) return coreResult;
866
- // sdkValue fallback: prefer the SDK-reported window when the model is not in the
867
- // shared map (new models, vendor-specific entries). Returns 200000 as last resort.
868
- if (sdkValue) return sdkValue;
869
- return 200000;
860
+ /**
861
+ * lr-3af675: vendor-first context-window resolution. The hardcoded
862
+ * model-name -> window table (lib/model-context-windows.js) is gone — both
863
+ * providers report their own context window, and that report is the only
864
+ * value this function ever returns.
865
+ *
866
+ * vendorWindow: the window size as reported by the vendor for the CURRENT
867
+ * turn/session (Claude: modelUsage.contextWindow or getContextUsage()'s
868
+ * maxTokens; Codex: modelUsage.contextWindow, sourced from
869
+ * ThreadTokenUsage.modelContextWindow on thread/tokenUsage/updated —
870
+ * lr-872f94 — absent until the app-server reports one for the session).
871
+ *
872
+ * Returns the vendor-reported window, or 0 when none is available (no
873
+ * completed turn yet, a resumed session before its first result, a daemon
874
+ * restart, or a vendor that hasn't reported one). Callers MUST treat 0 as
875
+ * "unknown" and render an indeterminate state — never substitute a guess.
876
+ */
877
+ export function resolveContextWindow(vendorWindow) {
878
+ return (typeof vendorWindow === "number" && vendorWindow > 0) ? vendorWindow : 0;
870
879
  }
871
880
 
872
881
  export function contextPctClass(pct) {
873
882
  return pct >= 85 ? " danger" : pct >= 60 ? " warn" : "";
874
883
  }
875
884
 
885
+ /**
886
+ * lr-3af675: the effective (used, window) pair the meter renders from.
887
+ * Prefers the rich context-usage breakdown (store.richContextUsage) when
888
+ * present — it is the freshest vendor read, including immediately after a
889
+ * compaction re-read (see the 'status' handler re-fetch in
890
+ * sdk-message-processor.js) — and falls back to the per-turn contextData
891
+ * accumulated from 'result' events. Both sources are vendor-first; neither
892
+ * ever substitutes a guessed window.
893
+ *
894
+ * Exported so every consumer of the meter (header bar, popover, panel, and
895
+ * the tools.js clear-context label) reads the exact same (used, win) pair
896
+ * instead of each recomputing its own view and risking disagreement.
897
+ */
898
+ export function getEffectiveContextFill() {
899
+ var rich = store.get('richContextUsage');
900
+ if (rich && typeof rich.totalTokens === "number") {
901
+ var richWin = resolveContextWindow(rich.maxTokens);
902
+ if (richWin > 0) return { used: rich.totalTokens, win: richWin };
903
+ }
904
+ return { used: contextData.input, win: resolveContextWindow(contextData.contextWindow) };
905
+ }
906
+
876
907
  export function updateContextPanel() {
877
908
  if (!contextUsedEl) return;
878
- // Context window usage = input tokens only (includes cache read/write)
879
- var used = contextData.input;
880
- // Re-resolve each paint so beta changes (e.g. context-1m toggle) are
881
- // reflected immediately without waiting for the next turn's result event.
882
- var win = resolveContextWindow(contextData.model, contextData.contextWindow);
909
+ var fill = getEffectiveContextFill();
910
+ var used = fill.used;
911
+ var win = fill.win;
883
912
  var pct = win > 0 ? Math.min(100, (used / win) * 100) : 0;
884
913
  var cls = contextPctClass(pct);
885
914
  // Panel bar
886
915
  contextBarFill.style.width = pct.toFixed(1) + "%";
887
916
  contextBarFill.className = "context-bar-fill" + cls;
888
- contextBarPct.textContent = pct.toFixed(0) + "%";
917
+ // lr-3af675: unknown window -> "-", never a fabricated "0%".
918
+ contextBarPct.textContent = win > 0 ? pct.toFixed(0) + "%" : "-";
889
919
  // Mini bar
890
920
  if (contextMiniFill) {
891
921
  contextMiniFill.style.width = pct.toFixed(1) + "%";
892
922
  contextMiniFill.className = "context-mini-fill" + cls;
893
923
  }
894
924
  if (contextMiniLabel) {
895
- contextMiniLabel.textContent = (win > 0 ? formatTokens(used) + "/" + formatTokens(win) : "0%");
925
+ // lr-3af675: unknown window -> "-", never a fabricated "0%".
926
+ contextMiniLabel.textContent = (win > 0 ? formatTokens(used) + "/" + formatTokens(win) : "-");
896
927
  }
897
928
  // Header bar
898
929
  if (pct > 0) {
@@ -934,6 +965,19 @@ export function updateContextPanel() {
934
965
  if (contextOutputEl) contextOutputEl.textContent = formatTokens(contextData.output);
935
966
  if (contextCacheReadEl) contextCacheReadEl.textContent = formatTokens(contextData.cacheRead);
936
967
  if (contextCacheWriteEl) contextCacheWriteEl.textContent = formatTokens(contextData.cacheWrite);
968
+ // lr-872f94: reasoning tokens are a real Codex-specific spend category
969
+ // (thread/tokenUsage/updated's reasoningOutputTokens) that was previously
970
+ // invisible to users. Row is hidden (not just "-") when a vendor hasn't
971
+ // reported any, so Claude sessions don't show a permanently-zero row.
972
+ if (contextReasoningEl) {
973
+ var reasoningRow = contextReasoningEl.closest(".usage-row");
974
+ if (contextData.reasoningOutput > 0) {
975
+ contextReasoningEl.textContent = formatTokens(contextData.reasoningOutput);
976
+ if (reasoningRow) reasoningRow.classList.remove("hidden");
977
+ } else if (reasoningRow) {
978
+ reasoningRow.classList.add("hidden");
979
+ }
980
+ }
937
981
  contextModelEl.textContent = contextData.model;
938
982
  var vendor = store.get('currentVendor');
939
983
  contextCostEl.textContent = (vendor === 'codex' || contextData.cost == null)
@@ -955,12 +999,20 @@ export function accumulateContext(cost, usage, modelUsage, lastStreamInputTokens
955
999
  if (lastStreamInputTokens) {
956
1000
  contextData.input = lastStreamInputTokens;
957
1001
  } else {
1002
+ // lr-3af675: input_tokens, cache_read_input_tokens, and
1003
+ // cache_creation_input_tokens are disjoint and all three occupy the
1004
+ // context window -- cache_creation_input_tokens was previously
1005
+ // omitted here, under-reporting fill on cache-write-heavy turns.
958
1006
  contextData.input = (usage.input_tokens || usage.inputTokens || 0)
959
- + (usage.cache_read_input_tokens || usage.cacheReadInputTokens || 0);
1007
+ + (usage.cache_read_input_tokens || usage.cacheReadInputTokens || 0)
1008
+ + (usage.cache_creation_input_tokens || usage.cacheCreationInputTokens || 0);
960
1009
  }
961
1010
  contextData.output = usage.output_tokens || usage.outputTokens || 0;
962
1011
  contextData.cacheRead = usage.cache_read_input_tokens || usage.cacheReadInputTokens || 0;
963
1012
  contextData.cacheWrite = usage.cache_creation_input_tokens || usage.cacheCreationInputTokens || 0;
1013
+ // lr-872f94: Codex-specific reasoning token spend (previously discarded).
1014
+ // No cumulative concept here, matching the other per-turn fields above.
1015
+ contextData.reasoningOutput = usage.reasoning_output_tokens || usage.reasoningOutputTokens || 0;
964
1016
  }
965
1017
  contextData.turns++;
966
1018
  if (modelUsage) {
@@ -972,7 +1024,12 @@ export function accumulateContext(cost, usage, modelUsage, lastStreamInputTokens
972
1024
  // (e.g. CLI reports "claude-sonnet-4-6" even when running as opus[1m])
973
1025
  var displayModel = store.get('currentModel') || m;
974
1026
  contextData.model = displayModel;
975
- contextData.contextWindow = resolveContextWindow(displayModel, mu.contextWindow);
1027
+ // lr-3af675: vendor-first, no hardcoded table. mu.contextWindow is the
1028
+ // vendor's own reported window for this model; resolveContextWindow no
1029
+ // longer does anything but validate it's a positive number. Absent a
1030
+ // vendor value, contextWindow stays 0 ("unknown") -- render blank, not
1031
+ // a guess.
1032
+ contextData.contextWindow = resolveContextWindow(mu.contextWindow);
976
1033
  if (mu.maxOutputTokens) contextData.maxOutputTokens = mu.maxOutputTokens;
977
1034
  }
978
1035
  }
@@ -995,7 +1052,7 @@ export function applyContextView(view) {
995
1052
  }
996
1053
 
997
1054
  export function resetContextData() {
998
- contextData = { contextWindow: 0, maxOutputTokens: 0, model: "-", cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
1055
+ contextData = { contextWindow: 0, maxOutputTokens: 0, model: "-", cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoningOutput: 0, turns: 0 };
999
1056
  store.set({ richContextUsage: null });
1000
1057
  // hideCtxPopover + updateContextPanel handled by store subscriber
1001
1058
  }
@@ -1066,9 +1123,10 @@ export function renderCtxPopover() {
1066
1123
  var d = richContextUsage;
1067
1124
  var cats = d.categories || [];
1068
1125
  var total = d.totalTokens || 0;
1069
- // SDK reports the model's base window in maxTokens; override with the
1070
- // beta-aware resolved window so 1M sessions show the correct denominator.
1071
- var max = resolveContextWindow(d.model || contextData.model, d.maxTokens || 0);
1126
+ // lr-3af675: vendor-first -- d.maxTokens is the SDK's own reported window
1127
+ // (already reflects any active beta, e.g. context-1m) and needs no local
1128
+ // override. resolveContextWindow now only validates it's a positive number.
1129
+ var max = resolveContextWindow(d.maxTokens);
1072
1130
  var pct = max > 0 ? Math.min(100, (total / max) * 100) : (d.percentage != null ? d.percentage : 0);
1073
1131
 
1074
1132
  var html = "";
@@ -1076,8 +1134,9 @@ export function renderCtxPopover() {
1076
1134
  // Header
1077
1135
  html += '<div class="ctx-pop-header">';
1078
1136
  html += '<span class="ctx-pop-model">' + escHtml(d.model || contextData.model || "-") + '</span>';
1079
- html += '<span class="ctx-pop-pct">' + pct.toFixed(0) + '%';
1080
- html += '<span class="ctx-pop-tokens">' + formatTokens(total) + ' / ' + formatTokens(max) + '</span>';
1137
+ // lr-3af675: unknown window -> "-", never a fabricated "0%"/0 denominator.
1138
+ html += '<span class="ctx-pop-pct">' + (max > 0 ? pct.toFixed(0) + '%' : '-');
1139
+ html += '<span class="ctx-pop-tokens">' + formatTokens(total) + ' / ' + (max > 0 ? formatTokens(max) : '-') + '</span>';
1081
1140
  html += '</span>';
1082
1141
  html += '</div>';
1083
1142