@rarog/server 1.1.0 → 1.1.2-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 (66) hide show
  1. package/node_modules/@rarog/shared/package.json +1 -1
  2. package/node_modules/@rarog/shared/src/decode.js +3 -0
  3. package/node_modules/@rarog/shared/src/notify-copy.js +1 -0
  4. package/node_modules/@rarog/shared/src/protocol/background.js +7 -0
  5. package/node_modules/@rarog/shared/src/sentences/dialogs.js +10 -0
  6. package/node_modules/@rarog/shared/src/sentences/push.js +3 -0
  7. package/package.json +2 -2
  8. package/server/src/bootstrap/pr-status.js +15 -7
  9. package/server/src/bootstrap/push.js +36 -5
  10. package/server/src/cli/doctor-pr-status.js +10 -6
  11. package/server/src/cli/update-registry.js +31 -1
  12. package/server/src/cli/update.js +128 -6
  13. package/server/src/demo/control.js +4 -2
  14. package/server/src/demo/mock-herdr.js +2 -2
  15. package/server/src/demo/scenarios.js +31 -17
  16. package/server/src/demo/seeds.js +62 -38
  17. package/server/src/drivers/herdr/pull-request-poll.js +5 -5
  18. package/server/src/drivers/herdr/queue-take-back.js +4 -0
  19. package/server/src/drivers/herdr/start-dialog-gate.js +132 -0
  20. package/server/src/drivers/herdr-driver.js +75 -15
  21. package/server/src/herdr/background/cli-shapes.js +16 -15
  22. package/server/src/herdr/background/index.js +7 -7
  23. package/server/src/herdr/background/merge.js +17 -5
  24. package/server/src/herdr/background/notification.js +0 -4
  25. package/server/src/herdr/background/pull-request-files.js +53 -161
  26. package/server/src/herdr/background/pull-requests.js +54 -632
  27. package/server/src/herdr/background/work.js +84 -0
  28. package/server/src/herdr/dialogs/copy.js +7 -0
  29. package/server/src/herdr/dialogs/index.js +4 -1
  30. package/server/src/herdr/dialogs/screen/form.js +2 -1
  31. package/server/src/herdr/dialogs/screen/option-run.js +25 -3
  32. package/server/src/herdr/dialogs/screen/parse.js +3 -3
  33. package/server/src/herdr/dialogs/screen/signatures.js +55 -0
  34. package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
  35. package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
  36. package/server/src/herdr/jsonl-follow.js +6 -2
  37. package/server/src/herdr/label-code.js +104 -0
  38. package/server/src/herdr/label-migration.js +142 -0
  39. package/server/src/herdr/launcher.js +30 -5
  40. package/server/src/herdr/provenance.js +80 -40
  41. package/server/src/herdr/start-dialog-wait.js +96 -0
  42. package/server/src/herdr/supervisor.js +33 -10
  43. package/server/src/herdr/workspace-resolver.js +5 -4
  44. package/server/src/index.js +8 -3
  45. package/server/src/notify/apns-payload.js +5 -3
  46. package/server/src/notify/content.js +37 -0
  47. package/server/src/notify/index.js +4 -0
  48. package/server/src/notify/live-activity-state.js +9 -5
  49. package/server/src/notify/live-activity.js +5 -2
  50. package/server/src/notify/policy.js +4 -2
  51. package/server/src/notify/stalled-wait.js +213 -0
  52. package/server/src/pr-status/facts.js +87 -0
  53. package/server/src/pr-status/gh.js +76 -9
  54. package/server/src/pr-status/index.js +1 -10
  55. package/server/src/pr-status/source.js +20 -6
  56. package/server/src/pr-status/tracker.js +32 -9
  57. package/server/src/sessions/conversation-lists.js +8 -2
  58. package/server/src/sessions/driver-events.js +7 -3
  59. package/server/src/sessions/interrupt-windows.js +28 -4
  60. package/server/src/sessions/manager.js +14 -5
  61. package/server/src/sessions/pr-status-link.js +64 -16
  62. package/server/src/sessions/session.js +10 -3
  63. package/server/src/sessions/state-machine.js +11 -0
  64. package/server/src/sessions/test-session.js +50 -0
  65. package/server/src/term/herdr-backend.js +15 -12
  66. package/server/src/term/lifecycle.js +4 -6
@@ -30,8 +30,9 @@ import { createAnswerRecheck } from './answer-recheck.js';
30
30
  import { createHerdrAuditLog } from './audit.js';
31
31
  import { createHerdrClient, createHerdrLaunchClient } from './client.js';
32
32
  import { createHiddenStore, sessionIdFor } from './identity.js';
33
+ import { createLabelMigration, isLegacyPaneLabel } from './label-migration.js';
33
34
  import { createSendThrottle } from './commands/index.js';
34
- import { claudePaneLabel, labelTrace, parsePaneLabel, projectKey, realProjectPath, sanitizePaneTitle, sanitizeTabLabel, } from './provenance.js';
35
+ import { claudePaneLabelFrom, claudeTraceMatches, labelTrace, newClaudeProvenance, parsePaneLabel, realProjectPath, sanitizePaneTitle, sanitizeTabLabel, } from './provenance.js';
35
36
  import { standingConsentDialog } from './dialogs/index.js';
36
37
  import { collapseFooterMode, parseModeFooter } from './dialogs/screen/mode-footer.js';
37
38
  import { HerdrUnavailableError, createHerdrSocket } from './socket.js';
@@ -184,6 +185,8 @@ export function createHerdrSupervisor(config, deps) {
184
185
  * na żywym panelu — oba źródła oddały ten sam ekran co do bajta.
185
186
  */
186
187
  readScreen: async (paneId) => ((await client.readScreen(paneId, 'detection')).text),
188
+ sessionAppeared: (paneId) => { void refreshPane(paneId); },
189
+ launchHeld: (key) => !disposed && agents.get(key)?.seenInList === false,
187
190
  logger: log,
188
191
  })
189
192
  : undefined);
@@ -226,6 +229,10 @@ export function createHerdrSupervisor(config, deps) {
226
229
  let refreshTimer = null;
227
230
  let disposed = false;
228
231
  let unavailable = false;
232
+ /** Old-format pane labels → the current format, over the whole `pane.list` whenever herdr answers. */
233
+ const labelMigration = launchClient === null ? null : createLabelMigration({
234
+ client: launchClient, writable: () => config.sendEnabled && !transport.status().readOnly, log,
235
+ });
229
236
  /** Status recheck after a dialog answer, so a lost `idle` push does not leave the card standing until the resync. */
230
237
  const answerRecheck = createAnswerRecheck({ scheduler, refresh: (paneId) => refreshPane(paneId), log });
231
238
  /** The client every driver gets: the same as `client`, with the recheck after each accepted dialog answer. */
@@ -276,6 +283,7 @@ export function createHerdrSupervisor(config, deps) {
276
283
  if (!unavailable)
277
284
  return;
278
285
  unavailable = false;
286
+ labelMigration?.requestPass();
279
287
  log('herdr: available again');
280
288
  lifecycle.push({ type: 'available' });
281
289
  };
@@ -420,12 +428,12 @@ export function createHerdrSupervisor(config, deps) {
420
428
  *
421
429
  * Rarog nazywa tab WYŁĄCZNIE gdy: lokator to agent `claude` (Codex nigdy), tab jest
422
430
  * jednopanelowy (`tab.get`, za każdym razem — panel mógł zostać przeniesiony albo tab
423
- * podzielony), a panel nosi etykietę pochodzenia `rarog-claude <klucz> <ślad>`. Bieżąca etykieta
431
+ * podzielony), a panel nosi etykietę pochodzenia `rc:<klucz><ślad>`. Bieżąca etykieta
424
432
  * taba jest „Raroga", gdy jej skrót równa się śladowi z etykiety panelu (trwałe — przeżywa
425
433
  * restart Raroga i herdr) albo gdy ten proces sam ją tam zostawił (`written`, RAM). Każda inna
426
434
  * = nadana ręcznie i NIETKNIĘTA — liczone przy każdym przebiegu od nowa, bez „ręcznej na zawsze".
427
435
  *
428
- * The pane label leads with the tab label (`<tab label> · rarog-claude <key> <trace>`): with
436
+ * The pane label leads with the tab label (`<tab label> · rc:<key><trace>`): with
429
437
  * Rarog's tab label it carries that label's trace, with a name given by hand it carries that
430
438
  * name and the old trace. The pane label it already has = no write.
431
439
  *
@@ -485,6 +493,9 @@ export function createHerdrSupervisor(config, deps) {
485
493
  // Panel terminala Raroga (ktoś odpalił `claude` w powłoce z Raroga): jego tab nazywa terminal.
486
494
  if (provenance?.kind === 'term')
487
495
  return 'done';
496
+ // An old-format label is rewritten by the label migration alone; the sync comes back after it.
497
+ if (isLegacyPaneLabel(pane.label))
498
+ return 'retry';
488
499
  if (provenance === null) {
489
500
  // Etykieta człowieka (niepusta, spoza wzorców Raroga) — panel cudzy, migracja też nie.
490
501
  if (pane.label !== null && pane.label.trim() !== '')
@@ -508,7 +519,7 @@ export function createHerdrSupervisor(config, deps) {
508
519
  if (provenance === null) {
509
520
  if (!isLegacyClaudeTabLabel(tab.label, [entry.agent.cwd, pane.cwd]))
510
521
  return 'done';
511
- const project = projectKey(await realProjectPath(entry.agent.cwd));
522
+ const fresh = newClaudeProvenance(await realProjectPath(entry.agent.cwd), tab.label);
512
523
  if (!(await confirmPane(client, paneId, tab.tabId, pane.label))) {
513
524
  log(`herdr: pane ${paneId} changed before the label migration — skipping`);
514
525
  return interrupted() ?? 'retry';
@@ -516,7 +527,7 @@ export function createHerdrSupervisor(config, deps) {
516
527
  const beforeMigration = interrupted();
517
528
  if (beforeMigration !== null)
518
529
  return beforeMigration;
519
- const migrated = claudePaneLabel(project, labelTrace(tab.label), tab.label);
530
+ const migrated = claudePaneLabelFrom(fresh, tab.label, 'keep');
520
531
  try {
521
532
  await client.renamePane(paneId, migrated);
522
533
  }
@@ -524,7 +535,7 @@ export function createHerdrSupervisor(config, deps) {
524
535
  return writeFailed(err, `label migration of pane ${paneId} failed`);
525
536
  }
526
537
  log(`herdr: migration — pane ${paneId} got a provenance label (tab ${tab.tabId})`);
527
- provenance = { kind: 'claude', value: project, trace: labelTrace(tab.label) };
538
+ provenance = fresh;
528
539
  expectedLabel = migrated;
529
540
  }
530
541
  const owned = provenance;
@@ -551,7 +562,7 @@ export function createHerdrSupervisor(config, deps) {
551
562
  return null;
552
563
  };
553
564
  /** The pane label Rarog's own tab label calls for: the card label first, its trace last. */
554
- const targetLabel = claudePaneLabel(owned.value, labelTrace(target), target);
565
+ const targetLabel = claudePaneLabelFrom(owned, target, 'fresh');
555
566
  /** Nowy ślad po etykiecie, którą Rarog zostawił na tabie; `settled` tylko po udanym zapisie. */
556
567
  const writeTrace = async () => {
557
568
  const failed = await writePane(targetLabel, 'the tab label trace');
@@ -571,7 +582,7 @@ export function createHerdrSupervisor(config, deps) {
571
582
  }
572
583
  return await writeTrace();
573
584
  }
574
- const ours = labelTrace(tab.label) === owned.trace || tab.label === state.written;
585
+ const ours = claudeTraceMatches(owned, tab.label) || tab.label === state.written;
575
586
  if (!ours) {
576
587
  logTabLabelOnce(`manual|${key}|${tab.tabId}|${labelTrace(tab.label)}`, `herdr: tab ${tab.tabId} named by hand — the card label does not overwrite it`);
577
588
  /*
@@ -579,7 +590,7 @@ export function createHerdrSupervisor(config, deps) {
579
590
  * shows it instead of hashes. The trace stays the old one: it proves Rarog's own tab
580
591
  * label, and the name given by hand must not pass for Rarog's on the next card change.
581
592
  */
582
- const manual = claudePaneLabel(owned.value, owned.trace, tab.label);
593
+ const manual = claudePaneLabelFrom(owned, tab.label, 'keep');
583
594
  if (ownLabel === manual)
584
595
  return 'done';
585
596
  return await writePane(manual, 'the hand-given tab name') ?? 'done';
@@ -874,6 +885,7 @@ export function createHerdrSupervisor(config, deps) {
874
885
  lastModeReadAt: 0,
875
886
  sentAt: 0,
876
887
  trustSeenAt: 0,
888
+ startDialog: null,
877
889
  consentDialog: null,
878
890
  // Wpis z `agent.list` zapala flagę od razu; rejestracja launchera zostaje na `false`,
879
891
  // dopóki agent naprawdę nie pokaże się na liście.
@@ -913,7 +925,7 @@ export function createHerdrSupervisor(config, deps) {
913
925
  agentSessionId: reg.agentSessionId,
914
926
  // Launcher zakłada WYŁĄCZNIE panele Claude (`agent.start(kind: 'claude')`) — Codex
915
927
  // z klienta jest poza zakresem. Panel launchera nie jest terminalem Raroga (własny tab
916
- // z etykietą `rarog-claude`), więc tokenu terminala nie ma.
928
+ // z etykietą `rc:`), więc tokenu terminala nie ma.
917
929
  engine: 'claude',
918
930
  termId: null,
919
931
  cwd: reg.cwd,
@@ -1291,6 +1303,7 @@ export function createHerdrSupervisor(config, deps) {
1291
1303
  return;
1292
1304
  }
1293
1305
  markAvailable();
1306
+ void labelMigration?.run();
1294
1307
  /*
1295
1308
  * Skład map zmienił się W TRAKCIE odczytu (równoległy resync coś odkrył, `closeTab`
1296
1309
  * coś zdjął): ta migawka `agent.list` jest starsza od rejestru, więc pętla `forget`
@@ -1625,6 +1638,14 @@ export function createHerdrSupervisor(config, deps) {
1625
1638
  entry.agent.agentSessionId = result.agentSessionId;
1626
1639
  bySession.set(result.agentSessionId, key);
1627
1640
  }
1641
+ /*
1642
+ * The launch result is one unordered `agent.get` read from before `ready` settled. An agent the supervisor
1643
+ * has seen on a list since then has fresher state in order: a start dialog read right before its answer would
1644
+ * put a ready pane back to `blocked` and hold the start prompt until the next resync.
1645
+ */
1646
+ if (entry.seenInList)
1647
+ return { ...result, key };
1648
+ entry.startDialog = result.startDialog ?? null;
1628
1649
  entry.agent.interactiveReady = result.interactiveReady;
1629
1650
  /*
1630
1651
  * Status ZAOBSERWOWANY przez launcher — jedyna droga, którą `blocked` dialogu
@@ -1896,6 +1917,7 @@ export function createHerdrSupervisor(config, deps) {
1896
1917
  markTrustDialog: () => {
1897
1918
  entry.trustSeenAt = now();
1898
1919
  },
1920
+ startPhase: () => (entry.seenInList ? null : { startDialog: entry.startDialog }),
1899
1921
  yoloRoots: config.yoloRoots,
1900
1922
  sendEnabled: config.sendEnabled,
1901
1923
  ...(entry.knownContextLimit === undefined
@@ -1925,6 +1947,7 @@ export function createHerdrSupervisor(config, deps) {
1925
1947
  if (refreshTimer !== null)
1926
1948
  scheduler.clearTimeout(refreshTimer);
1927
1949
  answerRecheck.dispose();
1950
+ labelMigration?.dispose();
1928
1951
  for (const key of [...tabLabels.keys()])
1929
1952
  dropTabLabel(key);
1930
1953
  subscription?.close();
@@ -41,7 +41,7 @@
41
41
  */
42
42
  import path from 'node:path';
43
43
  import { matchTermId } from '../term/lifecycle.js';
44
- import { parsePaneLabel, projectKey, sanitizePaneTitle } from './provenance.js';
44
+ import { claudeKeyMatches, parsePaneLabel, provenanceTermId, sanitizePaneTitle } from './provenance.js';
45
45
  /** `child` to `parent` albo ścieżka w nim (po separatorze — `/a/apix` NIE leży w `/a/api`). */
46
46
  export function isWithin(child, parent) {
47
47
  if (child === parent)
@@ -51,9 +51,10 @@ export function isWithin(child, parent) {
51
51
  }
52
52
  /** Etykieta pochodzenia jest etykietą Raroga dla katalogu `dir` (hash z tej ścieżki). */
53
53
  function labelBelongsTo(provenance, dir) {
54
- return provenance.kind === 'claude'
55
- ? provenance.value === projectKey(dir)
56
- : matchTermId(provenance.value, dir) !== null;
54
+ if (provenance.kind === 'claude')
55
+ return claudeKeyMatches(provenance, dir);
56
+ const id = provenanceTermId(provenance);
57
+ return id !== null && matchTermId(id, dir) !== null;
57
58
  }
58
59
  /**
59
60
  * Katalog, dla którego Rarog nadał tę etykietę, szukany od `cwd` panelu w górę — albo `null`.
@@ -274,6 +274,8 @@ async function loadHerdr(config, log, shadow, demoContent, consentMode, consentL
274
274
  // Dialog zaufania katalogu re-eksekuuje `claude`, a nadzorca musi wiedzieć, że
275
275
  // zniknięcie agenta w tym oknie znaczy „wstaje", a nie „zniknął".
276
276
  markTrustDialog: () => { ctx.markTrustDialog(); },
277
+ // A start dialog herdr reads as ready may stand until herdr knows the engine session.
278
+ startPhase: () => ctx.startPhase(),
277
279
  // Zrzuty hooka `PreToolUse` (warstwa 1 uniwersalnej karty): hook pisze, driver czyta
278
280
  // — oba przez ten sam `dataDir`. Bez zainstalowanego hooka plików po prostu nie ma
279
281
  // i karta powstaje z ekranu (warstwa 2).
@@ -588,7 +590,8 @@ async function main() {
588
590
  const macStats = config.demo ? (await import('./demo/mac.js')).demoMacStats() : createMacStats();
589
591
  // Powiadomienia: obecność, kanał APNs i harmonogram banerów (`bootstrap/push.ts`). Manager powstaje niżej,
590
592
  // więc push czyta go przez `managerRef`; sygnał nowej wersji dostaje sink kanału APNs.
591
- const { presence, apns, notifier } = createPush(config, { managerRef: () => managerRef, devices, macStats, log });
593
+ const push = createPush(config, { managerRef: () => managerRef, devices, macStats, log });
594
+ const { presence, apns, notifier, stalledWait } = push;
592
595
  setVersionSink(apns?.sink);
593
596
  // SDK Claude listy „Ostatnie sesje” raz, przed `listen()`; demo go nie dotyka (`bootstrap/manager.ts`).
594
597
  const sdk = await loadSdk(config, log);
@@ -606,6 +609,7 @@ async function main() {
606
609
  ...(consentCycle === null ? {} : { consent: consentManagerPort(consentCycle, consentMode, log) }),
607
610
  ...(consentCycle === null ? {} : { consentForgotten: consentForgottenPort(consentCycle, log) }),
608
611
  ...(prStatus === null ? {} : { prStatus: prStatus.port }),
612
+ ...(stalledWait === undefined ? {} : { stalledWait }),
609
613
  });
610
614
  managerRef = manager;
611
615
  /*
@@ -777,8 +781,9 @@ async function main() {
777
781
  // WebSockecie terminala. Powłoki w panelach herdr zostają: giną wyłącznie kontrolery.
778
782
  term?.dispose();
779
783
  // Timery Live Activity i połączenia HTTP/2 do APNs — bez nich proces i tak wyjdzie (`unref`),
780
- // ale grzecznie. The channel closes in its own order (poller, the weekly-limit send in flight, passes, sender).
781
- const apnsClosed = apns?.close() ?? Promise.resolve();
784
+ // ale grzecznie. The stalled wait alarm stops its timers first; the channel closes in its own order (poller, the
785
+ // weekly-limit send in flight, passes, sender).
786
+ const apnsClosed = push.close();
782
787
  versionWatch?.dispose();
783
788
  macStats.close();
784
789
  clearInterval(deviceSweep);
@@ -1,5 +1,5 @@
1
1
  import { RELAY_ALERT_PLACEHOLDER } from '@rarog/shared/relay';
2
- import { isSessionless } from './content.js';
2
+ import { isSessionless, topicFor } from './content.js';
3
3
  import { PUSH_PLAINTEXT_MAX_BYTES } from './push-crypto.js';
4
4
  /** Sufit ładunku powiadomienia APNs (bajty UTF-8 całego JSON-a). */
5
5
  export const APNS_PAYLOAD_MAX_BYTES = 4096;
@@ -130,6 +130,7 @@ export function apnsAlertRequestE2e(content, options) {
130
130
  const exp = expirationOf(content, options.nowMs);
131
131
  const plaintext = fitTexts(content, PUSH_PLAINTEXT_MAX_BYTES, (texts) => plaintextJson(content, exp, texts));
132
132
  const envelope = options.sealer.seal(options.key, plaintext);
133
+ const sessionId = sessionIdOf(content);
133
134
  const aps = badgeOnly(content)
134
135
  ? badgeAps(content)
135
136
  : {
@@ -137,8 +138,9 @@ export function apnsAlertRequestE2e(content, options) {
137
138
  'mutable-content': 1,
138
139
  sound: 'default',
139
140
  ...badgeAps(content),
140
- // Klucz koalescencji (skrót id sesji), ta sama wartość co jawny `apns-collapse-id` — nie surowe id.
141
- ...(sessionIdOf(content) === undefined ? {} : { 'thread-id': content.topic }),
141
+ // Hash of the session id, never the raw id: one group per session in the Notification Center. Equal to
142
+ // `apns-collapse-id` for every session kind except the stalled wait alarm, which has its own collapse key.
143
+ ...(sessionId === undefined ? {} : { 'thread-id': topicFor(sessionId) }),
142
144
  };
143
145
  const body = JSON.stringify({ aps, [APNS_RAROG_BLOCK]: { v: APNS_RAROG_BLOCK_VERSION, ...envelope } });
144
146
  if (bytes(body) > APNS_PAYLOAD_MAX_BYTES)
@@ -38,6 +38,7 @@ const FALLBACK_BODY = {
38
38
  done: 'push.body.fallback.done',
39
39
  error: 'push.body.fallback.error',
40
40
  limit: 'push.body.fallback.limit',
41
+ stalled: 'push.body.fallback.stalled',
41
42
  };
42
43
  /**
43
44
  * Jak długo APNs trzyma wiadomość dla telefonu, który akurat jest poza siecią (`apns-expiration`
@@ -51,6 +52,8 @@ const TTL_SECONDS = {
51
52
  blocking: 600,
52
53
  failure: 600,
53
54
  done: 3600,
55
+ // A subagent stuck on its own command stays stuck: an alarm delivered an hour late still tells the truth.
56
+ stalled: 3600,
54
57
  };
55
58
  /**
56
59
  * `high` = dostarcz natychmiast (`apns-priority: 10`), `normal` = system może poczekać na lepszy
@@ -60,6 +63,7 @@ const URGENCY = {
60
63
  blocking: 'high',
61
64
  failure: 'high',
62
65
  done: 'normal',
66
+ stalled: 'high',
63
67
  };
64
68
  /** Czy push nie dotyczy sesji ({@link SessionlessPushKind}). */
65
69
  export function isSessionless(content) {
@@ -107,6 +111,14 @@ export function flatten(text) {
107
111
  export function topicFor(sessionId) {
108
112
  return createHash('sha256').update(sessionId).digest('base64url').slice(0, TOPIC_MAX_CHARS);
109
113
  }
114
+ /**
115
+ * Collapse key of the stalled wait alarm of one session ({@link buildStalledContent}): a hash like {@link topicFor},
116
+ * stable per session, but never the session topic, so the alarm does not replace a pending decision banner of the
117
+ * same session and a later decision banner does not replace the alarm.
118
+ */
119
+ export function stalledTopicFor(sessionId) {
120
+ return topicFor(`rarog:stalled:${sessionId}`);
121
+ }
110
122
  const sentence = (said) => ({ text: said.text, ref: said.ref });
111
123
  /** `text` i `*Ref` pola treści, bez pola `*Ref`, gdy zdanie go nie ma. */
112
124
  const titleFields = (title) => (title.ref === undefined ? { title: title.text } : { title: title.text, titleRef: title.ref });
@@ -203,6 +215,31 @@ export function buildContent(input) {
203
215
  ...(input.badge === undefined ? {} : { badge: input.badge }),
204
216
  };
205
217
  }
218
+ /**
219
+ * Push `stalled`: a subagent of the session has waited over an hour on a background command it started itself. The
220
+ * title has the project (`push.title.stalled`), the body names the subagent by its description
221
+ * (`push.detail.stalled`, flattened and clipped before `say()`, so the body keeps its code), without a description the
222
+ * session label or `push.body.fallback.stalled`. Never the command: the lock screen is readable by bystanders
223
+ * (`docs/security-model.md`, "Push notifications"). Urgent, one hour in APNs, with its own collapse key
224
+ * ({@link stalledTopicFor}); the tap opens the session like any session banner.
225
+ */
226
+ export function buildStalledContent(input) {
227
+ const agent = input.agent === undefined ? '' : oneLine(input.agent);
228
+ const body = agent === ''
229
+ ? bodyFor('stalled', undefined, input.label)
230
+ : fitBody((a) => say('push.detail.stalled', { agent: a }), agent);
231
+ return {
232
+ kind: 'stalled',
233
+ sessionId: input.sessionId,
234
+ ...(input.termId === undefined ? {} : { termId: input.termId }),
235
+ ...titleFields(sentence(say(NOTIFY_KIND_TITLE.stalled, { project: input.project }))),
236
+ ...bodyFields(body),
237
+ topic: stalledTopicFor(input.sessionId),
238
+ urgency: URGENCY.stalled,
239
+ ttl: TTL_SECONDS.stalled,
240
+ ...(input.badge === undefined ? {} : { badge: input.badge }),
241
+ };
242
+ }
206
243
  /**
207
244
  * Push PRÓBNY po włączeniu powiadomień: tap otwiera listę sesji. Krótki TTL — próba, która
208
245
  * dojdzie po godzinie, niczego już nie potwierdza. Bez plakietki: nie wiemy tu, ile sesji czeka.
@@ -161,6 +161,7 @@ export class Notifier {
161
161
  backgroundTasks: input.backgroundTasks,
162
162
  ...(input.afterHerdrRestore === true ? { afterHerdrRestore: true } : {}),
163
163
  ...(input.afterStart === true ? { afterStart: true } : {}),
164
+ ...(input.testSession === true ? { testSession: true } : {}),
164
165
  ...(input.turnInput === undefined ? {} : { turnInput: input.turnInput }),
165
166
  ...(input.waitingOnOwnCommand === true ? { waitingOnOwnCommand: true } : {}),
166
167
  };
@@ -193,6 +194,9 @@ export class Notifier {
193
194
  else if (input.afterStart === true && kind === 'done') {
194
195
  this.#log?.(`${PUSH_QUIET_LOG} ${input.project} (done, session start)`);
195
196
  }
197
+ else if (input.testSession === true && kind === 'done') {
198
+ this.#log?.(`${PUSH_QUIET_LOG} ${input.project} (done, test session in a temporary directory)`);
199
+ }
196
200
  else if (kind === 'done' && input.backgroundTasks === 0 && input.turnInput !== undefined
197
201
  && noResultTurn(input.turnInput)) {
198
202
  // A reason visible neither in the session state nor in the task list: the turn was triggered
@@ -1,7 +1,7 @@
1
1
  import { TERM_ID_RE } from '@rarog/shared';
2
2
  import { phaseCounts } from '@rarog/shared/workflow-phases';
3
3
  import { LIVE_ACTIVITY_SEGMENTS_MAX, LIVE_ACTIVITY_TEXT_MAX, LIVE_ACTIVITY_WORKFLOWS_MAX, } from '@rarog/shared/rest';
4
- import { hasBackgroundWork, hasOpenWorkflow, workflowsWithRun } from '../herdr/background/work.js';
4
+ import { hasBackgroundWork, hasOpenWorkflow, stuckWait, workflowsWithRun } from '../herdr/background/work.js';
5
5
  import { currentPhase } from './workflow-phase.js';
6
6
  const WAITING = ['waiting-permission', 'waiting-question'];
7
7
  const WORKING = ['starting', 'running'];
@@ -127,9 +127,13 @@ export function aggregateState(sessions, nowMs, extras = {}) {
127
127
  const nowSec = Math.floor(nowMs / 1000);
128
128
  const waiting = sessions.filter((s) => WAITING.includes(s.state));
129
129
  const working = sessions.filter((s) => WORKING.includes(s.state));
130
- const background = sessions.filter((s) => QUIET.includes(s.state) && hasBackgroundWork(s.backgroundTasks));
131
- const finished = sessions.filter((s) => s.state === 'waiting-input' && s.seen !== true && !hasBackgroundWork(s.backgroundTasks)).length;
132
- // Wiodąca bez zmian: sesja „w tle" nie jest celem tapnięcia — jej tura już się skończyła.
130
+ // A session after a turn whose subagent is stuck on its own command waits for the owner: it counts once, as waiting.
131
+ const stuck = sessions.filter((s) => stuckWait(s.state, s.backgroundTasks));
132
+ const background = sessions.filter((s) => QUIET.includes(s.state) && !stuck.includes(s)
133
+ && hasBackgroundWork(s.backgroundTasks));
134
+ const finished = sessions.filter((s) => s.state === 'waiting-input' && s.seen !== true && !stuck.includes(s) && !hasBackgroundWork(s.backgroundTasks)).length;
135
+ // Wiodąca bez zmian: sesja „w tle" nie jest celem tapnięcia — jej tura już się skończyła. The same holds for a
136
+ // stuck session, so it is not a lead candidate.
133
137
  const lead = longest(waiting) ?? longest(working);
134
138
  const runs = openRuns(sessions);
135
139
  const workflows = runs.slice(0, LIVE_ACTIVITY_WORKFLOWS_MAX).map(workflowOf);
@@ -137,7 +141,7 @@ export function aggregateState(sessions, nowMs, extras = {}) {
137
141
  const limits = extras.limits !== undefined && Object.keys(extras.limits).length > 0 ? extras.limits : undefined;
138
142
  const mac = extras.mac !== undefined && Object.keys(extras.mac).length > 0 ? extras.mac : undefined;
139
143
  return {
140
- waiting: waiting.length,
144
+ waiting: waiting.length + stuck.length,
141
145
  working: working.length + background.length,
142
146
  finished,
143
147
  ...(lead === undefined ? {} : { top: topOf(lead) }),
@@ -295,8 +295,11 @@ export function createLiveActivity(options) {
295
295
  if (result.kind === 'ok')
296
296
  track.lastCounts = sentCounts.key;
297
297
  }
298
- if (chime !== undefined)
299
- safeLog(`live-activity: done chime → ${countsOutcomeOf(result)}`);
298
+ // `updatedEpoch` of the sent content: the app traces every content it receives with the same number, so the two
299
+ // logs join on it (did the chime land while the app was already in the foreground).
300
+ if (chime !== undefined) {
301
+ safeLog(`live-activity: done chime → ${countsOutcomeOf(result)}, updatedEpoch ${String(timestamp)}`);
302
+ }
300
303
  noteCounters();
301
304
  evaluate();
302
305
  };
@@ -59,11 +59,12 @@ export function noResultTurn(turn) {
59
59
  * Końcem zwykłej tury NIE jest: tura bez wyniku ({@link noResultTurn}: po samym postoju albo po
60
60
  * samym meldunku o artefakcie bez narzędzi), pierwsze `idle` karty odtworzonej po restarcie herdr
61
61
  * ani start sesji ({@link ClassifyInput.afterStart}) — w obu ostatnich żadna tura się nie skończyła.
62
+ * Nor is the end of a turn of a test session ({@link ClassifyInput.testSession}): nobody owes the owner its result.
62
63
  */
63
64
  export function leavesResult(input) {
64
65
  if (kindOf(input.event) !== 'done')
65
66
  return false;
66
- if (input.afterHerdrRestore === true || input.afterStart === true)
67
+ if (input.afterHerdrRestore === true || input.afterStart === true || input.testSession === true)
67
68
  return false;
68
69
  return !noResultTurn(input.turnInput);
69
70
  }
@@ -160,9 +161,10 @@ export function classify(input) {
160
161
  *
161
162
  * Przed wszystkimi trzema: start sesji ({@link ClassifyInput.afterStart})
162
163
  * to cisza, także przy zaległym „gotowe” — sesja wstała, a żadna tura się nie skończyła.
164
+ * A test session ({@link ClassifyInput.testSession}) is silent too: its result is for the agent that started it.
163
165
  */
164
166
  function doneOrSilence(input) {
165
- if (input.afterStart === true)
167
+ if (input.afterStart === true || input.testSession === true)
166
168
  return null;
167
169
  if (input.backgroundTasks > 0)
168
170
  return null;
@@ -0,0 +1,213 @@
1
+ import { buildStalledContent } from './content.js';
2
+ import { PUSH_QUIET_LOG } from './index.js';
3
+ /** Gaps before the 2nd, 3rd and 4th try after `failed` or `no-receiver`; then every last value. */
4
+ export const STALLED_WAIT_RETRY_MS = [60_000, 300_000, 900_000];
5
+ /** How long after the first edge of a wait its alarm may still go out (the push's own lifetime in APNs). */
6
+ export const STALLED_WAIT_WINDOW_MS = 3_600_000;
7
+ const defaultScheduler = {
8
+ setTimeout: (fn, ms) => setTimeout(fn, ms).unref(),
9
+ clearTimeout: (handle) => { clearTimeout(handle); },
10
+ now: () => performance.now(),
11
+ };
12
+ /** Gap after the try number `tries` (1-based) that did not deliver. */
13
+ const retryGap = (tries) => STALLED_WAIT_RETRY_MS[Math.min(tries, STALLED_WAIT_RETRY_MS.length) - 1] ?? STALLED_WAIT_RETRY_MS[2];
14
+ const OUTCOME_LABEL = {
15
+ delivered: 'SENT',
16
+ failed: 'FAILED',
17
+ 'no-receiver': 'NO RECEIVER',
18
+ };
19
+ export function createStalledWaitAlert(options) {
20
+ const scheduler = options.scheduler ?? defaultScheduler;
21
+ const sessions = new Map();
22
+ let closed = false;
23
+ const quiet = (entry, why) => {
24
+ options.log(`${PUSH_QUIET_LOG} ${entry.facts.project} (stalled, ${why})`);
25
+ };
26
+ const drop = (entry, batch) => {
27
+ if (batch.timer !== undefined)
28
+ scheduler.clearTimeout(batch.timer);
29
+ batch.timer = undefined;
30
+ entry.batches.delete(batch);
31
+ };
32
+ /** Ends a batch for good: its waits never alarm again while they stay on the list. */
33
+ const settle = (entry, batch) => {
34
+ for (const key of batch.keys.keys()) {
35
+ const wait = entry.waits.get(key);
36
+ if (wait !== undefined)
37
+ wait.state = 'settled';
38
+ }
39
+ drop(entry, batch);
40
+ };
41
+ /**
42
+ * Settles the waits of a batch whose own window (one hour from the first edge) is over at `at`; the other waits
43
+ * keep their tries. False when no wait is left and the batch is gone.
44
+ */
45
+ const expire = (entry, batch, at) => {
46
+ for (const key of [...batch.keys.keys()]) {
47
+ const wait = entry.waits.get(key);
48
+ if (wait !== undefined && at < wait.edgeAt + STALLED_WAIT_WINDOW_MS)
49
+ continue;
50
+ if (wait !== undefined)
51
+ wait.state = 'settled';
52
+ batch.keys.delete(key);
53
+ }
54
+ if (batch.keys.size > 0)
55
+ return true;
56
+ options.log(`push: stalled for ${entry.facts.project} — not delivered within 1 h, no more tries`);
57
+ drop(entry, batch);
58
+ return false;
59
+ };
60
+ const attempt = async (entry, batch) => {
61
+ batch.timer = undefined;
62
+ if (closed || !entry.batches.has(batch))
63
+ return;
64
+ // A timer that fires late (the process was suspended) must not send after the window.
65
+ if (batch.tries > 0 && !expire(entry, batch, scheduler.now()))
66
+ return;
67
+ if (batch.tries > 0 && options.presence.active()) {
68
+ quiet(entry, 'you are watching Rarog, retry dropped');
69
+ settle(entry, batch);
70
+ return;
71
+ }
72
+ const [agent] = batch.keys.values();
73
+ const { facts } = entry;
74
+ const badge = options.badge?.();
75
+ const content = buildStalledContent({
76
+ project: facts.project, sessionId: facts.sessionId,
77
+ ...(facts.label === undefined ? {} : { label: facts.label }),
78
+ ...(facts.termId === undefined ? {} : { termId: facts.termId }),
79
+ ...(agent === undefined ? {} : { agent }),
80
+ ...(badge === undefined ? {} : { badge }),
81
+ });
82
+ let outcome;
83
+ try {
84
+ outcome = await options.send(content);
85
+ }
86
+ catch {
87
+ outcome = 'failed';
88
+ }
89
+ batch.tries += 1;
90
+ // Forgotten, closed or every wait left `stuck` during the send: the outcome marks nothing.
91
+ if (closed || !entry.batches.has(batch))
92
+ return;
93
+ if (outcome !== 'no-receiver' || batch.tries === 1) {
94
+ options.log(`push: stalled for ${facts.project} — APNs: ${OUTCOME_LABEL[outcome]} (try ${String(batch.tries)})`);
95
+ }
96
+ if (outcome === 'delivered') {
97
+ settle(entry, batch);
98
+ return;
99
+ }
100
+ // The gap counts from the outcome: a slow send must not shorten the wait before the next try.
101
+ const gap = retryGap(batch.tries);
102
+ if (!expire(entry, batch, scheduler.now() + gap))
103
+ return;
104
+ batch.timer = scheduler.setTimeout(() => { run(entry, batch); }, gap);
105
+ };
106
+ const run = (entry, batch) => {
107
+ attempt(entry, batch).catch((err) => {
108
+ options.log(`push: stalled — internal error ${err.message}`);
109
+ });
110
+ };
111
+ /** New edges of one swap: the waits that may still alarm, each with its first edge. */
112
+ const candidates = (entry, newly) => {
113
+ const now = scheduler.now();
114
+ const fresh = [];
115
+ let already = false;
116
+ let late = false;
117
+ for (const edge of newly) {
118
+ const wait = entry.waits.get(edge.key);
119
+ if (wait === undefined) {
120
+ entry.waits.set(edge.key, { edgeAt: now, state: 'pending' });
121
+ fresh.push(edge);
122
+ }
123
+ else if (wait.state === 'idle' && now < wait.edgeAt + STALLED_WAIT_WINDOW_MS) {
124
+ wait.state = 'pending';
125
+ fresh.push(edge);
126
+ }
127
+ else if (wait.state === 'idle') {
128
+ wait.state = 'settled';
129
+ late = true;
130
+ }
131
+ else {
132
+ already = true;
133
+ }
134
+ }
135
+ if (already)
136
+ quiet(entry, 'this wait already had its alarm');
137
+ if (late)
138
+ quiet(entry, 'over 1 h since the first edge of this wait');
139
+ return fresh;
140
+ };
141
+ const update = (facts, waits) => {
142
+ const entry = sessions.get(facts.sessionId) ?? { facts, waits: new Map(), batches: new Set() };
143
+ sessions.set(facts.sessionId, entry);
144
+ entry.facts = facts;
145
+ const listed = new Set(waits.waitKeys);
146
+ const stuck = new Set(waits.stuckKeys);
147
+ for (const key of [...entry.waits.keys()])
148
+ if (!listed.has(key))
149
+ entry.waits.delete(key);
150
+ for (const batch of [...entry.batches]) {
151
+ for (const key of [...batch.keys.keys()]) {
152
+ if (stuck.has(key))
153
+ continue;
154
+ batch.keys.delete(key);
155
+ const wait = entry.waits.get(key);
156
+ if (wait?.state === 'pending')
157
+ wait.state = 'idle';
158
+ }
159
+ if (batch.keys.size === 0)
160
+ drop(entry, batch);
161
+ }
162
+ const fresh = candidates(entry, waits.newly);
163
+ if (fresh.length > 0) {
164
+ const batch = {
165
+ keys: new Map(fresh.map((edge) => [edge.key, edge.description])),
166
+ tries: 0,
167
+ timer: undefined,
168
+ };
169
+ entry.batches.add(batch);
170
+ if (facts.testSession) {
171
+ quiet(entry, 'test session in a temporary directory');
172
+ settle(entry, batch);
173
+ }
174
+ else if (options.presence.active()) {
175
+ quiet(entry, 'you are watching Rarog');
176
+ settle(entry, batch);
177
+ }
178
+ else {
179
+ run(entry, batch);
180
+ }
181
+ }
182
+ if (entry.waits.size === 0 && entry.batches.size === 0)
183
+ sessions.delete(facts.sessionId);
184
+ };
185
+ return {
186
+ update(facts, waits) {
187
+ if (closed)
188
+ return;
189
+ try {
190
+ update(facts, waits);
191
+ }
192
+ catch (err) {
193
+ options.log(`push: stalled — internal error ${err.message}`);
194
+ }
195
+ },
196
+ forget(sessionId) {
197
+ const entry = sessions.get(sessionId);
198
+ if (entry === undefined)
199
+ return;
200
+ for (const batch of [...entry.batches])
201
+ drop(entry, batch);
202
+ sessions.delete(sessionId);
203
+ },
204
+ close() {
205
+ closed = true;
206
+ for (const entry of sessions.values())
207
+ for (const batch of [...entry.batches])
208
+ drop(entry, batch);
209
+ sessions.clear();
210
+ return Promise.resolve();
211
+ },
212
+ };
213
+ }