shellpuppet 0.4.2 → 0.5.0

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 (72) hide show
  1. package/README.md +16 -5
  2. package/dist/agents/agy/index.js +1 -1
  3. package/dist/agents/agy/index.js.map +1 -1
  4. package/dist/agents/claude/index.js +1 -1
  5. package/dist/agents/claude/index.js.map +1 -1
  6. package/dist/agents/codex/draft.js +13 -6
  7. package/dist/agents/codex/draft.js.map +1 -1
  8. package/dist/agents/codex/index.js +1 -1
  9. package/dist/agents/codex/index.js.map +1 -1
  10. package/dist/agents/codex/nudge.js +7 -1
  11. package/dist/agents/codex/nudge.js.map +1 -1
  12. package/dist/agents/grok/index.js +1 -1
  13. package/dist/agents/grok/index.js.map +1 -1
  14. package/dist/agents/grok/nudge.js +13 -5
  15. package/dist/agents/grok/nudge.js.map +1 -1
  16. package/dist/agents/hermes/frame.js +4 -4
  17. package/dist/agents/hermes/frame.js.map +1 -1
  18. package/dist/agents/hermes/index.js +1 -1
  19. package/dist/agents/hermes/index.js.map +1 -1
  20. package/dist/agents/mimo/index.js +1 -1
  21. package/dist/agents/mimo/index.js.map +1 -1
  22. package/dist/agents/muse/index.js +1 -1
  23. package/dist/agents/muse/index.js.map +1 -1
  24. package/dist/agents/muse/nudge.js +8 -3
  25. package/dist/agents/muse/nudge.js.map +1 -1
  26. package/dist/agents/nudgeReading.d.ts +2 -0
  27. package/dist/agents/nudgeReading.js +3 -3
  28. package/dist/agents/nudgeReading.js.map +1 -1
  29. package/dist/agents/opencode/index.js +1 -1
  30. package/dist/agents/opencode/index.js.map +1 -1
  31. package/dist/agents/qoder/index.js +1 -1
  32. package/dist/agents/qoder/index.js.map +1 -1
  33. package/dist/agents/types.d.ts +4 -0
  34. package/dist/cli/index.js +244 -5
  35. package/dist/cli/index.js.map +1 -1
  36. package/dist/client/http.d.ts +3 -0
  37. package/dist/client/http.js +7 -0
  38. package/dist/client/http.js.map +1 -1
  39. package/dist/client/input.d.ts +18 -0
  40. package/dist/client/input.js +15 -0
  41. package/dist/client/input.js.map +1 -1
  42. package/dist/core/session.d.ts +17 -2
  43. package/dist/core/session.js +52 -12
  44. package/dist/core/session.js.map +1 -1
  45. package/dist/core/windowsPtyStart.d.ts +2 -0
  46. package/dist/core/windowsPtyStart.js +6 -0
  47. package/dist/core/windowsPtyStart.js.map +1 -1
  48. package/dist/daemon/audit.d.ts +1 -1
  49. package/dist/daemon/audit.js +1 -1
  50. package/dist/daemon/index.js +1 -0
  51. package/dist/daemon/index.js.map +1 -1
  52. package/dist/daemon/launchProfiles.d.ts +6 -0
  53. package/dist/daemon/launchProfiles.js +21 -4
  54. package/dist/daemon/launchProfiles.js.map +1 -1
  55. package/dist/daemon/liveness.d.ts +11 -0
  56. package/dist/daemon/liveness.js +39 -0
  57. package/dist/daemon/liveness.js.map +1 -1
  58. package/dist/daemon/schedules.d.ts +1 -1
  59. package/dist/daemon/schedules.js +8 -3
  60. package/dist/daemon/schedules.js.map +1 -1
  61. package/dist/daemon/server.d.ts +13 -0
  62. package/dist/daemon/server.js +274 -58
  63. package/dist/daemon/server.js.map +1 -1
  64. package/dist/daemon/sessionFeed.d.ts +1 -1
  65. package/dist/daemon/sessionFeed.js +3 -1
  66. package/dist/daemon/sessionFeed.js.map +1 -1
  67. package/dist/mcp/tools.js +12 -9
  68. package/dist/mcp/tools.js.map +1 -1
  69. package/dist/viewer/dashboard.css +20 -7
  70. package/dist/viewer/dashboard.js +120 -31
  71. package/dist/viewer/pane.js +149 -20
  72. package/package.json +1 -1
@@ -20,7 +20,7 @@ import { Mailbox, MailboxError, NAME_PATTERN, buildNudge } from '../core/mailbox
20
20
  import { buildMessagingPolicy, DEFAULT_NUDGE_INTERVAL_MS, DEFAULT_NUDGES_PER_MINUTE } from './config.js';
21
21
  import { NudgeScheduler } from './nudgeScheduler.js';
22
22
  import { ScheduleStore, PromptScheduler, watchSchedules } from './schedules.js';
23
- import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, WindowsWithoutConPTYError, credentialShapedNames, submitOutcome, } from '../core/session.js';
23
+ import { CommandNotFoundError, DEFAULT_SESSION_ENV, SessionInputFailedError, SessionProgramEndedError, TemporaryResizeNotReadyError, WindowsWithoutConPTYError, credentialShapedNames, submitOutcome, } from '../core/session.js';
24
24
  import { NativePtyUnavailableError } from '../core/nativePty.js';
25
25
  import { checkSessionCapacity, commandLine, compilePolicy, evaluateCommand } from '../core/policy.js';
26
26
  import { keyToBytes, knownKeys } from '../core/keys.js';
@@ -45,7 +45,7 @@ import { terminalReportKind } from './terminalReports.js';
45
45
  import { ViewerSync } from './viewerSync.js';
46
46
  import { SessionFeed } from './sessionFeed.js';
47
47
  import { compileProfilePolicy, copyDaemonEnv, describeProfileText, expandProfileText, resolveLaunchCommand, resolveAnyFolder, } from './launchProfiles.js';
48
- import { listRootFolders, resolveRootFolder } from './launchProfiles.js';
48
+ import { DEFAULT_LAUNCHES_PER_MINUTE, listRootFolders, parseLaunchesPerMinute, resolveRootFolder } from './launchProfiles.js';
49
49
  import { chooseFolder, FOLDER_PICKER_TIMEOUT_MS, FolderPickerFailureError, FolderPickerUnavailableError, FolderPickerTimeoutError } from './folderPicker.js';
50
50
  const DEFAULT_IDLE_MS = 30 * 60_000;
51
51
  /** Stop waits this long for an automatic dashboard launch before continuing. */
@@ -500,6 +500,12 @@ export class Daemon {
500
500
  dashboardSocketCredential = new WeakMap();
501
501
  /** External geometry acts invalidate a temporary wider read's restoration. */
502
502
  geometryEpoch = new Map();
503
+ /** One daemon order for layout notices and deliberate grid choices. */
504
+ geometryOrder = new Map();
505
+ choiceRevision = new Map();
506
+ controllerChoiceRevision = new Map();
507
+ explicitResizeRevision = new Map();
508
+ dashboardLayouts = new WeakMap();
503
509
  widerReads = new Map();
504
510
  /** Subscribers to the daemon-wide event stream (`/events`). */
505
511
  eventSockets = new Map();
@@ -556,6 +562,7 @@ export class Daemon {
556
562
  sessionEnv;
557
563
  /** The profiles the dashboard may name, and the entries that did not load. */
558
564
  launchProfiles;
565
+ launchesPerMinute;
559
566
  daemonEnv;
560
567
  cliPath;
561
568
  /** The global policy, kept here so a launch can report it before creating. */
@@ -593,6 +600,7 @@ export class Daemon {
593
600
  };
594
601
  this.sessionEnv = options.sessionEnv ?? DEFAULT_SESSION_ENV;
595
602
  this.launchProfiles = options.launchProfiles ?? { profiles: [], problems: [] };
603
+ this.launchesPerMinute = this.launchProfiles.launchesPerMinute ?? DEFAULT_LAUNCHES_PER_MINUTE;
596
604
  this.daemonEnv = options.daemonEnv ?? process.env;
597
605
  this.cliPath = fileURLToPath(new URL('../../dist/cli/index.js', import.meta.url));
598
606
  this.compiledPolicy = compilePolicy(options.policy);
@@ -863,7 +871,14 @@ export class Daemon {
863
871
  });
864
872
  }, this.options.promptScanIntervalMs ?? PROMPT_SCAN_INTERVAL_MS);
865
873
  this.promptScanTimer.unref();
866
- this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger);
874
+ this.stopScheduleWatch = watchSchedules(home, this.schedules, this.logger, (raw, initial) => {
875
+ if (initial && raw['launcher'] === undefined)
876
+ return;
877
+ const allowance = parseLaunchesPerMinute(raw['launcher']);
878
+ this.launchesPerMinute = allowance.value;
879
+ if (!initial && allowance.problem !== undefined)
880
+ this.logger.warn('CONFIG PROBLEM', { problem: allowance.problem });
881
+ });
867
882
  this.promptScheduler.start();
868
883
  this.logger.info('daemon started', {
869
884
  port: this.portValue,
@@ -1074,11 +1089,22 @@ export class Daemon {
1074
1089
  for (const read of this.widerReads.values())
1075
1090
  read.abort.abort();
1076
1091
  const readsDone = Promise.allSettled([...this.widerReads.values()].map((read) => read.done));
1092
+ const widerDeadline = Date.now() + 250;
1077
1093
  await this.shutdownRecords;
1078
1094
  // A free port lets a successor retire the ownership marker. Keep it
1079
1095
  // bound through publication, then close without waiting for PTY teardown.
1080
1096
  const listenerClosed = this.closeServerOnly();
1081
- await readsDone;
1097
+ let widerTimer;
1098
+ const widerOutcome = await Promise.race([
1099
+ readsDone.then(() => 'settled'),
1100
+ new Promise((resolve) => {
1101
+ widerTimer = setTimeout(() => resolve('timeout'), Math.max(0, widerDeadline - Date.now()));
1102
+ }),
1103
+ ]);
1104
+ if (widerTimer !== undefined)
1105
+ clearTimeout(widerTimer);
1106
+ if (widerOutcome === 'timeout')
1107
+ this.logger.warn('wider reads exceeded shutdown restoration budget');
1082
1108
  for (const socket of this.sockets) {
1083
1109
  try {
1084
1110
  socket.close();
@@ -1984,10 +2010,10 @@ export class Daemon {
1984
2010
  }
1985
2011
  const now = this.now();
1986
2012
  this.pruneLaunchTimes(now);
1987
- if (this.launchTimes.length + this.pendingProfileStarts.size >= 8) {
2013
+ if (this.launchTimes.length + this.pendingProfileStarts.size >= this.launchesPerMinute) {
1988
2014
  this.auditDashboardRefusal(req, 'rate', launcher?.name);
1989
2015
  json(res, 429, {
1990
- error: 'Dashboard launch rate reached (8 in 60 seconds). Wait before starting another profile.',
2016
+ error: `Dashboard launch rate reached (${String(this.launchesPerMinute)} in 60 seconds). Wait before starting another profile.`,
1991
2017
  });
1992
2018
  return;
1993
2019
  }
@@ -2312,7 +2338,7 @@ export class Daemon {
2312
2338
  // Unauthenticated by design (§4.1): clients must be able to poll before
2313
2339
  // the token file settles. The instance id is an identity, not a secret.
2314
2340
  if (req.method === 'GET' && url.pathname === '/health') {
2315
- json(res, 200, { ok: true, version: this.version, pid: process.pid, instanceId: this.instanceId });
2341
+ json(res, 200, { ok: true, version: this.version, pid: process.pid, instanceId: this.instanceId, inputSubmitMode: 1 });
2316
2342
  return;
2317
2343
  }
2318
2344
  // The viewer page itself is served without auth, and must stay that way:
@@ -3035,11 +3061,20 @@ export class Daemon {
3035
3061
  json(res, 200, { schedules: this.promptScheduler.list() });
3036
3062
  return;
3037
3063
  }
3064
+ if (url.pathname === '/daemon/stop-info' && req.method === 'GET') {
3065
+ res.setHeader('Cache-Control', 'no-store');
3066
+ json(res, 200, { completion: { version: 1,
3067
+ role: this.options.exitProcessOnStop === true ? 'standalone' : 'embedded',
3068
+ pid: process.pid, instanceId: this.instanceId } });
3069
+ return;
3070
+ }
3038
3071
  if (segments[0] === 'daemon' && segments[1] === 'shutdown' && req.method === 'POST') {
3039
3072
  const body = await readBody(req);
3073
+ const completion = { version: 1, role: this.options.exitProcessOnStop === true ? 'standalone' : 'embedded',
3074
+ pid: process.pid, instanceId: this.instanceId };
3040
3075
  if (this.stopping) {
3041
3076
  await this.shutdownRecords;
3042
- json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
3077
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings, completion });
3043
3078
  return;
3044
3079
  }
3045
3080
  const force = asBoolean(body['force']) ?? false;
@@ -3054,7 +3089,7 @@ export class Daemon {
3054
3089
  const stopping = this.stop({ restart: body['restart'] === true });
3055
3090
  this.audit.record(actor, 'shutdown', undefined, { force, liveSessions: live });
3056
3091
  await this.shutdownRecords;
3057
- json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings });
3092
+ json(res, 200, { ok: true, stopping: true, warnings: this.shutdownWarnings, completion });
3058
3093
  void stopping.then(() => {
3059
3094
  this.options.onSelfStop?.('shutdown-request');
3060
3095
  });
@@ -3402,7 +3437,7 @@ export class Daemon {
3402
3437
  this.audit.record(actor, 'wider-read', id, { requested, original });
3403
3438
  try {
3404
3439
  if (target.cols !== original.cols || target.rows !== original.rows) {
3405
- await session.resize(target.cols, target.rows);
3440
+ await session.resize(target.cols, target.rows, { temporarySignal: abort.signal });
3406
3441
  announce();
3407
3442
  }
3408
3443
  const settled = await session.waitFor({ quiet: 250 }, {
@@ -3425,6 +3460,7 @@ export class Daemon {
3425
3460
  // Only a deliberate geometry act wins. A departing controller does
3426
3461
  // not choose a new size; keep the control state its departure left.
3427
3462
  const mayRestore = () => (this.geometryEpoch.get(id) ?? 0) === epoch &&
3463
+ this.manager.get(id) === session && !session.isKilled &&
3428
3464
  !session.geometryHeld && !session.exited &&
3429
3465
  session.cols === target.cols && session.rows === target.rows;
3430
3466
  restored = target.cols === original.cols && target.rows === original.rows
@@ -3449,6 +3485,9 @@ export class Daemon {
3449
3485
  const code = readError instanceof SessionProgramEndedError ? readError.exitCode : session.exitCode;
3450
3486
  json(res, 409, { error: endedRefusal(id, code, session.fault) });
3451
3487
  }
3488
+ else if (readError instanceof TemporaryResizeNotReadyError) {
3489
+ json(res, 409, { error: readError.message });
3490
+ }
3452
3491
  else if (readError !== undefined) {
3453
3492
  throw readError instanceof Error ? readError : new Error('Wider read failed with a non-Error value.');
3454
3493
  }
@@ -3481,6 +3520,17 @@ export class Daemon {
3481
3520
  return;
3482
3521
  }
3483
3522
  if (req.method === 'POST' && action === 'input') {
3523
+ const header = req.headers['x-shellpuppet-submit'];
3524
+ const submitMode = header === undefined ? undefined : header === 'auto' || header === 'on' || header === 'off' ? header : null;
3525
+ if (submitMode === null) {
3526
+ json(res, 400, { error: 'Invalid submit mode.' });
3527
+ return;
3528
+ }
3529
+ if (req.headers['x-shellpuppet-expected-instance'] !== undefined &&
3530
+ req.headers['x-shellpuppet-expected-instance'] !== this.instanceId) {
3531
+ json(res, 409, { error: 'The daemon changed after submit preflight.' });
3532
+ return;
3533
+ }
3484
3534
  const body = await readBody(req);
3485
3535
  const data = asString(body['data']);
3486
3536
  if (data === undefined) {
@@ -3503,7 +3553,9 @@ export class Daemon {
3503
3553
  const submit = body['submit'] === true;
3504
3554
  let written;
3505
3555
  try {
3506
- written = await session.writeWithResult(data);
3556
+ written = submitMode === undefined
3557
+ ? await session.writeWithResult(data)
3558
+ : await session.writeWithResult(data, { submitMode });
3507
3559
  }
3508
3560
  catch (error) {
3509
3561
  json(res, 409, {
@@ -3513,9 +3565,13 @@ export class Daemon {
3513
3565
  });
3514
3566
  return;
3515
3567
  }
3516
- const reporting = submit ? submitOutcome(written) : undefined;
3517
- this.audit.record(actor, 'input', id, { chars: data.length,
3518
- ...(reporting ? { submit: true, ...reporting } : {}) });
3568
+ const reporting = submitMode === undefined ? submit ? submitOutcome(written) : undefined
3569
+ : submitMode === 'off' || (submitMode === 'auto' && !written.submitApplied)
3570
+ ? { outcome: 'not-requested' }
3571
+ : submitOutcome(written, true);
3572
+ const bytes = submitMode === undefined ? data.length : written.inputBytes ?? 0;
3573
+ this.audit.record(actor, 'input', id, { chars: bytes,
3574
+ ...(submitMode !== undefined ? { submitMode, ...reporting } : reporting ? { submit: true, ...reporting } : {}) });
3519
3575
  this.broadcastControl(id, { type: 'input-source', source: 'agent' });
3520
3576
  // §3.1: TUIs silently swallow input while loading or when a panel has
3521
3577
  // stolen focus. verify re-reads the screen and reports whether the
@@ -3524,7 +3580,7 @@ export class Daemon {
3524
3580
  if (asBoolean(body['verify']) === true) {
3525
3581
  json(res, 200, {
3526
3582
  ok: true,
3527
- bytes: data.length,
3583
+ bytes,
3528
3584
  ...reporting,
3529
3585
  verified: await this.verifyTyped(session, data, written.before),
3530
3586
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
@@ -3533,7 +3589,7 @@ export class Daemon {
3533
3589
  });
3534
3590
  return;
3535
3591
  }
3536
- json(res, 200, { ok: true, bytes: data.length,
3592
+ json(res, 200, { ok: true, bytes,
3537
3593
  ...reporting,
3538
3594
  ...(written.submitted !== undefined ? { submitted: written.submitted } : {}),
3539
3595
  ...(written.submitRetried ? { submitRetried: true } : {}),
@@ -3777,12 +3833,13 @@ export class Daemon {
3777
3833
  await session.resize(cols, rows, { hold, onApplied: () => {
3778
3834
  this.audit.record(actor, 'resize', id, { cols, rows, hold });
3779
3835
  this.geometryEpoch.set(id, (this.geometryEpoch.get(id) ?? 0) + 1);
3836
+ this.explicitResizeRevision.set(id, this.recordGeometryChoice(id));
3780
3837
  // An API resize takes the grid away from whichever viewport had it.
3781
3838
  this.geometryController.delete(id);
3782
3839
  this.dashboardGeometryOwner.delete(id);
3783
3840
  this.dashboardCredentialOwner.delete(id);
3784
3841
  this.dashboardTransferable.delete(id);
3785
- this.announceGeometry(id, session);
3842
+ this.announceGeometry(id, session, { clientResize: true });
3786
3843
  } });
3787
3844
  }
3788
3845
  catch (error) {
@@ -4177,6 +4234,10 @@ export class Daemon {
4177
4234
  this.dashboardCredentialOwner.delete(id);
4178
4235
  this.dashboardTransferable.delete(id);
4179
4236
  this.geometryEpoch.delete(id);
4237
+ this.geometryOrder.delete(id);
4238
+ this.choiceRevision.delete(id);
4239
+ this.controllerChoiceRevision.delete(id);
4240
+ this.explicitResizeRevision.delete(id);
4180
4241
  }
4181
4242
  /** Whether a live viewport is currently driving this session's grid. */
4182
4243
  hasGeometryController(sessionId) {
@@ -4188,6 +4249,32 @@ export class Daemon {
4188
4249
  this.geometryController.delete(sessionId);
4189
4250
  return false;
4190
4251
  }
4252
+ nextGeometryOrder(id) {
4253
+ const order = (this.geometryOrder.get(id) ?? 0) + 1;
4254
+ this.geometryOrder.set(id, order);
4255
+ return order;
4256
+ }
4257
+ recordGeometryChoice(id, controller = false) {
4258
+ const revision = this.nextGeometryOrder(id);
4259
+ this.choiceRevision.set(id, revision);
4260
+ if (controller)
4261
+ this.controllerChoiceRevision.set(id, revision);
4262
+ return revision;
4263
+ }
4264
+ /** A document can reserve its grid only while its credential and proof are valid. */
4265
+ hasDashboardGeometryOwner(id) {
4266
+ const owner = this.dashboardGeometryOwner.get(id);
4267
+ if (owner === undefined)
4268
+ return false;
4269
+ if (this.tokens.verifyDashboardToken(this.dashboardCredentialOwner.get(id)) &&
4270
+ (this.dashboardTransferable.has(id) || this.tokens.acceptsDashboardProof(dashboardProofFromProtocol(owner))))
4271
+ return true;
4272
+ this.dashboardGeometryOwner.delete(id);
4273
+ this.dashboardCredentialOwner.delete(id);
4274
+ this.dashboardTransferable.delete(id);
4275
+ this.recordGeometryChoice(id);
4276
+ return false;
4277
+ }
4191
4278
  // ---------------------------------------------------- prompt-stall alerts
4192
4279
  /**
4193
4280
  * Wait, for a session just created, until its program exists (the start
@@ -4267,10 +4354,10 @@ export class Daemon {
4267
4354
  },
4268
4355
  };
4269
4356
  }
4270
- updateFeedSession(id) {
4357
+ updateFeedSession(id, promptRestarted = false) {
4271
4358
  const session = this.manager.get(id);
4272
4359
  if (session !== undefined)
4273
- this.sessionFeed.update(this.summaryWithPrompt(session.summary()));
4360
+ this.sessionFeed.update(this.summaryWithPrompt(session.summary()), promptRestarted);
4274
4361
  }
4275
4362
  /** One transition drives the feed, audit, log and both notification channels. */
4276
4363
  watchStalls(session) {
@@ -4400,6 +4487,13 @@ export class Daemon {
4400
4487
  previous.prompt.selectedOption !== detected.selectedOption ||
4401
4488
  previous.prompt.options.length !== detected.options.length ||
4402
4489
  previous.prompt.options.some((option, index) => option !== detected.options[index]);
4490
+ const inputVersion = session.promptInputVersion();
4491
+ // Input alone does not mean this prompt was answered: a key may start
4492
+ // a repaint while the same decision remains on screen. A missed prompt
4493
+ // after input is evidence of a transition only when a prompt appears
4494
+ // again; the normal grace check still handles a lasting disappearance.
4495
+ const answered = previous !== undefined && previous.inputVersion !== inputVersion &&
4496
+ previous.missingSince !== null;
4403
4497
  if (previous !== undefined) {
4404
4498
  this.clearPromptGraceCheck(session.id);
4405
4499
  previous.missingSince = null;
@@ -4410,7 +4504,7 @@ export class Daemon {
4410
4504
  // then changes although the person still faces the same decision.
4411
4505
  // A stable signature also covers focus markers moving among options.
4412
4506
  const sameContent = previous !== undefined && !promptChanged;
4413
- if (previous === undefined || (previous.signature !== detected.signature && !sameContent)) {
4507
+ if (previous === undefined || answered || (previous.signature !== detected.signature && !sameContent)) {
4414
4508
  // A new (or changed) prompt starts its stall clock; it has not
4415
4509
  // alerted yet, so a prompt answered promptly stays silent.
4416
4510
  if (previous?.alerted === true) {
@@ -4433,13 +4527,13 @@ export class Daemon {
4433
4527
  }
4434
4528
  this.promptStates.set(session.id, {
4435
4529
  signature: detected.signature,
4530
+ inputVersion,
4436
4531
  since: this.now(),
4437
4532
  alerted: false,
4438
4533
  prompt: detected,
4439
4534
  missingSince: null,
4440
4535
  });
4441
- if (promptChanged || previous?.alerted === true)
4442
- this.updateFeedSession(session.id);
4536
+ this.updateFeedSession(session.id, previous !== undefined);
4443
4537
  continue;
4444
4538
  }
4445
4539
  previous.signature = detected.signature;
@@ -4918,7 +5012,11 @@ export class Daemon {
4918
5012
  announceGeometry(sessionId, session, options = {}) {
4919
5013
  for (const [ws, sync] of this.sessionSockets.get(sessionId) ?? []) {
4920
5014
  if (ws.readyState === ws.OPEN) {
4921
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5015
+ ws.send(JSON.stringify({ ...this.geometryFrame(session, ws),
5016
+ ...(options.clientResize ? { clientResize: true,
5017
+ layoutFence: this.dashboardLayouts.get(ws)?.realId ?? 0 } : {}),
5018
+ ...(ws === this.geometryController.get(sessionId) && options.acceptedTakeId !== undefined
5019
+ ? { acceptedTakeId: options.acceptedTakeId } : {}) }));
4922
5020
  }
4923
5021
  if (options.resync !== false)
4924
5022
  sync.resync();
@@ -4933,8 +5031,13 @@ export class Daemon {
4933
5031
  }
4934
5032
  /** What one watcher is told about the grid, from its own point of view. */
4935
5033
  geometryFrame(session, ws) {
5034
+ const reserved = this.dashboardSocketCredential.has(ws) && this.hasDashboardGeometryOwner(session.id);
5035
+ const controlled = this.hasGeometryController(session.id);
4936
5036
  return {
4937
5037
  type: 'geometry',
5038
+ choiceRevision: this.choiceRevision.get(session.id) ?? 0,
5039
+ controllerChoiceRevision: this.controllerChoiceRevision.get(session.id) ?? 0,
5040
+ explicitResizeRevision: this.explicitResizeRevision.get(session.id) ?? 0,
4938
5041
  ...(this.widerReads.get(session.id)?.isTemporary() ? { temporary: true } : {}),
4939
5042
  cols: session.cols,
4940
5043
  rows: session.rows,
@@ -4944,8 +5047,7 @@ export class Daemon {
4944
5047
  max: { cols: MAX_VIEWPORT_COLS, rows: MAX_VIEWPORT_ROWS },
4945
5048
  // An adopting dashboard must distinguish a fresh session from one
4946
5049
  // already taken in another window before scheduling its initial fit.
4947
- owned: this.hasGeometryController(session.id) ||
4948
- (this.dashboardSocketCredential.has(ws) && this.dashboardGeometryOwner.has(session.id)),
5050
+ owned: controlled || reserved,
4949
5051
  // Only a controller's explicit assignment handover offers its grid to
4950
5052
  // another dashboard pane while the old socket is closing.
4951
5053
  dashboardTransferable: this.gridOfferedTo(session.id, ws),
@@ -5057,12 +5159,13 @@ export class Daemon {
5057
5159
  if (credential.kind === 'dashboard' &&
5058
5160
  // The returning document can restore its grid while a release to a
5059
5161
  // different assignment belongs to that recipient alone.
5060
- this.dashboardGeometryOwner.has(session.id) &&
5162
+ this.hasDashboardGeometryOwner(session.id) &&
5061
5163
  (!this.dashboardTransferable.has(session.id) || this.gridOfferedTo(session.id, ws)) &&
5062
5164
  tokensEqual(this.dashboardGeometryOwner.get(session.id), ws.protocol) &&
5063
5165
  !session.exited &&
5064
5166
  !this.hasGeometryController(session.id)) {
5065
5167
  this.geometryController.set(session.id, ws);
5168
+ this.recordGeometryChoice(session.id, true);
5066
5169
  this.dashboardTransferable.delete(session.id);
5067
5170
  this.announceGeometry(session.id, session, { resync: false });
5068
5171
  }
@@ -5070,8 +5173,9 @@ export class Daemon {
5070
5173
  !readOnly &&
5071
5174
  !passive &&
5072
5175
  !this.hasGeometryController(session.id) &&
5073
- !this.dashboardGeometryOwner.has(session.id)) {
5176
+ !this.hasDashboardGeometryOwner(session.id)) {
5074
5177
  this.geometryController.set(session.id, ws);
5178
+ this.recordGeometryChoice(session.id, true);
5075
5179
  this.dashboardGeometryOwner.delete(session.id);
5076
5180
  this.dashboardCredentialOwner.delete(session.id);
5077
5181
  this.dashboardTransferable.delete(session.id);
@@ -5167,10 +5271,40 @@ export class Daemon {
5167
5271
  }
5168
5272
  return;
5169
5273
  }
5274
+ if (typeof parsed === 'object' && parsed !== null &&
5275
+ parsed.type === 'layout') {
5276
+ const notice = parsed;
5277
+ if (credential.kind === 'dashboard' && this.dashboardFeedCurrent(ws) &&
5278
+ Number.isSafeInteger(notice.layoutId) && Number(notice.layoutId) > 0 &&
5279
+ typeof notice.eligible === 'boolean') {
5280
+ const id = Number(notice.layoutId);
5281
+ if (id > (this.dashboardLayouts.get(ws)?.id ?? 0)) {
5282
+ const prior = this.dashboardLayouts.get(ws);
5283
+ const real = notice.real === true;
5284
+ this.dashboardLayouts.set(ws, { id, realId: real ? id : (prior?.realId ?? 0),
5285
+ order: real ? this.nextGeometryOrder(session.id) : (prior?.order ?? 0),
5286
+ eligible: notice.eligible });
5287
+ }
5288
+ }
5289
+ return;
5290
+ }
5170
5291
  if (typeof parsed === 'object' &&
5171
5292
  parsed !== null &&
5172
5293
  parsed.type === 'resize') {
5173
- const { cols, rows, take, acceptOffer } = parsed;
5294
+ const { cols, rows, take, acceptOffer, automatic, takeId, choiceRevision, layoutId } = parsed;
5295
+ const autoTake = automatic === true && take === true && acceptOffer !== true &&
5296
+ credential.kind === 'dashboard';
5297
+ const requestId = Number.isSafeInteger(takeId) && Number(takeId) > 0 ? Number(takeId) : undefined;
5298
+ const refuseAuto = (staleLayoutId = false) => {
5299
+ if (ws.readyState === ws.OPEN)
5300
+ ws.send(JSON.stringify({ ...this.geometryFrame(session, ws),
5301
+ refusedTakeId: requestId, ...(staleLayoutId ? { staleLayoutId: true } : {}) }));
5302
+ };
5303
+ if (automatic === true && (!autoTake || requestId === undefined ||
5304
+ !Number.isSafeInteger(choiceRevision) || !Number.isSafeInteger(layoutId))) {
5305
+ refuseAuto();
5306
+ return;
5307
+ }
5174
5308
  // Fit, Enlarge, Focus and Restore are a resize that says `take`.
5175
5309
  // A passive socket's other resizes, including one a dashboard pane
5176
5310
  // sends because the window moved, are not that act: the grid stays,
@@ -5191,51 +5325,131 @@ export class Daemon {
5191
5325
  if (session.geometryHeld) {
5192
5326
  // Held against viewports. Answer with the real grid so the page
5193
5327
  // stops proposing one it will never be given.
5194
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5328
+ if (autoTake)
5329
+ refuseAuto();
5330
+ else
5331
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5195
5332
  return;
5196
5333
  }
5197
5334
  const wanted = {
5198
5335
  cols: Math.min(cols, MAX_VIEWPORT_COLS),
5199
5336
  rows: Math.min(rows, MAX_VIEWPORT_ROWS),
5200
5337
  };
5338
+ if (autoTake) {
5339
+ try {
5340
+ let applied = false;
5341
+ let changedAtApply = false;
5342
+ let staleLayoutId = false;
5343
+ const shouldApply = () => {
5344
+ if (session.geometryHeld || session.exited || ws.readyState !== ws.OPEN ||
5345
+ !this.sessionSockets.get(session.id)?.has(ws) || !this.dashboardFeedCurrent(ws))
5346
+ return false;
5347
+ const layout = this.dashboardLayouts.get(ws);
5348
+ if (Number(layoutId) !== (layout?.id ?? 0)) {
5349
+ staleLayoutId = true;
5350
+ return false;
5351
+ }
5352
+ if (layout?.eligible === false)
5353
+ return false;
5354
+ const ownerPresent = this.hasGeometryController(session.id);
5355
+ if (ownerPresent && this.geometryController.get(session.id) !== ws)
5356
+ return false;
5357
+ const reserved = this.hasDashboardGeometryOwner(session.id);
5358
+ if (reserved && this.geometryController.get(session.id) !== ws)
5359
+ return false;
5360
+ const explicit = this.explicitResizeRevision.get(session.id) ?? 0;
5361
+ if (explicit > (this.controllerChoiceRevision.get(session.id) ?? 0) &&
5362
+ (layout?.order ?? 0) <= explicit)
5363
+ return false;
5364
+ const current = this.choiceRevision.get(session.id) ?? 0;
5365
+ if (Number(choiceRevision) !== current &&
5366
+ !(layout !== undefined && layout.id === Number(layoutId) && layout.order > current))
5367
+ return false;
5368
+ changedAtApply = wanted.cols !== session.cols || wanted.rows !== session.rows;
5369
+ return true;
5370
+ };
5371
+ const onApplied = () => {
5372
+ applied = true;
5373
+ const handedOver = this.geometryController.get(session.id) !== ws;
5374
+ this.geometryController.set(session.id, ws);
5375
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5376
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5377
+ this.dashboardTransferable.delete(session.id);
5378
+ this.recordGeometryChoice(session.id, true);
5379
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5380
+ if (changedAtApply)
5381
+ this.audit.record(actor, 'resize', session.id, {
5382
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5383
+ });
5384
+ if (changedAtApply || handedOver)
5385
+ this.announceGeometry(session.id, session, { resync: changedAtApply, acceptedTakeId: requestId });
5386
+ else
5387
+ ws.send(JSON.stringify({ ...this.geometryFrame(session, ws), acceptedTakeId: requestId }));
5388
+ };
5389
+ await session.resize(wanted.cols, wanted.rows, { shouldApply, skipIfSame: true, onApplied });
5390
+ if (!applied)
5391
+ refuseAuto(staleLayoutId);
5392
+ }
5393
+ catch (error) {
5394
+ refuseAuto();
5395
+ if (!(error instanceof SessionProgramEndedError))
5396
+ this.logger.warn('viewer resize failed', {
5397
+ id: session.id, error: String(error),
5398
+ });
5399
+ }
5400
+ return;
5401
+ }
5201
5402
  if (!this.widerReads.has(session.id) && acceptOffer !== true) {
5202
- // Wider restores and conditional offer takes check ownership
5203
- // in the session's resize queue below.
5204
- const handedOver = this.geometryController.get(session.id) !== ws;
5205
- const changed = wanted.cols !== session.cols || wanted.rows !== session.rows;
5206
5403
  let applied = false;
5207
- try {
5208
- if (changed)
5209
- await session.resize(wanted.cols, wanted.rows);
5404
+ let changedAtApply = false;
5405
+ const shouldApply = () => {
5406
+ if (session.geometryHeld || session.exited || ws.readyState !== ws.OPEN ||
5407
+ !this.sessionSockets.get(session.id)?.has(ws))
5408
+ return false;
5409
+ changedAtApply = wanted.cols !== session.cols || wanted.rows !== session.rows;
5410
+ return true;
5411
+ };
5412
+ const onApplied = () => {
5210
5413
  applied = true;
5414
+ const handedOver = this.geometryController.get(session.id) !== ws;
5415
+ this.geometryController.set(session.id, ws);
5416
+ this.recordGeometryChoice(session.id, true);
5417
+ this.dashboardTransferable.delete(session.id);
5418
+ this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5419
+ if (credential.kind === 'dashboard') {
5420
+ this.dashboardGeometryOwner.set(session.id, ws.protocol);
5421
+ this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5422
+ }
5423
+ else {
5424
+ this.dashboardGeometryOwner.delete(session.id);
5425
+ this.dashboardCredentialOwner.delete(session.id);
5426
+ }
5427
+ if (changedAtApply) {
5428
+ this.audit.record(actor, 'resize', session.id, {
5429
+ cols: wanted.cols, rows: wanted.rows, hold: false,
5430
+ });
5431
+ this.announceGeometry(session.id, session);
5432
+ }
5433
+ else if (handedOver)
5434
+ this.announceGeometry(session.id, session, { resync: false });
5435
+ else if (take === true)
5436
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5437
+ };
5438
+ try {
5439
+ if (wanted.cols !== session.cols || wanted.rows !== session.rows) {
5440
+ await session.resize(wanted.cols, wanted.rows, { shouldApply, skipIfSame: true, onApplied });
5441
+ }
5442
+ else {
5443
+ await session.resizeIfCurrent(wanted.cols, wanted.rows, shouldApply, () => onApplied(), true);
5444
+ }
5445
+ if (!applied && ws.readyState === ws.OPEN)
5446
+ ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5211
5447
  }
5212
5448
  catch (error) {
5213
5449
  if (error instanceof SessionProgramEndedError)
5214
5450
  return;
5215
5451
  this.logger.warn('viewer resize failed', { id: session.id, error: String(error) });
5216
5452
  }
5217
- this.geometryController.set(session.id, ws);
5218
- this.dashboardTransferable.delete(session.id);
5219
- this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5220
- if (credential.kind === 'dashboard') {
5221
- this.dashboardGeometryOwner.set(session.id, ws.protocol);
5222
- this.dashboardCredentialOwner.set(session.id, credential.dashboardToken);
5223
- }
5224
- else {
5225
- this.dashboardGeometryOwner.delete(session.id);
5226
- this.dashboardCredentialOwner.delete(session.id);
5227
- }
5228
- if (changed && applied) {
5229
- this.audit.record(actor, 'resize', session.id, {
5230
- cols: wanted.cols, rows: wanted.rows, hold: false,
5231
- });
5232
- }
5233
- if (changed)
5234
- this.announceGeometry(session.id, session);
5235
- else if (handedOver)
5236
- this.announceGeometry(session.id, session, { resync: false });
5237
- else if (take === true)
5238
- ws.send(JSON.stringify(this.geometryFrame(session, ws)));
5239
5453
  return;
5240
5454
  }
5241
5455
  try {
@@ -5249,6 +5463,7 @@ export class Daemon {
5249
5463
  // The controller change and epoch belong to the same queued
5250
5464
  // act as the resize, before a queued wider restore can run.
5251
5465
  this.geometryController.set(session.id, ws);
5466
+ this.recordGeometryChoice(session.id, true);
5252
5467
  this.dashboardTransferable.delete(session.id);
5253
5468
  this.geometryEpoch.set(session.id, (this.geometryEpoch.get(session.id) ?? 0) + 1);
5254
5469
  if (credential.kind === 'dashboard') {
@@ -5389,6 +5604,7 @@ export class Daemon {
5389
5604
  // does not inherit it.
5390
5605
  if (this.geometryController.get(session.id) === ws) {
5391
5606
  this.geometryController.delete(session.id);
5607
+ this.recordGeometryChoice(session.id);
5392
5608
  this.announceGeometry(session.id, session, { resync: false });
5393
5609
  }
5394
5610
  this.lastActivity = Date.now();