@north-light/cli 0.3.700 → 0.3.702

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 (33) hide show
  1. package/dist/clients/attach/command.js +1 -1
  2. package/dist/clients/attach/session/connection.d.ts +14 -25
  3. package/dist/clients/attach/session/connection.js +1 -1
  4. package/dist/clients/attach/session/input-wiring.d.ts +3 -0
  5. package/dist/clients/attach/session/input-wiring.js +1 -1
  6. package/dist/clients/attach/session/reconnect.d.ts +0 -3
  7. package/dist/clients/attach/session/reconnect.js +1 -1
  8. package/dist/clients/attach/session/teardown.d.ts +2 -0
  9. package/dist/clients/attach/session/teardown.js +10 -5
  10. package/dist/clients/attach/viewer.js +486 -480
  11. package/dist/core/broker-client/transport-relay.js +1 -1
  12. package/dist/core/runtime/broker/client-registry.js +1 -1
  13. package/dist/core/runtime/broker/frame-client.js +1 -1
  14. package/dist/daemon/api/bridge.js +4 -4
  15. package/dist/daemon/machine-link/client.d.ts +5 -1
  16. package/dist/daemon/machine-link/client.js +1 -1
  17. package/dist/daemon/machine-link/forward.js +1 -1
  18. package/dist/daemon/machine-link/holder.d.ts +4 -1
  19. package/dist/daemon/machine-link/holder.js +5 -5
  20. package/package.json +3 -3
  21. package/packages/crouter-api/dist/clients/attach/command.js +1 -1
  22. package/packages/crouter-api/dist/clients/attach/session/connection.js +48 -116
  23. package/packages/crouter-api/dist/clients/attach/session/input-wiring.js +3 -3
  24. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +12 -5
  25. package/packages/crouter-api/dist/clients/attach/session/teardown.js +3 -0
  26. package/packages/crouter-api/dist/clients/attach/viewer.js +89 -44
  27. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +8 -0
  28. package/packages/crouter-api/dist/daemon/machine-link/forward.js +6 -2
  29. package/packages/crouter-api/dist/daemon/machine-link/holder.js +14 -5
  30. package/packages/crouter-api/package.json +1 -1
  31. package/packages/crouter-identity/package.json +1 -1
  32. package/packages/crouter-plugin/package.json +3 -3
  33. package/runtime.lock.json +14 -14
@@ -2,11 +2,12 @@
2
2
  // local or remote attach target, dialing it, the role it claims in the hello
3
3
  // handshake, and the optional pre-wait for a socket still being bound.
4
4
  //
5
- // Everything here runs BEFORE the TUI takes over the terminal, which is the
6
- // point: a missing broker must exit non-zero with a plain CLI error, not paint
7
- // an alternate screen first. Nothing here launches anything — attach holds ONLY
8
- // a socket; the engine is started server-side by crtrd (`reviveNode`, the one
9
- // sanctioned launcher), never here.
5
+ // `connectToNode` resolves the target before the TUI takes over the terminal;
6
+ // it waits for nothing on the broker. Everything that does wait — the attach
7
+ // ensure, the dial — is `dial()`, which the viewer runs AFTER it has painted, so
8
+ // its failure is reported through the viewer. Nothing here launches anything —
9
+ // attach holds ONLY a socket; the engine is started server-side by crtrd
10
+ // (`reviveNode`, the one sanctioned launcher), never here.
10
11
  import { createConnection } from 'node:net';
11
12
  import { apiSocketPath, viewSocketPath } from '../../../core/canvas/paths.js';
12
13
  import { BrokerClient, BrokerUnavailableError, RelayTransport } from '../../../core/broker-client/index.js';
@@ -16,6 +17,7 @@ import { InputError, apiErrorToCliError } from '../../../core/io.js';
16
17
  import { ApiError } from '../../../api/index.js';
17
18
  import { readMachineConfig } from '../../../daemon/machine-link/config.js';
18
19
  import { personBearer } from '../../../core/directory/person-credential.js';
20
+ import { mark } from '../../../core/timing.js';
19
21
  /** The person bearer is cached until 30 s before it ends; a viewer redials with whatever the target holds at that moment, so a shorter timer keeps it fresh. */
20
22
  const BEARER_REFRESH_MS = 15_000;
21
23
  /** A relay target for an imported Mac: the cloud control plane, with the signed-in person's bearer. `relayToken` is read at each dial. */
@@ -61,12 +63,9 @@ export async function preWaitForViewSocket(nodeId) {
61
63
  await new Promise((r) => setTimeout(r, 100));
62
64
  }
63
65
  }
64
- /** Resolve the target, revive the node if it is dormant (server-side), and dial
65
- * the broker. Rejects with a plain `InputError` — no terminal has been taken
66
- * over at this point, so a failure here is an ordinary non-zero CLI exit. */
67
- export async function connectToNode(nodeId, canvasName, wakeParked = true, known,
68
- /** The viewer's identity for the `hello` sent right after the connect. A live attach stays on the caller's screen until the broker's `welcome` answers it. */
69
- hello) {
66
+ /** Resolve the attach target and build the not-yet-connected socket. Rejects with
67
+ * a plain `InputError` for an unknown node — no terminal has been taken over yet. */
68
+ export async function connectToNode(nodeId, canvasName, wakeParked = true, known) {
70
69
  // An imported Mac has no local canvas API: its canvas and its brokers' viewer channels are reached through the cloud control plane,
71
70
  // so attach without `--canvas` dials the cloud with the person's sign-in. It is still the person's own attach, not a `--canvas` view:
72
71
  // `remote` stays false, so the viewer claims the controller role like any local attach.
@@ -91,8 +90,6 @@ hello) {
91
90
  let meta;
92
91
  let nodeIdentity;
93
92
  let transport;
94
- let initialSnapshot;
95
- let initialCommands;
96
93
  if (canvasName !== undefined) {
97
94
  meta = { cwd: process.cwd() };
98
95
  transport = new RelayTransport(nodeId, resolveRemoteCanvasTarget(canvasName));
@@ -116,35 +113,13 @@ hello) {
116
113
  transport = new RelayTransport(nodeId, await machineRelayTarget(machine.apiUrl, machine.directoryUrl), wakeParked);
117
114
  }
118
115
  else {
119
- // Attach revives a dormant node (B2 acceptance): the server-side
120
- // ensureAttach runs reviveNode (the ONE sanctioned launcher) and waits for
121
- // the broker's view socket, returning socket_path === viewSocketPath(nodeId).
122
- // The viewer connects through crtrd's Unix-socket WebSocket bridge after
123
- // this ensure. The daemon, not the broker, owns attending viewer presence.
124
- try {
125
- const attach = await cliClient().ensureAttach(nodeId, { resume: true, revive: true, wakeParked });
126
- if (attach.parked) {
127
- const saved = await cliClient().getSnapshot(nodeId);
128
- // The API DTO stays dependency-light and structural; this viewer is the
129
- // consumer that knows the complete broker snapshot contract.
130
- initialSnapshot = saved.snapshot;
131
- initialCommands = saved.commands;
132
- }
133
- }
134
- catch (err) {
135
- rethrowAsCliError(err, 'The node may be finalized or otherwise not attachable.');
136
- }
137
- // An offline parked focus has deliberately no socket to wait for.
138
- if (initialSnapshot === undefined)
139
- await preWaitForViewSocket(nodeId);
116
+ // The attach ensure runs in `dial()`; the viewer connects through crtrd's Unix-socket WebSocket bridge.
140
117
  transport = new RelayTransport(nodeId, { socketPath: apiSocketPath() });
141
118
  }
142
119
  }
143
120
  const socket = new BrokerClient(nodeId, { transport });
144
- const earlyFrames = [];
145
- let collectFrame;
146
- /** One error shape for a connect-time failure, whether the connect race below
147
- * caught it or the deferred `assertConnected` checkpoint did. */
121
+ const local = canvasName === undefined && machine === undefined;
122
+ /** One error shape for a connect-time failure. */
148
123
  const toAttachError = (err) => {
149
124
  // An upgrade the daemon refused with an API error shows as that error, as the attach ensure it replaced did.
150
125
  const refusal = err?.refusal;
@@ -165,89 +140,46 @@ hello) {
165
140
  next: 'Check the node has a running headless broker.',
166
141
  });
167
142
  };
168
- // A remote crtrd attach connection can close after its WebSocket upgrade when
169
- // its broker socket drops. Install a listener before dialing and keep it
170
- // through synchronous TUI/editor setup, so `assertConnected` can surface any
171
- // terminal startup failure at its one checkpoint immediately before permanent
172
- // socket wiring. Failures after that are mid-session and belong to the
173
- // reconnect supervisor, as they do for a local socket.
174
- let terminalStartupError;
175
- socket.on('error', (err) => {
176
- if (terminalStartupError === undefined)
177
- terminalStartupError = err;
178
- });
179
- // Connect FIRST (race connect/error) so a missing broker exits non-zero
180
- // cleanly, BEFORE the TUI takes over the terminal. Offline parked focus is
181
- // the one intentional exception: reconnect owns its first dial after paint.
182
- if (initialSnapshot === undefined) {
183
- await new Promise(async (resolve, reject) => {
184
- const onConnect = () => {
185
- cleanup();
186
- resolve();
187
- };
188
- const onErr = (err) => {
189
- cleanup();
190
- reject(err);
191
- };
192
- const cleanup = () => {
193
- socket.off('connect', onConnect);
194
- socket.off('error', onErr);
195
- };
196
- socket.on('connect', onConnect);
197
- socket.on('error', onErr);
198
- socket.connect();
199
- }).catch(async (err) => {
200
- // A Mac's upgrade refuses a parked node it was told not to wake: show its saved snapshot, offline, as a local parked focus does.
201
- if (machine !== undefined && !wakeParked && String(err?.message).includes('node_dormant')) {
202
- const saved = await cliClient().getSnapshot(nodeId).catch((e) => rethrowAsCliError(e, 'The node may be finalized or otherwise not attachable.'));
203
- initialSnapshot = saved.snapshot;
204
- initialCommands = saved.commands;
205
- return;
143
+ const parkedSnapshot = async () => {
144
+ const saved = await cliClient().getSnapshot(nodeId);
145
+ // The API DTO stays dependency-light and structural; this viewer is the
146
+ // consumer that knows the complete broker snapshot contract.
147
+ return { snapshot: saved.snapshot, commands: saved.commands };
148
+ };
149
+ const dial = async () => {
150
+ if (local) {
151
+ // Attach revives a dormant node (B2 acceptance): the server-side ensureAttach runs reviveNode (the ONE sanctioned launcher)
152
+ // and waits for the broker's view socket. The daemon, not the broker, owns attending viewer presence.
153
+ try {
154
+ const attach = await cliClient().ensureAttach(nodeId, { resume: true, revive: true, wakeParked });
155
+ // A parked node focused without waking has deliberately no socket to wait for.
156
+ if (attach.parked)
157
+ return await parkedSnapshot();
206
158
  }
207
- throw toAttachError(err);
208
- });
209
- // A broker listens before its session exists and answers `hello` only once it does. Wait for that answer here, so the caller's screen stays up and
210
- // no input is accepted until the session is real. Every frame from the welcome on is kept for the viewer to replay once its handlers exist.
211
- if (hello !== undefined) {
159
+ catch (err) {
160
+ rethrowAsCliError(err, 'The node may be finalized or otherwise not attachable.');
161
+ }
162
+ await preWaitForViewSocket(nodeId);
163
+ }
164
+ try {
212
165
  await new Promise((resolve, reject) => {
213
- const onFrame = (frame) => {
214
- earlyFrames.push(frame);
215
- if (frame.type === 'welcome') {
216
- cleanup();
217
- resolve();
218
- }
219
- };
220
- const onClose = () => { cleanup(); reject(new BrokerUnavailableError(nodeId, `the broker of node ${nodeId} closed before its session was ready; it did not start`)); };
166
+ const onConnect = () => { cleanup(); resolve(); };
221
167
  const onErr = (err) => { cleanup(); reject(err); };
222
- const cleanup = () => { socket.off('error', onErr); socket.off('close', onClose); if (!earlyFrames.some((f) => f.type === 'welcome'))
223
- socket.off('frame', onFrame); };
224
- collectFrame = onFrame;
225
- socket.on('frame', onFrame);
226
- socket.on('close', onClose);
168
+ const cleanup = () => { socket.off('connect', onConnect); socket.off('error', onErr); };
169
+ socket.on('connect', onConnect);
227
170
  socket.on('error', onErr);
228
- socket.send({ type: 'hello', role: hello.role, client_id: hello.clientId, term: { cols: process.stdout.columns ?? 80, rows: process.stdout.rows ?? 24 } });
229
- }).catch((err) => {
230
- throw toAttachError(err);
171
+ socket.connect();
231
172
  });
232
173
  }
233
- }
234
- return {
235
- remote,
236
- canvasSource,
237
- meta,
238
- nodeIdentity,
239
- socket,
240
- ...(initialSnapshot === undefined ? {} : { initialSnapshot, initialCommands }),
241
- earlyFrames,
242
- takeEarlyFrames: () => {
243
- if (collectFrame !== undefined)
244
- socket.off('frame', collectFrame);
245
- collectFrame = undefined;
246
- return earlyFrames.splice(0);
247
- },
248
- assertConnected: () => {
249
- if (initialSnapshot === undefined && terminalStartupError !== undefined)
250
- throw toAttachError(terminalStartupError);
251
- },
174
+ catch (err) {
175
+ // A Mac's upgrade refuses a parked node it was told not to wake: show its saved snapshot, offline, as a local parked focus does.
176
+ if (machine !== undefined && !wakeParked && String(err?.message).includes('node_dormant')) {
177
+ return await parkedSnapshot().catch((e) => rethrowAsCliError(e, 'The node may be finalized or otherwise not attachable.'));
178
+ }
179
+ throw toAttachError(err);
180
+ }
181
+ mark('viewer.transport_open');
182
+ return undefined;
252
183
  };
184
+ return { remote, canvasSource, meta, nodeIdentity, socket, dial };
253
185
  }
@@ -59,7 +59,7 @@ export function createInputController(ctx, km, capabilities, hooks) {
59
59
  // engine's auth, which a read-only viewer must not do. Unwired here means the
60
60
  // slash context carries no picker at all, so `/login` and `/logout` report
61
61
  // themselves unavailable rather than reaching a `reload_auth` frame.
62
- const reloadAuth = () => socket.send({ type: 'reload_auth' });
62
+ const reloadAuth = () => hooks.send({ type: 'reload_auth' });
63
63
  const authPickers = !capabilities.permits('auth')
64
64
  ? {}
65
65
  : {
@@ -73,8 +73,8 @@ export function createInputController(ctx, km, capabilities, hooks) {
73
73
  },
74
74
  };
75
75
  const input = new InputController(tui, editor, km, {
76
- onCommand: (frame) => socket.send(frame),
77
- onDialogResponse: (resp) => socket.send(resp),
76
+ onCommand: hooks.send,
77
+ onDialogResponse: hooks.send,
78
78
  onNotice: (msg) => setNotice(msg),
79
79
  // The slash context: `/promote` targets this node, `/resume-node` opens
80
80
  // scoped to its profile, `remote` structurally omits the local-only
@@ -16,7 +16,7 @@ export function createReconnect(ctx, hooks) {
16
16
  const { nodeId, socket, canvasSource } = ctx;
17
17
  let lastSocketError;
18
18
  let reconnecting = false;
19
- let viewerDormant = hooks.initialDormant === true;
19
+ let viewerDormant = false;
20
20
  // Captured at give-up: a finished node closes its pane; a deleted one keeps
21
21
  // the "broker gone" corpse.
22
22
  let finalizedDone = false;
@@ -71,9 +71,12 @@ export function createReconnect(ctx, hooks) {
71
71
  // successful redial re-sends `hello`; the new broker's `welcome` runs
72
72
  // applySnapshot, which resetChat()s the pane and rebuilds from the persisted
73
73
  // .jsonl — a clean "clear + continuation" for free.
74
- const attemptReconnect = async () => {
74
+ // `quiet`: the node is already known to be parked, so nothing is "refreshing" and no notice of ours is shown until the row says otherwise.
75
+ const attemptReconnect = async (quiet = false) => {
75
76
  reconnecting = true;
76
- hooks.setNotice('↻ node refreshing — reconnecting…', { sticky: true });
77
+ let noticed = !quiet;
78
+ if (noticed)
79
+ hooks.setNotice('↻ node refreshing — reconnecting…', { sticky: true });
77
80
  let delay = 200;
78
81
  try {
79
82
  while (!stopped && !hooks.isTornDown()) {
@@ -107,7 +110,10 @@ export function createReconnect(ctx, hooks) {
107
110
  viewerDormant = dormant;
108
111
  if (enteredDormancy)
109
112
  hooks.onEnterDormancy();
110
- hooks.setNotice(deadOrCanceled ? `node is ${row?.status} — waiting for a revive` : dormant ? '' : '↻ node refreshing — reconnecting…', { sticky: !dormant });
113
+ if (noticed || !dormant) {
114
+ hooks.setNotice(deadOrCanceled ? `node is ${row?.status} — waiting for a revive` : dormant ? '' : '↻ node refreshing — reconnecting…', { sticky: !dormant });
115
+ noticed = !dormant;
116
+ }
111
117
  try {
112
118
  const redialed = await Promise.race([
113
119
  socket.redial({ brokerUnavailableIsExpected: dormant || deadOrCanceled }).then(() => true),
@@ -174,8 +180,9 @@ export function createReconnect(ctx, hooks) {
174
180
  startDormant: () => {
175
181
  if (reconnecting || stopped || hooks.isTornDown())
176
182
  return;
183
+ viewerDormant = true;
177
184
  hooks.onEnterDormancy();
178
- void attemptReconnect();
185
+ void attemptReconnect(true);
179
186
  },
180
187
  isDormant: () => viewerDormant,
181
188
  lastSocketError: () => lastSocketError,
@@ -72,6 +72,9 @@ export function createTeardown(s, hooks) {
72
72
  `broker gone — node ${nodeId} is no longer running its engine.`;
73
73
  process.stderr.write(`\n${msg}\nReattach with: ${hooks.reattachCommand}\n`);
74
74
  }
75
+ const unsent = hooks.undelivered();
76
+ if (unsent.length > 0)
77
+ process.stderr.write(`\nNot delivered:\n${unsent.join('\n---\n')}\n`);
75
78
  // Local tmux only — a remote attach has no local pane to close, and a
76
79
  // non-tmux/pipe invocation just prints the line. Pane close is pane-granular
77
80
  // (siblings in a swap-pane window survive); the daemon reconciles the
@@ -92,18 +92,16 @@ onConnected) {
92
92
  await loadPersonSettingsViaApi();
93
93
  else
94
94
  installPersonSettingsDto(held.settings);
95
- // 1. Get onto the broker before anything paints (session/connection.ts):
96
- // resolve local-vs-relay, revive the node server-side if it is dormant,
97
- // and win the connect race. A failure here is still a plain CLI error.
95
+ // 1. Resolve the attach target (session/connection.ts). Nothing here waits for the broker:
96
+ // the viewer paints first and `connection.dial()` (revive, connect, hello) runs after it, so a
97
+ // dial failure is shown by the viewer (see `dialBroker` below). An unknown node is still a plain CLI error.
98
98
  // `remote` is THE single remote fact (it selects the canvas and turns off local-host operations; `role` alone decides driving) for this whole session,
99
99
  // derived once here and threaded via `AttachSession` — every local disk
100
100
  // read, native slash command, pane tag and lifecycle action gates on it,
101
101
  // and no collaborator may re-derive it.
102
- mark('viewer.connect_start', { node: nodeId });
103
102
  const role = resolveHelloRole(observer);
104
103
  const clientId = randomUUID();
105
- const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node, { role, clientId });
106
- mark(connection.initialSnapshot === undefined ? 'viewer.socket_connected' : 'viewer.offline_snapshot_ready');
104
+ const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node);
107
105
  const { remote, canvasSource, meta, socket } = connection;
108
106
  // 2. Theme + keybindings — pi's components throw "Theme not initialized"
109
107
  // otherwise. One KeybindingsManager feeds BOTH editor and input; the
@@ -328,7 +326,7 @@ onConnected) {
328
326
  'crtr.attach.verbosity.less': () => setNotice(lessDetailNotice(chatView.lessDetail())),
329
327
  };
330
328
  let reconnect;
331
- const capabilities = createViewerCapabilitiesForInput(ctx, () => reconnect === undefined ? connection.initialSnapshot !== undefined : reconnect.isDormant());
329
+ const capabilities = createViewerCapabilitiesForInput(ctx, () => reconnect !== undefined && reconnect.isDormant());
332
330
  // Per-user completion frecency (usage bias), shared by the editor inventory
333
331
  // that RANKS completions and the input controller that RECORDS uses. One
334
332
  // store per viewer session; persists to the user scope root.
@@ -448,6 +446,24 @@ onConnected) {
448
446
  refreshInFlightTools: () => { chatView.refreshInFlightTools(); void chatView.refreshPageBlocks(); },
449
447
  pollGit: editorChrome.pollGit,
450
448
  });
449
+ // Frames the person sends before the broker's first welcome are held and delivered, in order, once it arrives:
450
+ // the broker accepts no turn before its session is ready. Their text already shows in the pending (gray) state.
451
+ const heldFrames = [];
452
+ let welcomed = false;
453
+ // True once nothing is held any more: delivered at the first welcome, or handed to a parked node's wake path.
454
+ let settled = false;
455
+ const sendToBroker = (frame) => {
456
+ if (welcomed)
457
+ socket.send(frame);
458
+ else
459
+ heldFrames.push(frame);
460
+ };
461
+ const onFirstWelcome = () => {
462
+ welcomed = true;
463
+ settled = true;
464
+ for (const frame of heldFrames.splice(0))
465
+ socket.send(frame);
466
+ };
451
467
  // Input layer — session/input-wiring.ts answers every hook InputController
452
468
  // takes (socket sinks, slash context, pickers, auth, dormant submit).
453
469
  const input = createInputController(ctx, km, capabilities, {
@@ -470,6 +486,7 @@ onConnected) {
470
486
  whipAnimation.play();
471
487
  },
472
488
  onMessageSent: (text) => chatView.addPendingSend(text),
489
+ send: sendToBroker,
473
490
  frecency,
474
491
  });
475
492
  const whip = () => {
@@ -672,22 +689,29 @@ onConnected) {
672
689
  },
673
690
  // Reached lazily: reconnect is built after teardown (it needs `isTornDown`),
674
691
  // and this is only ever read once teardown actually runs.
675
- lastSocketError: () => reconnect.lastSocketError(),
692
+ lastSocketError: () => startupFailure ?? reconnect.lastSocketError(),
693
+ undelivered: () => (settled ? [] : [...heldFrames.flatMap((f) => ('text' in f ? [f.text] : [])), ...(editor.getText().trim() === '' ? [] : [editor.getText()])]),
676
694
  reattachCommand: `crtr surface attach to ${quoteIfNeeded(nodeId)}` +
677
695
  (observer ? ' --observer' : '') +
678
696
  (canvasName !== undefined ? ` --canvas ${quoteIfNeeded(canvasName)}` : ''),
679
697
  tagPane: paneTag.pane,
680
698
  });
681
699
  const teardown = lifecycle.teardown;
700
+ let startupFailure;
682
701
  // The reconnect supervisor: the hello handshake, the permanent socket
683
702
  // handlers, and the redial policy that decides whether a closed socket means
684
703
  // "hold the pane, the broker is coming back" or "this node is genuinely gone".
685
704
  reconnect = createReconnect(ctx, {
686
705
  role,
687
706
  remote,
688
- initialDormant: connection.initialSnapshot !== undefined,
689
707
  clientId,
690
- onFrame: handleBrokerFrame,
708
+ onFrame: (frame) => {
709
+ if (frame.type === 'welcome' && !welcomed)
710
+ mark('viewer.welcome_received');
711
+ handleBrokerFrame(frame);
712
+ if (frame.type === 'welcome' && !welcomed)
713
+ onFirstWelcome();
714
+ },
691
715
  setNotice,
692
716
  isTornDown: () => lifecycle.isTornDown(),
693
717
  teardown,
@@ -699,33 +723,12 @@ onConnected) {
699
723
  sync.patchLocal({ isStreaming: false });
700
724
  },
701
725
  });
702
- // 5. The startup checkpoint. A relay's post-upgrade "no node"/"no running
703
- // broker" close may have arrived any time during the synchronous setup
704
- // above; connection.ts's never-removed error listener is how it survives
705
- // that gap. Surface it BEFORE the reconnect supervisor takes over (which
706
- // would misclassify a genuinely-gone target as a live session that
707
- // dropped) and before the pane tag is claimed (so a failed attach never
708
- // leaves a stale tag behind).
709
- connection.assertConnected();
710
726
  paneTag.set();
711
- reconnect.install();
712
- // 6. Lay out, paint, start, then handshake — starting before the handshake
713
- // means the welcome's applySnapshot renders into a live TUI.
727
+ // 5. Lay out and paint; the broker connection follows (`dialBroker`).
714
728
  layout.mount();
715
729
  // Synchronous with tui.start(): the caller's screen gives the terminal back and the viewer takes it in the same tick, with no cooked-mode gap.
716
730
  onConnected?.();
717
731
  tui.start();
718
- if (connection.initialSnapshot !== undefined) {
719
- // Seed the same state/transcript owners a broker welcome feeds. No socket
720
- // frame is fabricated: the first real welcome remains authoritative and
721
- // ChatView's generation guard replaces this saved reconstruction cleanly.
722
- sync.fold({ type: 'welcome', snapshot: connection.initialSnapshot, role });
723
- void chatView.applySnapshot(connection.initialSnapshot);
724
- inventory.setCommands(connection.initialCommands);
725
- // A parked conversation has no broker, so the attach bridge never sees it shown.
726
- if (!remote)
727
- void cliClient().markNodeRead(nodeId).catch(() => undefined);
728
- }
729
732
  if (userConfig.whip_mode && initialWhip)
730
733
  whipAnimation.play();
731
734
  mouse.reassert();
@@ -886,20 +889,62 @@ onConnected) {
886
889
  // ProcessTerminal negotiated the keyboard protocol on OUR pi-tui instance; the
887
890
  // editor reads the flag from its own (possibly separate) instance.
888
891
  void mirrorKittyProtocolToEditor(procTerminal.kittyProtocolActive);
889
- // A live viewer waits for welcome so the synchronous tmux sweep cannot block
890
- // that frame. If the broker vanishes before welcome, reconnect's dormancy
891
- // callback schedules the same install. A dormant viewer schedules it directly.
892
- if (connection.initialSnapshot !== undefined)
892
+ // The viewer is painted and interactive: now revive, connect and say hello. A live viewer's tmux binding install waits for the welcome
893
+ // so the synchronous tmux sweep cannot block that frame; a parked one installs below, and reconnect's dormancy callback covers a broker that vanishes.
894
+ const dialBroker = async () => {
895
+ mark('viewer.connect_start', { node: nodeId });
896
+ let parked;
897
+ try {
898
+ parked = await connection.dial();
899
+ }
900
+ catch (err) {
901
+ if (lifecycle.isTornDown())
902
+ return;
903
+ // The connection failed: teardown prints the reason and whatever the person entered that the broker never saw.
904
+ startupFailure = err instanceof Error ? err.message : String(err);
905
+ process.exitCode = 1;
906
+ teardown('broker-gone');
907
+ return;
908
+ }
909
+ if (lifecycle.isTornDown())
910
+ return;
911
+ reconnect.install();
912
+ if (parked === undefined) {
913
+ reconnect.sendHello();
914
+ mark('viewer.hello_sent');
915
+ return;
916
+ }
917
+ mark('viewer.offline_snapshot_ready');
918
+ // Text sent while the dial was still running has no broker to hold it: deliver it as the wake message a parked viewer's own sends use.
919
+ // An engine command (`/x`, `!x`) is refused as a later parked submission is, and returned to the editor.
920
+ settled = true;
921
+ const refused = [];
922
+ for (const frame of heldFrames.splice(0)) {
923
+ if (!('text' in frame))
924
+ continue;
925
+ const t = frame.text.trim();
926
+ if (t.startsWith('/') || t.startsWith('!'))
927
+ refused.push(frame.text);
928
+ else
929
+ void cliClient().sendMessage(nodeId, { body: frame.text, from: 'human' }).catch((e) => setNotice(`Couldn't wake node: ${e instanceof Error ? e.message : String(e)}`));
930
+ }
931
+ if (refused.length > 0) {
932
+ editor.setText([...refused, editor.getText()].filter((x) => x.trim() !== '').join('\n'));
933
+ setNotice('This node is parked — submit a message to wake it; broker commands need a live engine');
934
+ }
935
+ // Seed the same state/transcript owners a broker welcome feeds. No socket
936
+ // frame is fabricated: the first real welcome remains authoritative and
937
+ // ChatView's generation guard replaces this saved reconstruction cleanly.
938
+ sync.fold({ type: 'welcome', snapshot: parked.snapshot, role });
939
+ void chatView.applySnapshot(parked.snapshot);
940
+ inventory.setCommands(parked.commands);
941
+ // A parked conversation has no broker, so the attach bridge never sees it shown.
942
+ if (!remote)
943
+ void cliClient().markNodeRead(nodeId).catch(() => undefined);
893
944
  scheduleTmuxBindingInstall();
894
- if (connection.initialSnapshot === undefined) {
895
- // The hello went out during the connect and the broker's welcome answered it; replay what it sent through the handlers just installed.
896
- mark('viewer.hello_sent');
897
- for (const frame of connection.takeEarlyFrames())
898
- socket.emit('frame', frame);
899
- }
900
- else {
901
945
  reconnect.startDormant();
902
- }
946
+ };
947
+ void dialBroker();
903
948
  chromeRefresh.start();
904
949
  if (startupReviewId !== undefined)
905
950
  void openReviewSurfaceById(surfaceHost, startupReviewId);
@@ -8,6 +8,7 @@
8
8
  // header and never logs it.
9
9
  import { EventEmitter } from 'node:events';
10
10
  import { WebSocket } from 'ws';
11
+ import { mark } from '../timing.js';
11
12
  import { classify } from '../fault-classifier.js';
12
13
  import { AttachRefusedError, BrokerUnavailableError } from './transport.js';
13
14
  function relayUrl(target, nodeId, wakeParked) {
@@ -46,10 +47,17 @@ export class RelayTransport extends EventEmitter {
46
47
  return relayUrl(this.target, this.nodeId, this.wakeParked);
47
48
  }
48
49
  dial() {
50
+ // CRTR_TIMING marks (stderr, same timeline as `viewer.*`): the target kind and the dial's own steps, each with the duration since this dial began.
51
+ const dialStart = performance.now();
52
+ const since = () => (performance.now() - dialStart).toFixed(1);
53
+ const kind = 'socketPath' in this.target ? 'local' : 'remote';
54
+ mark('relay.dial_start', { node: this.nodeId, target: kind });
49
55
  const ws = new WebSocket(this.url, {
50
56
  ...('relayToken' in this.target ? { headers: { authorization: `Bearer ${this.target.relayToken}` } } : {}),
51
57
  perMessageDeflate: false,
52
58
  });
59
+ ws.once('upgrade', () => mark('relay.upgrade_response', { node: this.nodeId, target: kind, since_dial_ms: since() }));
60
+ ws.once('open', () => mark('relay.ws_open', { node: this.nodeId, target: kind, since_dial_ms: since() }));
53
61
  // A refusal's JSON body carries the reason (`broker_not_ready`, `attach_revive_failed`); ws would drop it as a bare status.
54
62
  ws.on('unexpected-response', (_req, res) => {
55
63
  let text = '';
@@ -39,7 +39,7 @@ class ForwardedViewLink extends EventEmitter {
39
39
  this.environmentId = environmentId;
40
40
  this.nodeId = nodeId;
41
41
  const opened = performance.now();
42
- this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.forwarded_view_ready', fields: { environment: this.environmentId, node: this.nodeId, open_to_ready_ms: Math.round((performance.now() - opened) * 10) / 10 } }));
42
+ this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.forwarded_view_ready', node_id: this.nodeId, fields: { environment: this.environmentId, open_to_ready_ms: Math.round((performance.now() - opened) * 10) / 10 } }));
43
43
  this.dial().catch((error) => this.finish(error instanceof Error ? error.message : String(error)));
44
44
  }
45
45
  get destroyed() { return this.ended; }
@@ -119,7 +119,11 @@ class ForwardedViewLink extends EventEmitter {
119
119
  function openReadyMachineView(environmentId, nodeId, timeoutMs) {
120
120
  return new Promise((resolve) => {
121
121
  const view = openMachineView(environmentId, nodeId);
122
- const timer = setTimeout(() => { resolve(null); view.destroy(); }, timeoutMs);
122
+ const timer = setTimeout(() => {
123
+ emitEvent({ level: 'info', event: 'daemon.timing.view_ready_timeout', node_id: nodeId, fields: { channel: view.channel ?? '', timeout_ms: timeoutMs } });
124
+ resolve(null);
125
+ view.destroy();
126
+ }, timeoutMs);
123
127
  // The no-op error listener stays on the returned channel until its user attaches its own: an error before then must not throw.
124
128
  view.on('error', () => { });
125
129
  view.on('connect', () => { clearTimeout(timer); resolve(view); });
@@ -188,9 +188,13 @@ export class HeldLink extends EventEmitter {
188
188
  case 'wedge':
189
189
  await this.recordWedge(frame);
190
190
  return;
191
- case 'view.ready':
192
- this.channels.get(frame.channel)?.emit('connect');
191
+ case 'view.ready': {
192
+ const channel = this.channels.get(frame.channel);
193
+ // One mark per ready frame (a viewer connection sends one); a ready for a channel already closed or never opened here says so.
194
+ emitEvent({ level: 'info', event: 'daemon.timing.view_ready_received', ...(channel === undefined ? {} : { node_id: channel.nodeId }), fields: { channel: frame.channel, known: channel !== undefined, ...(channel === undefined ? {} : { open_to_ready_ms: channel.sinceOpenMs() }) } });
195
+ channel?.emit('connect');
193
196
  return;
197
+ }
194
198
  case 'view.data':
195
199
  this.channels.get(frame.channel)?.emit('data', Buffer.from(frame.bytes, 'base64'));
196
200
  return;
@@ -309,18 +313,23 @@ async function endUnlistedMachineExecutions(environmentId, listed, openedAt) {
309
313
  /** A viewer channel to one node's view.sock on the Mac, as the relay's broker-side link. */
310
314
  export class MachineViewLink extends EventEmitter {
311
315
  link;
316
+ nodeId;
312
317
  ended = false;
313
318
  failed = false;
314
319
  channel = randomUUID();
320
+ opened = performance.now();
315
321
  constructor(link, nodeId) {
316
322
  super();
317
323
  this.link = link;
324
+ this.nodeId = nodeId;
318
325
  link.channels.set(this.channel, this);
319
- const opened = performance.now();
320
- this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.machine_view_ready', fields: { channel: this.channel, node: nodeId, open_to_ready_ms: Math.round((performance.now() - opened) * 10) / 10 } }));
321
- if (!link.send({ type: 'view.open', channel: this.channel, node: nodeId }))
326
+ this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.machine_view_ready', node_id: nodeId, fields: { channel: this.channel, open_to_ready_ms: this.sinceOpenMs() } }));
327
+ const sent = link.send({ type: 'view.open', channel: this.channel, node: nodeId });
328
+ emitEvent({ level: 'info', event: 'daemon.timing.view_open_sent', node_id: nodeId, fields: { channel: this.channel, sent, link_buffered_bytes: link.ws.bufferedAmount, send_sync_ms: this.sinceOpenMs() } });
329
+ if (!sent)
322
330
  queueMicrotask(() => this.finish('machine link closed'));
323
331
  }
332
+ sinceOpenMs() { return Math.round((performance.now() - this.opened) * 10) / 10; }
324
333
  get destroyed() { return this.ended; }
325
334
  write(line) {
326
335
  return !this.ended && this.link.send({ type: 'view.data', channel: this.channel, bytes: Buffer.from(line).toString('base64') });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.700",
3
+ "version": "0.3.702",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.700",
3
+ "version": "0.3.702",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.700",
3
+ "version": "0.3.702",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.700",
31
- "@north-light/identity": "0.3.700"
30
+ "@north-light/api": "0.3.702",
31
+ "@north-light/identity": "0.3.702"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {