@zergai/ztc 0.25.0-beta.1 → 0.26.0-beta.1

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 (38) hide show
  1. package/README.md +70 -0
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/app/emergency_exit.d.ts +14 -0
  8. package/dist/app/emergency_exit.js +36 -0
  9. package/dist/app/layout_change.d.ts +20 -0
  10. package/dist/app/layout_change.js +14 -0
  11. package/dist/app/workspace_topology.d.ts +8 -0
  12. package/dist/app/workspace_topology.js +8 -0
  13. package/dist/cli_main.js +2 -24
  14. package/dist/cli_ratatui.d.ts +70 -1
  15. package/dist/cli_ratatui.js +259 -53
  16. package/dist/desktop/daily/status_restore.js +6 -2
  17. package/dist/mcp/workspace_server.js +9 -2
  18. package/dist/ui/core/input_segments.d.ts +15 -0
  19. package/dist/ui/core/input_segments.js +22 -0
  20. package/dist/ui/core/layout_yoga.d.ts +7 -0
  21. package/dist/ui/core/layout_yoga.js +16 -0
  22. package/dist/ui/ratatui/owner_ping.d.ts +24 -0
  23. package/dist/ui/ratatui/owner_ping.js +18 -0
  24. package/dist/ui/ratatui/process.d.ts +2 -2
  25. package/dist/ui/ratatui/protocol.d.ts +80 -3
  26. package/dist/ui/ratatui/protocol.js +58 -0
  27. package/dist/ui/scrollback.d.ts +24 -0
  28. package/dist/ui/scrollback.js +53 -18
  29. package/dist/ui/terminal_image.js +17 -1
  30. package/dist/ui/transcript_bound.d.ts +41 -0
  31. package/dist/ui/transcript_bound.js +100 -0
  32. package/dist/ui/transcript_render_cache.d.ts +15 -4
  33. package/dist/ui/transcript_render_cache.js +39 -16
  34. package/dist/ui/views/app.js +3 -2
  35. package/dist/ui/views/input_area.d.ts +1 -0
  36. package/dist/ui/views/input_area.js +34 -8
  37. package/dist/zlm-embed.mjs +1 -1
  38. package/package.json +17 -9
@@ -7,6 +7,8 @@ import { environmentOperationInProgress } from './agent/commands/environment.js'
7
7
  import { getEnvironment, openEnvironment, releaseEnvironment, describeEnvironmentForAgent, isEnvironmentWorkspacePath } from './environment/store.js';
8
8
  import { readPaneLabels, sessionNamePaneTitle } from './panes/labels.js';
9
9
  import { reconcileOrderedTranscript } from './app/ordered_transcript.js';
10
+ import { layoutChangeEffects } from './app/layout_change.js';
11
+ import { workspacePaneTopology } from './app/workspace_topology.js';
10
12
  import { listCommandJobs, shutdownCommandJobs, subscribeCommandJobs } from './agent/runtime/command_jobs.js';
11
13
  import { CommandPaneManager, commandPaneText } from './agent/runtime/command_panes.js';
12
14
  import { isPaneRefusalFor, waitForPaneCreatedOrError } from './agent/tools/pane.js';
@@ -62,11 +64,12 @@ import { checkForUpdate } from './utils/update.js';
62
64
  import { isBundledDesktopRuntime } from './desktop/runtime.js';
63
65
  import { getTuiProcess, getNullTuiProcess, TuiProcess, HeadlessPaneManager, decodeZtcPaneInput } from './ui/ratatui/index.js';
64
66
  import { getZmuxBinaryPath } from './ui/ratatui/process.js';
67
+ import { startOwnerPing } from './ui/ratatui/owner_ping.js';
65
68
  import { clipboardPastePreference } from './ui/ratatui/input.js';
66
69
  import { createInputBus, isControlKey } from './ui/core/input.js';
67
70
  import { buildAppView, getAppLayoutMetrics } from './ui/views/app.js';
68
71
  import { getQueuePreview, formatQueuedMessagePreview } from './ui/views/queue_panel.js';
69
- import { computeLayout } from './ui/core/layout_yoga.js';
72
+ import { computeLayout, frameForRenderer } from './ui/core/layout_yoga.js';
70
73
  import { frameTextLines } from './ui/core/frame_text.js';
71
74
  import { formatTranscriptTime } from './ui/core/time_format.js';
72
75
  import { buildStatusBarView } from './ui/views/status_bar.js';
@@ -112,7 +115,8 @@ import { modelHandoffSummarizer } from './utils/compaction.js';
112
115
  import { resolvePromptPrefixId } from './utils/compaction.js';
113
116
  import { IDLE_COMPACT_DEFAULT_LEAD_MS, IDLE_COMPACT_MIN_CONTEXT_TOKENS, IdleCompactionScheduler, resolveCacheLifetimeMs, } from './utils/idle_compaction.js';
114
117
  import { KittyImageUploads, kittyGraphicsTerminal, setTerminalImageMode, transcriptImagesForToolOutput } from './ui/terminal_image.js';
115
- import { insertText, insertBadge, expandPasteBadge, backspace, deleteForward, moveLeft, moveRight, moveWordLeft, moveWordRight, moveToStart, moveToEnd, moveToLineStart, moveToLineEnd, killToLineStart, killToLineEnd, moveVertical, wordBeforeCaret, wordAfterCaret, deleteWordBackward, deleteWordForward, getPlainText, serializeSegments, serializeMessageInput, textCursorIndex, killInputDraft, yankInputKill, historyUp, historyDown, PASTE_BADGE_THRESHOLD, } from './ui/core/input_segments.js';
118
+ import { MIN_TRANSCRIPT_LINE_BUDGET, RENDERER_TRANSCRIPT_ROWS, TRANSCRIPT_LINE_BUDGET, boundTranscript, sizeName } from './ui/transcript_bound.js';
119
+ import { insertText, insertBadge, expandPasteBadge, backspace, deleteForward, moveLeft, moveRight, moveWordLeft, moveWordRight, moveToStart, moveToEnd, moveToLineStart, moveToLineEnd, killToLineStart, killToLineEnd, moveVertical, wordBeforeCaret, wordAfterCaret, deleteWordBackward, deleteWordForward, getPlainText, serializeSegments, serializeMessageInput, textCursorIndex, killInputDraft, yankInputKill, historyUp, historyDown, PASTE_BADGE_THRESHOLD, pasteBecomesBadge, } from './ui/core/input_segments.js';
116
120
  import { findAtMention, completeAtMention, applyAtMention } from './utils/at_mention.js';
117
121
  import { DEFAULT_SPINNER_VERBS } from './utils/spinner_verbs.js';
118
122
  import { SPINNER_FRAMES } from './utils/spinner_frames.js';
@@ -224,7 +228,7 @@ import { loadSessionTranscript } from './session_preview.js';
224
228
  import { PromptTracer } from './agent/runtime/prompt_tracer.js';
225
229
  import { SupervisionManager } from './supervision/manager.js';
226
230
  import { HookLifecycle } from './hooks/lifecycle.js';
227
- import { messageToScrollbackLines as _messageToScrollbackLines, messageHeaderToScrollbackLine as _messageHeaderToScrollbackLine, renderMarkdownToScrollback as _renderMarkdownToScrollback, processMarkdownLine as _processMarkdownLine, } from './ui/scrollback.js';
231
+ import { messageToScrollbackLines as _messageToScrollbackLines, messageHeaderToScrollbackLine as _messageHeaderToScrollbackLine, renderMarkdownToScrollback as _renderMarkdownToScrollback, processMarkdownLine as _processMarkdownLine, appendRows, } from './ui/scrollback.js';
228
232
  import { initialStreamingScrollbackState, planStreamingScrollbackAppend, } from './ui/streaming_scrollback.js';
229
233
  import { initialStreamTypewriterState, planStreamTypewriterSample, } from './ui/stream_typewriter.js';
230
234
  import { TranscriptRenderCache, } from './ui/transcript_render_cache.js';
@@ -931,9 +935,39 @@ export class RatatuiApp {
931
935
  /** Fingerprint of the last transcript actually shipped, so an idle rebuild
932
936
  * (identical content) skips re-serialising and re-sending the whole buffer. */
933
937
  transcriptShipped = null;
934
- /** Rows of the transcript last built for zmux: a compact select sits right under them (see render). */
938
+ /** Rows of the transcript last shipped to zmux: a compact select sits right under them (see render). */
935
939
  transcriptRows = null;
940
+ /**
941
+ * The most bytes of transcript one command line carries (ui/transcript_bound.ts). A renderer that refuses a
942
+ * transcript as too long halves it, down to MIN_TRANSCRIPT_LINE_BUDGET; a new renderer starts it again.
943
+ */
944
+ transcriptLineBudget = TRANSCRIPT_LINE_BUDGET;
945
+ /** The last transcript command shipped, to tell a too_long refusal of it by its size. */
946
+ transcriptCommand = null;
947
+ /** The renderer's too_long refusals of a transcript, and whether one came at the smallest budget. */
948
+ transcriptRefusals = 0;
949
+ transcriptRefusedAtFloor = false;
950
+ /** Whether the person was told of a too_long refusal of a command other than the transcript. */
951
+ commandRefusalTold = false;
952
+ /** The render frames sent last, newest last, to tell a too_long refusal of one by its size. */
953
+ recentRenders = [];
954
+ /** Whether the person was told this renderer refused a render frame. */
955
+ renderRefusalTold = false;
956
+ /** How many render frames are kept to tell a refusal of one: as many as reach the renderer before its answer. */
957
+ static RECENT_RENDERS = 4;
958
+ /** A draft at least this large is named, with how to clear it, when a render frame is refused. */
959
+ static COMPOSER_DRAFT_NOTICE_BYTES = 1024 * 1024;
936
960
  static TRANSCRIPT_REBUILD_THROTTLE_MS = 50;
961
+ /**
962
+ * How long a width that keeps changing must hold still before the transcript is rebuilt for it (LS3). ZTerm sends a
963
+ * resize each frame a window edge or a split is dragged, and every width renders the shipped rows again.
964
+ */
965
+ static TRANSCRIPT_WIDTH_SETTLE_MS = 100;
966
+ /** When the width last changed, and when the last rebuild ended. */
967
+ transcriptWidthChangedAt = 0;
968
+ transcriptRebuiltAt = 0;
969
+ /** Until when a rebuild for a width still changing waits (0 when none does). */
970
+ transcriptWidthSettlesAt = 0;
937
971
  desktopMode = false;
938
972
  desktopRuntime;
939
973
  childPaneIds = new Set();
@@ -1014,6 +1048,8 @@ export class RatatuiApp {
1014
1048
  stopFollowingConfig = null;
1015
1049
  /** Stops refreshConnectedState from following a ZergAI login's wait. */
1016
1050
  stopFollowingLogin = null;
1051
+ /** Stops the pings that tell a desktop renderer this process's event loop still runs (owner_ping.ts). */
1052
+ stopOwnerPing = null;
1017
1053
  /** The connection snapshot last given to which mirror server, as JSON. */
1018
1054
  publishedConnection = null;
1019
1055
  intakeNotifications = new IntakeNotifications();
@@ -4633,9 +4669,8 @@ export class RatatuiApp {
4633
4669
  perfStage('received');
4634
4670
  // Normalize line endings once (paste may carry \r\n).
4635
4671
  const normalized = input.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
4636
- const lineCount = normalized.split('\n').length;
4637
- const looksLikePaste = lineCount > 1 || normalized.length > 100;
4638
- if (looksLikePaste && lineCount >= PASTE_BADGE_THRESHOLD) {
4672
+ const looksLikePaste = normalized.includes('\n') || normalized.length > 100;
4673
+ if (looksLikePaste && pasteBecomesBadge(normalized)) {
4639
4674
  this.inputState = insertBadge(this.inputState, {
4640
4675
  type: 'paste',
4641
4676
  text: normalized,
@@ -4679,12 +4714,11 @@ export class RatatuiApp {
4679
4714
  // Normalize line endings: \r\n -> \n, \r -> \n
4680
4715
  const normalized = input.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
4681
4716
  // Check if this looks like a paste (multi-line or very long input)
4682
- const lineCount = normalized.split('\n').length;
4683
- const looksLikePaste = lineCount > 1 || input.length > 100;
4684
- debugLog(`[processInputBuffer] Text input: length=${input.length}, lines=${lineCount}, looksLikePaste=${looksLikePaste}, threshold=${PASTE_BADGE_THRESHOLD}`);
4685
- if (looksLikePaste && lineCount >= PASTE_BADGE_THRESHOLD) {
4717
+ const looksLikePaste = normalized.includes('\n') || input.length > 100;
4718
+ debugLog(`[processInputBuffer] Text input: length=${input.length}, looksLikePaste=${looksLikePaste}, threshold=${PASTE_BADGE_THRESHOLD}`);
4719
+ if (looksLikePaste && pasteBecomesBadge(normalized)) {
4686
4720
  // Convert to paste badge for large pastes
4687
- debugLog(`[processInputBuffer] Creating paste badge for ${lineCount} lines`);
4721
+ debugLog(`[processInputBuffer] Creating paste badge for ${normalized.length} characters`);
4688
4722
  this.inputState = insertBadge(this.inputState, {
4689
4723
  type: 'paste',
4690
4724
  text: normalized,
@@ -5374,6 +5408,9 @@ export class RatatuiApp {
5374
5408
  });
5375
5409
  this.assertStartupActive();
5376
5410
  debugLog(`[start] tui.start() returned: ${size.cols}x${size.rows}`);
5411
+ // ZTerm hears from this event loop every 2 s, and takes an owner that goes 10 s without a ping for one that hangs.
5412
+ if (this.tui instanceof TuiProcess)
5413
+ this.stopOwnerPing ??= startOwnerPing(this.tui);
5377
5414
  // A fresh renderer knows nothing about the last one: its wheel capture
5378
5415
  // defaults to off and no surface has been painted yet. Forget our side of
5379
5416
  // both so the next render re-sends the claim and re-records the origin,
@@ -5831,8 +5868,10 @@ export class RatatuiApp {
5831
5868
  // Signal-safe shutdown: preserve colony state + save session before exit
5832
5869
  for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT']) {
5833
5870
  process.on(signal, () => {
5834
- if (signal === 'SIGINT' && this.exiting)
5835
- process.exit(130);
5871
+ if (signal === 'SIGINT' && this.exiting) {
5872
+ this.leaveMidQuit();
5873
+ return;
5874
+ }
5836
5875
  void this.emergencyExit();
5837
5876
  });
5838
5877
  }
@@ -7893,6 +7932,8 @@ export class RatatuiApp {
7893
7932
  || this.cols !== this.transcriptCols
7894
7933
  || state.expandToolOutputs !== this.transcriptExpandToolOutputs
7895
7934
  || showThinking !== this.transcriptShowThinking)) {
7935
+ if (this.transcriptCols !== 0 && this.cols !== this.transcriptCols)
7936
+ this.noteTranscriptWidthChange();
7896
7937
  this.transcriptMessagesRef = messages;
7897
7938
  this.transcriptCols = this.cols;
7898
7939
  this.transcriptExpandToolOutputs = state.expandToolOutputs;
@@ -7926,20 +7967,40 @@ export class RatatuiApp {
7926
7967
  return;
7927
7968
  // Throttle: if the last rebuild was longer ago than the throttle
7928
7969
  // window, fire immediately (next tick). Otherwise schedule for the
7929
- // remaining window so we hit at most one rebuild per window.
7970
+ // remaining window so we hit at most one rebuild per window. A width
7971
+ // still changing waits until it holds still (LS3).
7930
7972
  const now = Date.now();
7931
7973
  const since = now - this.transcriptLastRebuildAt;
7932
- const delay = since >= RatatuiApp.TRANSCRIPT_REBUILD_THROTTLE_MS
7933
- ? 0
7934
- : RatatuiApp.TRANSCRIPT_REBUILD_THROTTLE_MS - since;
7935
- this.transcriptRebuildTimer = setTimeout(() => {
7936
- this.transcriptRebuildTimer = null;
7937
- if (this.transcriptDirty) {
7938
- this.transcriptDirty = false;
7939
- this.transcriptLastRebuildAt = Date.now();
7940
- this.rebuildTranscript();
7941
- }
7942
- }, delay);
7974
+ const delay = Math.max(since >= RatatuiApp.TRANSCRIPT_REBUILD_THROTTLE_MS ? 0 : RatatuiApp.TRANSCRIPT_REBUILD_THROTTLE_MS - since, this.transcriptWidthSettlesAt - now);
7975
+ this.transcriptRebuildTimer = setTimeout(() => this.runTranscriptRebuildTimer(), delay);
7976
+ }
7977
+ runTranscriptRebuildTimer() {
7978
+ this.transcriptRebuildTimer = null;
7979
+ // The width changed again meanwhile, and pushed the wait further out.
7980
+ const settling = this.transcriptWidthSettlesAt - Date.now();
7981
+ if (settling > 0) {
7982
+ this.transcriptRebuildTimer = setTimeout(() => this.runTranscriptRebuildTimer(), settling);
7983
+ return;
7984
+ }
7985
+ if (this.transcriptDirty) {
7986
+ this.transcriptDirty = false;
7987
+ this.transcriptLastRebuildAt = Date.now();
7988
+ this.rebuildTranscript();
7989
+ this.transcriptRebuiltAt = Date.now();
7990
+ }
7991
+ }
7992
+ /**
7993
+ * The transcript's width changed (LS3). The first change after a quiet spell is rebuilt at once, as a single resize
7994
+ * should be. One that comes while the change before it, or the rebuild that ended last, is more recent than
7995
+ * TRANSCRIPT_WIDTH_SETTLE_MS waits until the width has held still that long, so a drag through 20 widths rebuilds the
7996
+ * transcript twice rather than 20 times, and resizes queued behind a slow rebuild are not each rebuilt in turn.
7997
+ */
7998
+ noteTranscriptWidthChange() {
7999
+ const now = Date.now();
8000
+ if (now - Math.max(this.transcriptWidthChangedAt, this.transcriptRebuiltAt) < RatatuiApp.TRANSCRIPT_WIDTH_SETTLE_MS) {
8001
+ this.transcriptWidthSettlesAt = now + RatatuiApp.TRANSCRIPT_WIDTH_SETTLE_MS;
8002
+ }
8003
+ this.transcriptWidthChangedAt = now;
7943
8004
  }
7944
8005
  /**
7945
8006
  * Flush a pending rebuild synchronously when the throttle window has
@@ -7957,6 +8018,9 @@ export class RatatuiApp {
7957
8018
  if (!this.isAtomicRebuildActive())
7958
8019
  return;
7959
8020
  const now = Date.now();
8021
+ // A width still changing is rebuilt from the timer, once it holds still.
8022
+ if (now < this.transcriptWidthSettlesAt)
8023
+ return;
7960
8024
  if (now - this.transcriptLastRebuildAt < RatatuiApp.TRANSCRIPT_REBUILD_THROTTLE_MS) {
7961
8025
  return;
7962
8026
  }
@@ -7967,6 +8031,7 @@ export class RatatuiApp {
7967
8031
  this.transcriptDirty = false;
7968
8032
  this.transcriptLastRebuildAt = now;
7969
8033
  this.rebuildTranscript();
8034
+ this.transcriptRebuiltAt = Date.now();
7970
8035
  }
7971
8036
  /**
7972
8037
  * Force the next render to rebuild the external transcript before painting
@@ -7984,6 +8049,7 @@ export class RatatuiApp {
7984
8049
  }
7985
8050
  this.transcriptDirty = true;
7986
8051
  this.transcriptLastRebuildAt = 0;
8052
+ this.transcriptWidthSettlesAt = 0;
7987
8053
  }
7988
8054
  /**
7989
8055
  * Everything a rendered message depends on besides the message itself, as the transcript's render cache keys it. A
@@ -8007,10 +8073,24 @@ export class RatatuiApp {
8007
8073
  rebuildTranscript() {
8008
8074
  const state = this.controller.getState();
8009
8075
  const display = resolveMessageDisplaySettings(configStore.get());
8076
+ // What the transcript is built from, as this rebuild finds it. A rebuild from the throttle's timer can ship a change
8077
+ // no render has noted yet; if that change is then undone, the next render compares the transcript with what it is
8078
+ // shipped as, not with what the last render noted, and rebuilds it again.
8079
+ this.transcriptMessagesRef = state.messages;
8080
+ this.transcriptCols = this.cols;
8081
+ this.transcriptExpandToolOutputs = state.expandToolOutputs;
8082
+ this.transcriptShowThinking = display.showThinking;
8010
8083
  const configKey = this.transcriptConfigKey(display);
8011
- const allLines = [];
8084
+ // Newest first, and only until the rows the renderer keeps are rendered (LS1, LS3): the renderer keeps the last
8085
+ // RENDERER_TRANSCRIPT_ROWS rows, so older messages are neither rendered nor copied. The oldest message rendered is
8086
+ // rendered whole, as head_line_offset counts its rows left out. A long session's resize, or a rebuild while a
8087
+ // message of 150,000 rows sits in it, costs the rows shipped and that message, not the whole session.
8088
+ const messages = this.materializeToolOutputMessages(state.messages, state.expandToolOutputs);
8089
+ const kept = [];
8012
8090
  const fingerprint = [];
8013
- for (const msg of this.materializeToolOutputMessages(state.messages, state.expandToolOutputs)) {
8091
+ let keptRows = 0;
8092
+ for (let index = messages.length - 1; index >= 0 && keptRows < RENDERER_TRANSCRIPT_ROWS; index--) {
8093
+ const msg = messages[index];
8014
8094
  if (msg.metadata?.steeringPending === true)
8015
8095
  continue;
8016
8096
  // Phase 7 fix: include streaming messages too. Earlier we skipped
@@ -8036,22 +8116,23 @@ export class RatatuiApp {
8036
8116
  const rendered = this.transcriptRenderCache.render(typed, configKey);
8037
8117
  if (rendered.lines.length === 0)
8038
8118
  continue;
8039
- allLines.push(...rendered.lines);
8040
- allLines.push({ text: '', message_id: msg.id });
8119
+ kept.push({ lines: rendered.lines, id: msg.id });
8120
+ keptRows += rendered.lines.length + 1;
8041
8121
  fingerprint.push(rendered.hash);
8042
8122
  }
8043
8123
  this.pruneStreamTypewriters(state.messages);
8044
- if (allLines.length !== this.transcriptRows) {
8045
- this.transcriptRows = allLines.length;
8046
- // A compact select sits on the row after the transcript: lay it out again
8047
- // once this render (or the throttled rebuild) is done.
8048
- if (this.selectWidget.isActive() && this.selectWidget.isCompact())
8049
- queueMicrotask(() => this.render());
8124
+ // Oldest first again, each message's rows and the blank row after them. Never `push(...rows)`: a message's rows
8125
+ // can pass the arguments a call takes.
8126
+ const allLines = [];
8127
+ for (let index = kept.length - 1; index >= 0; index--) {
8128
+ appendRows(allLines, kept[index].lines);
8129
+ allLines.push({ text: '', message_id: kept[index].id });
8050
8130
  }
8051
8131
  // Native scrolling is the source of truth. Preserve its current anchor at
8052
8132
  // replacement time; a resize-ack snapshot can predate newer user scrolling.
8053
8133
  if (this.transcriptShipped !== null
8054
8134
  && this.transcriptShipped.configKey === configKey
8135
+ && this.transcriptShipped.budget === this.transcriptLineBudget
8055
8136
  && sameFingerprint(this.transcriptShipped.fingerprint, fingerprint)) {
8056
8137
  // Nothing a reader can see changed: a reveal tick that produced the same
8057
8138
  // prefix, a repeated resize ack, or a state update that touched only
@@ -8059,12 +8140,26 @@ export class RatatuiApp {
8059
8140
  // holds; the anchor is untouched because the content is untouched.
8060
8141
  return;
8061
8142
  }
8062
- this.transcriptShipped = { configKey, fingerprint };
8063
- transcriptDebugLog(`rebuild lines=${allLines.length}`);
8064
- const shipped = this.sendTranscriptCommand({
8143
+ // Only the rows the renderer keeps, and at most the line budget of them
8144
+ // (VR2): the whole transcript of a long session passes the renderer's
8145
+ // line cap, which refuses it and leaves Main unchanged.
8146
+ const bounded = boundTranscript(allLines, { rows: RENDERER_TRANSCRIPT_ROWS, bytes: this.transcriptLineBudget });
8147
+ if (bounded.lines.length !== this.transcriptRows) {
8148
+ this.transcriptRows = bounded.lines.length;
8149
+ // A compact select sits on the row after the transcript: lay it out again
8150
+ // once this render (or the throttled rebuild) is done.
8151
+ if (this.selectWidget.isActive() && this.selectWidget.isCompact())
8152
+ queueMicrotask(() => this.render());
8153
+ }
8154
+ this.transcriptShipped = { configKey, fingerprint, budget: this.transcriptLineBudget };
8155
+ transcriptDebugLog(`rebuild lines=${allLines.length} shipped=${bounded.lines.length} head=${bounded.headLineOffset} over_budget=${bounded.overBudget}`);
8156
+ const command = {
8065
8157
  type: 'replace_scrollback_with_anchor',
8066
- lines: allLines,
8067
- });
8158
+ lines: bounded.lines,
8159
+ ...(bounded.headLineOffset > 0 ? { head_line_offset: bounded.headLineOffset } : {}),
8160
+ };
8161
+ this.transcriptCommand = command;
8162
+ const shipped = this.sendTranscriptCommand(command);
8068
8163
  if (!shipped) {
8069
8164
  // The renderer did not take the buffer (socket backpressure or a
8070
8165
  // pending resize fence). Forget the fingerprint so the next rebuild
@@ -8081,6 +8176,67 @@ export class RatatuiApp {
8081
8176
  this.printedMessageIds.add(msg.id);
8082
8177
  }
8083
8178
  }
8179
+ /**
8180
+ * The renderer dropped a command line over its cap (RZ1, RX1: `too_long`, naming the line's bytes). ZTC bounds what
8181
+ * it ships so this never comes; if it does, it is never let go silently, nor answered by shipping the same line
8182
+ * forever. A refused transcript ships again at half the size, at most every time a refusal halves the budget down to
8183
+ * MIN_TRANSCRIPT_LINE_BUDGET, and after that only as it changes; the transcript says so once each way.
8184
+ */
8185
+ handleCommandRefusedTooLong(message) {
8186
+ const refused = Number(/a command line of (\d+) bytes/.exec(message)?.[1] ?? Number.NaN);
8187
+ const transcript = this.transcriptCommand;
8188
+ if (transcript !== null && refused === Buffer.byteLength(JSON.stringify(transcript), 'utf8')) {
8189
+ this.transcriptCommand = null;
8190
+ const halved = Math.floor(Math.min(this.transcriptLineBudget, refused) / 2);
8191
+ if (halved >= MIN_TRANSCRIPT_LINE_BUDGET) {
8192
+ this.transcriptLineBudget = halved;
8193
+ if (this.transcriptRefusals++ === 0) {
8194
+ this.addSystemMessage(`This window's renderer refused ZTC's transcript of ${sizeName(refused)} as too long. ZTC now sends it at most the newest ${sizeName(halved)} of the transcript, and leaves the older rows out.`, { ephemeral: true });
8195
+ }
8196
+ this.transcriptShipped = null;
8197
+ this.markTranscriptDirty();
8198
+ }
8199
+ else if (!this.transcriptRefusedAtFloor) {
8200
+ this.transcriptRefusedAtFloor = true;
8201
+ this.addSystemMessage(`This window's renderer refused ZTC's transcript as too long even at ${sizeName(refused)}. ZTC sends it again only as it changes.`, { ephemeral: true });
8202
+ }
8203
+ return;
8204
+ }
8205
+ if (Number.isFinite(refused) && this.isRecentRender(refused)) {
8206
+ // Main's live frame stays as it was: the composer, the status line and the spinner stop updating (LS2). It is
8207
+ // said in its own words, once for each renderer, with how to clear a large draft, the one part of the screen the
8208
+ // person can shrink. Ctrl+C stops a running turn before it clears the composer, so the notice says so.
8209
+ if (this.renderRefusalTold)
8210
+ return;
8211
+ this.renderRefusalTold = true;
8212
+ const draft = this.composerDraftBytes();
8213
+ const clear = draft >= RatatuiApp.COMPOSER_DRAFT_NOTICE_BYTES
8214
+ ? ` The composer holds a draft of ${sizeName(draft)}: Ctrl+C clears it (after stopping a running turn), and Ctrl+Y brings it back.` : '';
8215
+ this.addSystemMessage(`This window's renderer refused ZTC's screen of ${sizeName(refused)} as too long, so the composer, status line and spinner it shows stop updating.${clear}`, { ephemeral: true });
8216
+ return;
8217
+ }
8218
+ if (this.commandRefusalTold)
8219
+ return;
8220
+ this.commandRefusalTold = true;
8221
+ this.addSystemMessage(`This window's renderer refused a command from ZTC as too long: ${message}`, { ephemeral: true });
8222
+ }
8223
+ /** Whether one of the render frames sent last was `bytes` long as the renderer read it, newest first. */
8224
+ isRecentRender(bytes) {
8225
+ for (let index = this.recentRenders.length - 1; index >= 0; index--) {
8226
+ if (Buffer.byteLength(JSON.stringify(this.recentRenders[index]), 'utf8') === bytes)
8227
+ return true;
8228
+ }
8229
+ return false;
8230
+ }
8231
+ /** The bytes of the composer's draft: its text and pastes. */
8232
+ composerDraftBytes() {
8233
+ let bytes = 0;
8234
+ for (const segment of this.inputState.segments) {
8235
+ if (segment.type === 'text' || segment.type === 'paste')
8236
+ bytes += Buffer.byteLength(segment.text, 'utf8');
8237
+ }
8238
+ return bytes;
8239
+ }
8084
8240
  /**
8085
8241
  * Get a human-readable verb for a tool name (for spinner/status display)
8086
8242
  */
@@ -8303,7 +8459,7 @@ export class RatatuiApp {
8303
8459
  continue;
8304
8460
  const msgLines = this.messageToScrollbackLines(msg);
8305
8461
  if (msgLines.length > 0) {
8306
- lines.push(...msgLines);
8462
+ appendRows(lines, msgLines);
8307
8463
  // Only visible messages own spacing. Hidden history records must not
8308
8464
  // scroll the terminal or push a completed answer out of view.
8309
8465
  lines.push({ text: '', message_id: msg.id });
@@ -8376,6 +8532,9 @@ export class RatatuiApp {
8376
8532
  return rows - 1;
8377
8533
  }
8378
8534
  handleTuiEvent(event) {
8535
+ // The renderer's answer to a ping (owner_ping.ts) asks nothing of the app; one comes every 2 s, unlogged.
8536
+ if (event.type === 'pong')
8537
+ return;
8379
8538
  debugLog(`[handleTuiEvent] type=${event.type}`);
8380
8539
  switch (event.type) {
8381
8540
  case 'ready':
@@ -8391,6 +8550,13 @@ export class RatatuiApp {
8391
8550
  setTerminalImageMode(!this.paneMode && !this.headlessMirror
8392
8551
  && this.tui.hasCapability(CAPABILITY_KITTY_GRAPHICS) && kittyGraphicsTerminal(process.env) ? 'kitty' : 'blocks', event.cell_pixels ?? null);
8393
8552
  this.kittyImageUploads.reset();
8553
+ // A new renderer: its cap is its own, so the transcript goes out under the full budget again.
8554
+ this.transcriptLineBudget = TRANSCRIPT_LINE_BUDGET;
8555
+ this.transcriptCommand = null;
8556
+ this.transcriptRefusals = 0;
8557
+ this.transcriptRefusedAtFloor = false;
8558
+ this.recentRenders.length = 0;
8559
+ this.renderRefusalTold = false;
8394
8560
  break;
8395
8561
  case 'desktop_task_action':
8396
8562
  void this.handleDesktopTaskAction(event);
@@ -8437,6 +8603,8 @@ export class RatatuiApp {
8437
8603
  }
8438
8604
  break;
8439
8605
  case 'error':
8606
+ if (event.code === 'too_long')
8607
+ this.handleCommandRefusedTooLong(event.message);
8440
8608
  if (this.debug) {
8441
8609
  debugLog(`[RatatuiApp] ${event.message}`);
8442
8610
  }
@@ -8588,6 +8756,17 @@ export class RatatuiApp {
8588
8756
  .catch(error => this.addSystemMessage(`Workspace: ${error.message}`));
8589
8757
  break;
8590
8758
  }
8759
+ case 'layout_changed': {
8760
+ // The person or the owner arranged the live workspace (pane-drag-drop spec §7.4).
8761
+ const effects = layoutChangeEffects(event, { nativeRestorePending: this.nativeRestorePending });
8762
+ if (effects.dropRetainedStartupLayout)
8763
+ this.retainedStartupLayout = null;
8764
+ if (effects.saveAfterMs !== null)
8765
+ this.scheduleMuxPersistenceSave(effects.saveAfterMs);
8766
+ if (effects.debug)
8767
+ debugLog(effects.debug);
8768
+ break;
8769
+ }
8591
8770
  case 'pane_closed':
8592
8771
  if (!this.nativeRestorePending)
8593
8772
  this.retainedStartupLayout = null;
@@ -8848,8 +9027,7 @@ export class RatatuiApp {
8848
9027
  this.idleCompaction.cancel();
8849
9028
  this.lastInputAt = Date.now();
8850
9029
  const text = input.replace(/\r\n?/g, '\n');
8851
- const lines = text.split('\n').length;
8852
- this.inputState = lines >= PASTE_BADGE_THRESHOLD
9030
+ this.inputState = pasteBecomesBadge(text)
8853
9031
  ? insertBadge(this.inputState, { type: 'paste', text })
8854
9032
  : insertText(this.inputState, text);
8855
9033
  this.controller.setInputState(this.inputState);
@@ -14128,10 +14306,7 @@ export class RatatuiApp {
14128
14306
  await this.ensureSessionManager().save({ persistEmpty: force, required: force, signal, ...(this.exiting ? { captureLayout: true } : {}) });
14129
14307
  }
14130
14308
  workspacePaneTopology(state) {
14131
- const layout = (node) => node.type === 'leaf' ? node.pane_id : [node.direction, layout(node.first), layout(node.second)];
14132
- return JSON.stringify({ windows: state.windows
14133
- ? state.windows.map(window => [window.id, layout(window.layout)]).sort((a, b) => Number(a[0]) - Number(b[0]))
14134
- : [[0, layout(state.layout)]], panes: state.panes.map(pane => [pane.id, pane.window_id ?? 0]).sort((a, b) => a[0] - b[0]) });
14309
+ return workspacePaneTopology(state);
14135
14310
  }
14136
14311
  async completeSessionLayout(timeoutMs = 4000, checkpoint = false) {
14137
14312
  if (this.nativeRestorePending)
@@ -15148,9 +15323,9 @@ export class RatatuiApp {
15148
15323
  // bursts from shipping a rebuild per delta — within-window
15149
15324
  // mutations stay deferred to the timer.
15150
15325
  this.flushTranscriptRebuildIfDue();
15151
- this.sendTranscriptCommand({
15326
+ const command = {
15152
15327
  type: 'render',
15153
- frame,
15328
+ frame: frameForRenderer(frame),
15154
15329
  viewport_height: effectiveViewportHeight,
15155
15330
  scroll_region_y: transcriptRegionY,
15156
15331
  scroll_region_height: transcriptRegionHeight,
@@ -15159,7 +15334,11 @@ export class RatatuiApp {
15159
15334
  // so without this a question or panel opened mid-scroll would be
15160
15335
  // invisible — and its keys, swallowed by scroll mode, would never arrive.
15161
15336
  owns_screen: widgetActive,
15162
- });
15337
+ };
15338
+ this.recentRenders.push(command);
15339
+ if (this.recentRenders.length > RatatuiApp.RECENT_RENDERS)
15340
+ this.recentRenders.shift();
15341
+ this.sendTranscriptCommand(command);
15163
15342
  }
15164
15343
  /**
15165
15344
  * The widget that owns the mouse wheel right now, if any.
@@ -15891,14 +16070,39 @@ export class RatatuiApp {
15891
16070
  return;
15892
16071
  }
15893
16072
  }
16073
+ /**
16074
+ * A Ctrl+C in the terminal that started ZTC while a quit already runs: leave now, as before, but tell the renderer
16075
+ * first that this is a quit (Q1). The quit sends `shutdown` only once it has the window's layout, up to 300 ms on, and
16076
+ * a desktop renderer that loses its owner without `shutdown` keeps the window and every pane under its "ZTC stopped"
16077
+ * banner, as after a crash (RZ8a). The line reaches the socket at once when nothing waits ahead of it; the exit waits
16078
+ * one turn of the event loop for what does.
16079
+ */
16080
+ leaveMidQuit() {
16081
+ this.tui.send({ type: 'shutdown' });
16082
+ setImmediate(() => process.exit(130));
16083
+ }
15894
16084
  emergencyExitPromise = null;
16085
+ /** Leave at once, saving the session and stopping the renderer: for a signal (SIGTERM, SIGHUP, SIGQUIT, a Ctrl+C). */
15895
16086
  emergencyExit() {
16087
+ return this.leaveInEmergency(true);
16088
+ }
16089
+ /**
16090
+ * Leave after ZTC itself failed: an uncaught exception or an unhandled rejection reached cli_main.ts's handlers. The
16091
+ * session is saved as for a signal. In a terminal the renderer is stopped too, as only that gives the terminal back.
16092
+ * A desktop renderer that has admitted this owner is left running: ZTerm reads `shutdown` as a quit and ends every
16093
+ * pane with its window, while an owner that leaves without it is a crash, and ZTerm keeps the window and its panes
16094
+ * under "ZTC (the agent runtime) stopped" (P3a-0, RZ8a), as after a SIGKILL.
16095
+ */
16096
+ crashExit() {
16097
+ return this.leaveInEmergency(!(this.desktopMode && this.tui.isReady()));
16098
+ }
16099
+ leaveInEmergency(stopRenderer) {
15896
16100
  if (this.emergencyExitPromise)
15897
16101
  return this.emergencyExitPromise;
15898
16102
  const deadline = setTimeout(() => process.exit(1), 3000);
15899
16103
  deadline.unref();
15900
16104
  this.emergencyExitPromise = (async () => {
15901
- debugLog('[signal] Emergency save triggered');
16105
+ debugLog(stopRenderer ? '[signal] Emergency save triggered' : '[crash] Emergency save triggered; the desktop renderer keeps its panes');
15902
16106
  this.exiting = true;
15903
16107
  try {
15904
16108
  getColonyService()?.getAgentBridge?.()?.prepareForShutdown();
@@ -15906,7 +16110,7 @@ export class RatatuiApp {
15906
16110
  catch { }
15907
16111
  this._captureEmergencyMuxSnapshot();
15908
16112
  const saved = this.saveCurrentSession();
15909
- const stopped = this.tui.stop();
16113
+ const stopped = stopRenderer ? this.tui.stop() : Promise.resolve();
15910
16114
  let desktopTimer;
15911
16115
  const desktop = Promise.race([
15912
16116
  Promise.resolve().then(() => this.dailyDesktop?.close()).catch(() => { }),
@@ -16012,6 +16216,8 @@ export class RatatuiApp {
16012
16216
  catch (err) {
16013
16217
  debugLog(`[exit] tui.stop failed: ${err.message}`);
16014
16218
  }
16219
+ this.stopOwnerPing?.();
16220
+ this.stopOwnerPing = null;
16015
16221
  playSfxLazy('session_end');
16016
16222
  if (options.announce !== false) {
16017
16223
  if (options.persistSession !== false && this.shouldPersistSession()) {
@@ -56,11 +56,15 @@ export function statusRestoreState(source, status, present) {
56
56
  }
57
57
  if (state.windows?.length) {
58
58
  if (!state.windows.some(window => ids(window.layout).includes(0))) {
59
- state.active_window_id ??= Math.min(...state.windows.map(window => window.id));
59
+ // The windows run in the strip's order: with none named, the first comes forward, as zterm brings it.
60
+ state.active_window_id ??= state.windows[0].id;
60
61
  let id = 0;
61
62
  while (state.windows.some(window => window.id === id))
62
63
  id++;
63
- state.windows.push({ id, title: 'ZTC', focused_pane_id: 0, layout: { type: 'leaf', pane_id: 0 } });
64
+ // Main's tab goes where zterm puts the owner tab it adds: before the first tab with a larger id, so a session
65
+ // saved in id order shows it where it always did.
66
+ const before = state.windows.findIndex(window => window.id > id);
67
+ state.windows.splice(before < 0 ? state.windows.length : before, 0, { id, title: 'ZTC', focused_pane_id: 0, layout: { type: 'leaf', pane_id: 0 } });
64
68
  }
65
69
  }
66
70
  else if (!ids(state.layout).includes(0)) {
@@ -154,6 +154,10 @@ function attentionNote(pane) {
154
154
  const what = attention.text?.trim() || attention.kind;
155
155
  return `wants attention: ${what}${attention.count > 1 ? ` (${attention.count})` : ''}`;
156
156
  }
157
+ /** A tab's place in the strip, as a renderer says it: 1 to 64. */
158
+ function isTabPlace(place) {
159
+ return Number.isInteger(place) && place >= 1 && place <= 64;
160
+ }
157
161
  function paneName(pane) {
158
162
  return pane.labels?.manual_title || pane.title;
159
163
  }
@@ -321,15 +325,18 @@ export function createWorkspaceMcpServer(options) {
321
325
  const all = await panes();
322
326
  if (all.length === 0)
323
327
  return 'The workspace has no panes.';
324
- // Tabs numbered as the desktop app's Cmd+1–9 count them: in the order of their ids.
328
+ // Tabs numbered as the desktop app's Cmd+1–9 count them, in the strip's order, which each pane's tab_place says.
329
+ // A renderer that says no place has its tabs in the order of their ids.
330
+ const placed = all.every(pane => pane.window_id === undefined || isTabPlace(pane.tab_place));
325
331
  const tabs = [...new Set(all.flatMap(pane => pane.window_id === undefined ? [] : [pane.window_id]))].sort((a, b) => a - b);
332
+ const tabNumber = (pane) => placed ? pane.tab_place : tabs.indexOf(pane.window_id) + 1;
326
333
  return all
327
334
  .slice()
328
335
  .sort((a, b) => a.id - b.id)
329
336
  .map(pane => {
330
337
  const label = pane.activity_label?.trim() || pane.activity_status;
331
338
  const notes = [
332
- pane.window_id === undefined ? '' : `tab ${tabs.indexOf(pane.window_id) + 1}`,
339
+ pane.window_id === undefined ? '' : `tab ${tabNumber(pane)}`,
333
340
  pane.id === ownPaneId ? 'you' : '',
334
341
  pane.is_focused ? 'focused' : '',
335
342
  pane.is_alive ? '' : 'exited',
@@ -1,6 +1,21 @@
1
1
  import { InputSegment, InputCursor, InputState, InputKill, InputDraftSnapshot } from './input_state.js';
2
2
  import type { MessageInput } from '../../types.js';
3
3
  export declare const PASTE_BADGE_THRESHOLD = 4;
4
+ /**
5
+ * A paste this long is a badge whatever its line count (LS4). The composer wraps all of its text on every render to
6
+ * show the rows around the cursor, about 0.8 µs a character: a one-line paste of 2 MiB (a token, minified JSON, base64)
7
+ * made every render take 1.7 s. A paste shorter than this stays text the person can edit: a URL or a key, and a task of
8
+ * the desktop queue, which edits a task as text up to 64 KiB and keeps all of a longer one. This is twice that, so a
9
+ * render takes at most about 0.1 s for the text.
10
+ */
11
+ export declare const PASTE_BADGE_CHARS: number;
12
+ /** Whether a paste of `text` goes into the composer as a badge rather than as text. */
13
+ export declare function pasteBecomesBadge(text: string): boolean;
14
+ /**
15
+ * How many lines `text` holds, its newlines and one, counted no further than `atMost`. A paste can hold millions of
16
+ * lines and the composer counts them on every render, where splitting it made a string of every line.
17
+ */
18
+ export declare function countLines(text: string, atMost?: number): number;
4
19
  export declare function normalizeSegments(segments: InputSegment[]): InputSegment[];
5
20
  export declare function clampCursor(segments: InputSegment[], cursor: InputCursor): InputCursor;
6
21
  export declare function insertText(state: InputState, text: string): InputState;