@rarog/server 1.1.1 → 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 (64) 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/demo/control.js +4 -2
  12. package/server/src/demo/mock-herdr.js +2 -2
  13. package/server/src/demo/scenarios.js +31 -17
  14. package/server/src/demo/seeds.js +62 -38
  15. package/server/src/drivers/herdr/pull-request-poll.js +5 -5
  16. package/server/src/drivers/herdr/queue-take-back.js +4 -0
  17. package/server/src/drivers/herdr/start-dialog-gate.js +132 -0
  18. package/server/src/drivers/herdr-driver.js +75 -15
  19. package/server/src/herdr/background/cli-shapes.js +16 -15
  20. package/server/src/herdr/background/index.js +7 -7
  21. package/server/src/herdr/background/merge.js +17 -5
  22. package/server/src/herdr/background/notification.js +0 -4
  23. package/server/src/herdr/background/pull-request-files.js +53 -161
  24. package/server/src/herdr/background/pull-requests.js +54 -632
  25. package/server/src/herdr/background/work.js +84 -0
  26. package/server/src/herdr/dialogs/copy.js +7 -0
  27. package/server/src/herdr/dialogs/index.js +4 -1
  28. package/server/src/herdr/dialogs/screen/form.js +2 -1
  29. package/server/src/herdr/dialogs/screen/option-run.js +25 -3
  30. package/server/src/herdr/dialogs/screen/parse.js +3 -3
  31. package/server/src/herdr/dialogs/screen/signatures.js +55 -0
  32. package/server/src/herdr/dialogs/screen/start-dialog.js +72 -0
  33. package/server/src/herdr/dialogs/screen/trust-arrow.js +46 -9
  34. package/server/src/herdr/jsonl-follow.js +6 -2
  35. package/server/src/herdr/label-code.js +104 -0
  36. package/server/src/herdr/label-migration.js +142 -0
  37. package/server/src/herdr/launcher.js +30 -5
  38. package/server/src/herdr/provenance.js +80 -40
  39. package/server/src/herdr/start-dialog-wait.js +96 -0
  40. package/server/src/herdr/supervisor.js +33 -10
  41. package/server/src/herdr/workspace-resolver.js +5 -4
  42. package/server/src/index.js +8 -3
  43. package/server/src/notify/apns-payload.js +5 -3
  44. package/server/src/notify/content.js +37 -0
  45. package/server/src/notify/index.js +4 -0
  46. package/server/src/notify/live-activity-state.js +9 -5
  47. package/server/src/notify/live-activity.js +5 -2
  48. package/server/src/notify/policy.js +4 -2
  49. package/server/src/notify/stalled-wait.js +213 -0
  50. package/server/src/pr-status/facts.js +87 -0
  51. package/server/src/pr-status/gh.js +76 -9
  52. package/server/src/pr-status/index.js +1 -10
  53. package/server/src/pr-status/source.js +20 -6
  54. package/server/src/pr-status/tracker.js +32 -9
  55. package/server/src/sessions/conversation-lists.js +8 -2
  56. package/server/src/sessions/driver-events.js +7 -3
  57. package/server/src/sessions/interrupt-windows.js +28 -4
  58. package/server/src/sessions/manager.js +14 -5
  59. package/server/src/sessions/pr-status-link.js +64 -16
  60. package/server/src/sessions/session.js +10 -3
  61. package/server/src/sessions/state-machine.js +11 -0
  62. package/server/src/sessions/test-session.js +50 -0
  63. package/server/src/term/herdr-backend.js +15 -12
  64. package/server/src/term/lifecycle.js +4 -6
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rarog/shared",
3
- "version": "1.1.1",
3
+ "version": "1.1.2-beta.1",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -59,6 +59,8 @@ export const DEGRADATIONS = {
59
59
  'activity.kind': undefined,
60
60
  'waitingFor.kind': undefined,
61
61
  'backgroundTasks.kind': UNSUPPORTED,
62
+ /** `BackgroundTask.ownCommandWait`: an unknown stage drops the field, so the task reads as without a known wait. */
63
+ 'backgroundTasks.ownCommandWait': undefined,
62
64
  /** Notka systemowa — nie udaje ani człowieka, ani agenta. */
63
65
  'message.role': 'system',
64
66
  /** Blok zastępczy `{ type: 'unsupported' }`; reszta pól nieznanego bloku jest odcinana. */
@@ -205,6 +207,7 @@ function buildSchemas(raw) {
205
207
  activity: activity.optional(),
206
208
  backgroundTasks: z.array(backgroundTaskSchema.extend({
207
209
  kind: lenient(backgroundTaskSchema.shape.kind, UNSUPPORTED),
210
+ ownCommandWait: lenientOpt(backgroundTaskSchema.shape.ownCommandWait, undefined),
208
211
  })).optional(),
209
212
  waitingFor: waitingFor.optional(),
210
213
  pullRequests: z.array(sessionPullRequestSchema.extend({
@@ -9,4 +9,5 @@ export const NOTIFY_KIND_TITLE = {
9
9
  done: 'push.title.done',
10
10
  error: 'push.title.error',
11
11
  limit: 'push.title.limit',
12
+ stalled: 'push.title.stalled',
12
13
  };
@@ -5,6 +5,12 @@
5
5
  * Re-exported unchanged by `shared/src/protocol.ts`; code imports the names from there.
6
6
  */
7
7
  import { z } from 'zod';
8
+ /**
9
+ * How long a subagent in standby has waited on its own background command (`BackgroundTask.ownCommandWait`), on the
10
+ * server clock from `waitingSince`: `short` below 30 minutes, `long` from 30, `stuck` from 60
11
+ * (`docs/subagent-long-wait.md`). Wire values; a new meaning is a new value.
12
+ */
13
+ export const OWN_COMMAND_WAITS = ['short', 'long', 'stuck'];
8
14
  /**
9
15
  * PR state on GitHub (`SessionPullRequest.state`): the wire values, lowercase. `draft` is an open PR marked as a draft
10
16
  * on GitHub; only an open PR can be one.
@@ -41,6 +47,7 @@ export const backgroundTaskSchema = z.object({
41
47
  // nieznane klucze, więc bez tych linii klient parsujący tym schematem by ich nie zobaczył.
42
48
  waitingSince: z.string().optional(),
43
49
  ownTasks: z.array(agentOwnTaskSchema).optional(),
50
+ ownCommandWait: z.enum(OWN_COMMAND_WAITS).optional(),
44
51
  });
45
52
  const _agentOwnTaskSchemaMatchesType = true;
46
53
  const _agentOwnTaskTypeMatchesSchema = true;
@@ -88,6 +88,16 @@ export const DIALOGS_SENTENCES = {
88
88
  'dialogs.stale-decision': {
89
89
  en: "⚠ The answer didn't go through: the dialog in the terminal changed in the meantime. Tap again on the new card. Rarog sent no key.",
90
90
  },
91
+ 'dialogs.start-dialog.imports': {
92
+ en: 'Claude Code asks in the terminal whether to allow external imports in the instruction files of this project. ' +
93
+ 'Answer it in the terminal: Claude Code keeps the answer for this project for good. Rarog sends no key to it.',
94
+ },
95
+ 'dialogs.start-dialog.refused': {
96
+ en: '⚠ A Claude Code start dialog stands in the terminal. Rarog sent no key and no text. Answer it in the terminal.',
97
+ },
98
+ 'dialogs.start-dialog.unknown': {
99
+ en: "Claude Code stands on a start dialog Rarog doesn't know. Answer it in the terminal; Rarog sends no key to it.",
100
+ },
91
101
  'dialogs.submit-abort.not-a-form': { en: 'the screen no longer shows a question form' },
92
102
  'dialogs.submit-abort.notes-editing': {
93
103
  en: 'the form is in note-editing mode (the digit may have been typed as text; check the field)',
@@ -12,6 +12,8 @@ export const PUSH_SENTENCES = {
12
12
  'push.body.fallback.limit': { en: 'Open to see when to try again.' },
13
13
  'push.body.fallback.permission': { en: 'Open to decide.' },
14
14
  'push.body.fallback.question': { en: 'The agent asked a question. Answer in Rarog.' },
15
+ 'push.body.fallback.stalled': { en: 'A subagent is waiting on its own command.' },
16
+ 'push.detail.stalled': { en: 'Subagent "{agent}" is waiting on its own command.', args: ['agent:text'] },
15
17
  'push.body.label': { en: '{label}', args: ['label:text'] },
16
18
  'push.paired-body.mac': {
17
19
  en: "{label}. If this wasn't you, revoke it on the Mac: rarog devices",
@@ -30,6 +32,7 @@ export const PUSH_SENTENCES = {
30
32
  'push.title.limit': { en: '✋ Plan limit · {project}', args: ['project:text'] },
31
33
  'push.title.permission': { en: '⏳ Waiting for permission · {project}', args: ['project:text'] },
32
34
  'push.title.question': { en: '❓ Question · {project}', args: ['project:text'] },
35
+ 'push.title.stalled': { en: '⏰ Waiting over 1 h · {project}', args: ['project:text'] },
33
36
  'push.version-title': { en: '🔄 Version changed' },
34
37
  'push.version-body.claude-code': { en: 'Claude Code {from} → {to}', args: ['from:text', 'to:text'] },
35
38
  'push.version-body.herdr': { en: 'herdr {from} → {to}', args: ['from:text', 'to:text'] },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rarog/server",
3
- "version": "1.1.1",
3
+ "version": "1.1.2-beta.1",
4
4
  "description": "Rarog is a free, open-source (MIT) iPhone and iPad app, plus a server on your Mac or Linux machine, that shows the Claude Code sessions running in Herdr TUI and lets you drive them.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "@number0/iroh": "1.2.0",
37
- "@rarog/shared": "1.1.1",
37
+ "@rarog/shared": "1.1.2-beta.1",
38
38
  "qrcode": "1.5.4",
39
39
  "ws": "8.21.3",
40
40
  "zod": "4.4.3"
@@ -2,21 +2,25 @@ import { createFixedPrStateSource, createGhSource, createPrStatusTracker } from
2
2
  /** Tracker and port over a source; the change callback goes to the listener the manager registers. */
3
3
  export function createPrStatusLink(opts) {
4
4
  let listener = null;
5
- const tracker = createPrStatusTracker({ ...opts, onChange: (urls) => { listener?.(urls); } });
5
+ const tracker = createPrStatusTracker({ ...opts, onChange: (change) => { listener?.(change); } });
6
6
  return {
7
7
  tracker,
8
8
  port: {
9
9
  stateOf: (url) => tracker.stateOf(url),
10
+ factsOf: (url) => tracker.factsOf(url),
11
+ viewerLogin: () => tracker.viewerLogin(),
10
12
  setSessionUrls: (sessionId, urls) => { tracker.setSessionUrls(sessionId, urls); },
13
+ setSessionLinks: (sessionId, urls) => { tracker.setSessionLinks(sessionId, urls); },
11
14
  dropSession: (sessionId) => { tracker.dropSession(sessionId); },
12
15
  listen: (onChange) => { listener = onChange; },
13
16
  },
14
17
  };
15
18
  }
16
19
  /**
17
- * The PR status of this process, or `null` when `RAROG_PR_STATUS=0`. The demo source is a fixed map of the active
18
- * content set (`demoContent`, `null` outside the demo) read without delay, so a demo list gets its state at once; it is
19
- * loaded lazily, like the rest of the demo content.
20
+ * The PR status of this process, or `null` when `RAROG_PR_STATUS=0`. The demo source is the fixed GitHub of the
21
+ * active content set (`demoContent`, `null` outside the demo; states, titles, authors, the demo login) read without
22
+ * delay and without a connected client, so a demo list gets its facts and state at once; it is loaded lazily, like
23
+ * the rest of the demo content.
20
24
  */
21
25
  export async function createPrStatus(config, log, demoContent, deps = {}) {
22
26
  if (!config.prStatusEnabled)
@@ -25,10 +29,14 @@ export async function createPrStatus(config, log, demoContent, deps = {}) {
25
29
  if (config.demo) {
26
30
  if (demoContent === null)
27
31
  throw new Error('createPrStatus: demo mode requires demoContent');
28
- const { demoPullRequestStates } = await import('../demo/seeds.js');
29
- return createPrStatusLink({
30
- source: createFixedPrStateSource(demoPullRequestStates(demoContent)), log: logLine, newUrlDelayMs: 0,
32
+ const { demoGitHub } = await import('../demo/seeds.js');
33
+ const link = createPrStatusLink({
34
+ source: createFixedPrStateSource(demoGitHub(demoContent)), log: logLine, newUrlDelayMs: 0,
31
35
  });
36
+ // The fixed map starts no process: it is read whatever the client count, so a scenario created before the app
37
+ // connects has its list at once.
38
+ link.tracker.setClientConnected(true);
39
+ return { ...link, tracker: { ...link.tracker, setClientConnected: () => undefined } };
32
40
  }
33
41
  const ghSource = deps.ghSource ?? createGhSource;
34
42
  return createPrStatusLink({ source: ghSource({ env: { ...config.prStatusEnvBase } }), log: logLine });
@@ -2,8 +2,26 @@ import { createApnsChannel } from '../notify/apns-channel.js';
2
2
  import { createFanoutSink } from '../notify/fanout.js';
3
3
  import { Notifier, sessionLook } from '../notify/index.js';
4
4
  import { Presence } from '../notify/presence.js';
5
+ import { createStalledWaitAlert } from '../notify/stalled-wait.js';
6
+ import { inTemporaryDirectory } from '../sessions/test-session.js';
5
7
  /** Start log phrase when `RAROG_PUSH_RELAY_URL` has a bad value (`docs/server-config.md`). */
6
8
  export const PUSH_RELAY_DISABLED_LOG = 'push: push relay off';
9
+ /**
10
+ * The stalled wait alarm behind the manager's listener: the session facts of the push (`title`, `label`, `termId`) and
11
+ * the test session rule (`inTemporaryDirectory(cwd)`) come from the session at every list swap.
12
+ */
13
+ export function stalledWaitListener(alert, testSession = inTemporaryDirectory) {
14
+ return {
15
+ stuckWaits: (session, waits) => {
16
+ alert.update({
17
+ sessionId: session.id, project: session.title, testSession: testSession(session.cwd),
18
+ ...(session.label === undefined ? {} : { label: session.label }),
19
+ ...(session.termId === undefined ? {} : { termId: session.termId }),
20
+ }, waits);
21
+ },
22
+ forget: (sessionId) => { alert.forget(sessionId); },
23
+ };
24
+ }
7
25
  export function createPush(config, deps) {
8
26
  const { managerRef, devices, macStats, log } = deps;
9
27
  /*
@@ -44,6 +62,10 @@ export function createPush(config, deps) {
44
62
  // Klucze push urządzeń i filtr tokenów odpiętych: magazyn `devices.json` powstał wcześniej.
45
63
  pairedDevices: devices,
46
64
  });
65
+ // Plakietka na ikonie = sesje, które STOJĄ i czekają na człowieka (`waiting-permission`
66
+ // i `waiting-question`). Liczona w chwili WYSYŁKI.
67
+ const badge = () => (managerRef()?.list() ?? [])
68
+ .filter((s) => s.state === 'waiting-permission' || s.state === 'waiting-question').length;
47
69
  /*
48
70
  * Harmonogram powstaje WYŁĄCZNIE z kanałem APNs — to jedyny kanał zdolny wysłać baner. Bez
49
71
  * niego nie ma też obecności w routerze (`main()`), więc `POST /api/presence` jest no-opem.
@@ -55,12 +77,13 @@ export function createPush(config, deps) {
55
77
  // Dźwięk „skończył” z kafla Live Activity: zlecany przy wysłanym „gotowe”.
56
78
  sink: createFanoutSink({ apns: apns.sink, chime: () => apns.liveActivity.chime() }),
57
79
  look: (id) => sessionLook(managerRef()?.get(id)),
58
- // Plakietka na ikonie = sesje, które STOJĄ i czekają na człowieka (`waiting-permission`
59
- // i `waiting-question`). Liczona w chwili WYSYŁKI.
60
- badge: () => (managerRef()?.list() ?? [])
61
- .filter((s) => s.state === 'waiting-permission' || s.state === 'waiting-question').length,
80
+ badge,
62
81
  })
63
82
  : null;
83
+ // The stalled wait alarm sends through the same sink, next to the scheduler and never through it.
84
+ const alert = apns === undefined ? undefined : createStalledWaitAlert({
85
+ send: (content) => apns.sink.send(content), presence, badge, log: (line) => { log.info(line); },
86
+ });
64
87
  if (notifier !== null && apns !== undefined) {
65
88
  // Powrót do Raroga kasuje czekające banery i dźwięki kafla, które jeszcze nie wyszły.
66
89
  const liveActivity = apns.liveActivity;
@@ -84,5 +107,13 @@ export function createPush(config, deps) {
84
107
  // Przepustki dla wpisów, które ich nie mają albo którym kończy się termin; bez przekaźnika — nic.
85
108
  apns.passes?.start();
86
109
  }
87
- return { presence, apns, notifier };
110
+ return {
111
+ presence, apns, notifier,
112
+ stalledWait: alert === undefined ? undefined : stalledWaitListener(alert),
113
+ close: () => {
114
+ // The alarm only stops its timers (nothing to wait for), so the channel starts closing at once, as before.
115
+ void alert?.close();
116
+ return apns?.close() ?? Promise.resolve();
117
+ },
118
+ };
88
119
  }
@@ -1,7 +1,9 @@
1
1
  /**
2
- * `rarog doctor`: the PR status line (`docs/pull-requests.md`). It looks for `gh` the way the server does (the closed
3
- * directory list, `~/` from the service environment that `buildServeEnv` gives), then runs
4
- * `gh auth status --active --no-refresh --hostname github.com` with the same closed environment as the server's reads.
2
+ * `rarog doctor`: the PR status line (`docs/pull-requests.md`). Session cards list only PRs whose author GitHub
3
+ * confirms through the `gh` login, so without `gh` in the closed directory list and a login they show no PRs. It
4
+ * looks for `gh` the way the server does (the closed directory list, `~/` from the service environment that
5
+ * `buildServeEnv` gives), then runs `gh auth status --active --no-refresh --hostname github.com` with the same closed
6
+ * environment as the server's reads.
5
7
  *
6
8
  * `RAROG_PR_STATUS=0` = info; the demo and its review mode (`RAROG_DEMO`, as `bootstrap/pr-status.ts` decides) = info
7
9
  * about the fixed state source, no lookup; no `gh` = warn with a fix; not logged in, a `gh` too old for the check's
@@ -15,14 +17,16 @@ import { GH_AUTH_ARGV, GH_DIRECTORIES, GH_HOST, checkGhAuth, findGh } from '../p
15
17
  const LOGIN = `gh auth login --hostname ${GH_HOST}`;
16
18
  const CHECK = `gh ${GH_AUTH_ARGV.join(' ')}`;
17
19
  const CHECK_FLAGS = GH_AUTH_ARGV.filter((arg) => arg === '--active' || arg === '--no-refresh').join(' ');
20
+ /** Without GitHub's answer no linked PR is confirmed as the user's, so the cards list none. */
21
+ const NO_PRS = ', so session cards show no PRs';
18
22
  /** The line for given facts; no process, no disk. */
19
23
  export function prStatusLineOf(input) {
20
24
  if (input.flag.trim() === '0')
21
- return { verdict: 'info', text: `PR status: off (${PR_STATUS_ENV}=0)` };
25
+ return { verdict: 'info', text: `PR status: off (${PR_STATUS_ENV}=0)${NO_PRS}` };
22
26
  if (input.gh === null) {
23
27
  return {
24
28
  verdict: 'warn',
25
- text: `PR status: gh not found in ${(input.directories ?? GH_DIRECTORIES).join(', ')}, so PRs show no state`,
29
+ text: `PR status: gh not found in ${(input.directories ?? GH_DIRECTORIES).join(', ')}${NO_PRS}`,
26
30
  repair: `install the GitHub CLI (gh) in one of these directories, run ${LOGIN} and restart the server,`
27
31
  + ` or set ${PR_STATUS_ENV}=0 in config.json`,
28
32
  };
@@ -32,7 +36,7 @@ export function prStatusLineOf(input) {
32
36
  if (input.auth === 'not-logged-in') {
33
37
  return {
34
38
  verdict: 'warn',
35
- text: `PR status: ${input.gh} is not logged in to ${GH_HOST}, so PRs show no state`,
39
+ text: `PR status: ${input.gh} is not logged in to ${GH_HOST}${NO_PRS}`,
36
40
  repair: `${LOGIN} as the user the service runs as; the server picks it up within 30 min, without a restart`,
37
41
  };
38
42
  }
@@ -24,7 +24,9 @@ const actionSchema = z.discriminatedUnion('action', [
24
24
  'artifacts', 'pull-requests', 'scheduled-tasks', 'prompt-blocked']),
25
25
  label: z.string().trim().min(1).max(80).optional(),
26
26
  // Katalog sesji zamiast `SCENARIO_CWD`: długa nazwa projektu w nagłówku (tytuł to nazwa katalogu, nie etykieta).
27
- cwd: z.string().startsWith('/').max(200).optional() }).strict(),
27
+ cwd: z.string().startsWith('/').max(200).optional(),
28
+ // `standby` only: the subagent has stood 47 min (`long`) or 75 min (`stuck`) on a wait loop of its own.
29
+ wait: z.enum(['long', 'stuck']).optional() }).strict(),
28
30
  // Notatka projektu zapisana „na innym urządzeniu": nowa wersja w magazynie demo i event `notes`.
29
31
  z.object({ action: z.literal('note-remote'), text: z.string().max(4096) }).strict(),
30
32
  z.object({ action: z.literal('emit'), sessionId: z.uuid(),
@@ -270,7 +272,7 @@ export function createDemoControl(router, config, manager, panels, notes) {
270
272
  if (action.action === 'create') {
271
273
  const scenario = action.scenario;
272
274
  await reset();
273
- const pane = panels.create(scenario, action.label ?? `M1 ${scenario}`, action.cwd);
275
+ const pane = panels.create(scenario, action.label ?? `M1 ${scenario}`, action.cwd, action.wait);
274
276
  sessionId = pane.sessionId;
275
277
  driver = pane.driver;
276
278
  // Adopcja i historia są asynchroniczne. Odpowiedź create daje gotowy scenariusz,
@@ -232,9 +232,9 @@ export function createMockHerdr(content) {
232
232
  // Ten sam wzorzec nazwy co `herdr/uploads.ts` — ścieżka od klienta nie wskaże niczego innego.
233
233
  const readUpload = (cwd, name) => Promise.resolve(UPLOAD_IMAGE_FILE_PATTERN.test(name) ? (uploads.get(uploadKey(cwd, name)) ?? null) : null);
234
234
  const scenarioPanels = {
235
- create(scenario, label, cwd = SCENARIO_CWD) {
235
+ create(scenario, label, cwd = SCENARIO_CWD, wait) {
236
236
  const sessionId = randomUUID();
237
- const driver = new ScenarioDriver(scenario, label);
237
+ const driver = new ScenarioDriver(scenario, label, wait);
238
238
  panes.set(sessionId, { key: sessionId, cwd, scenario: { kind: 'idle' },
239
239
  launchedByRarog: true, driver });
240
240
  // Normalna ścieżka przyłączenia panelu herdr; seedy innych sesji zostają na miejscu.
@@ -4,6 +4,7 @@ import { foreign } from '@rarog/shared/sentences';
4
4
  import { MAX_DIRTY, demoGitStatus } from '../drivers/mock-driver.js';
5
5
  import { AsyncEventQueue } from '../drivers/runtime.js';
6
6
  import { APPLIED, STALE } from '../drivers/types.js';
7
+ import { ownCommandWaitOf } from '../herdr/background/work.js';
7
8
  import { echoKey } from '../herdr/jsonl-follow.js';
8
9
  import { demoArtifacts, demoBlocks, demoPullRequests, demoScheduledTasks, demoStandbyNotice } from './seeds.js';
9
10
  /** Katalog paneli scenariuszy — w tabeli ahead/behind demo (`rarog`: ↓1). */
@@ -27,6 +28,7 @@ export const SCENARIO_BLOCKED_REASON = 'this session must be restarted before it
27
28
  /** Subagent w postoju scenariusza `standby` (sekcja „w tle” apki: trzy stany subagenta). */
28
29
  export const SCENARIO_STANDBY_TASK_ID = 'm1-standby';
29
30
  export const SCENARIO_STANDBY_NAME = 'Przegląd pokrycia testami';
31
+ const STANDBY_WAIT_AGO_MS = { long: 47 * 60_000, stuck: 75 * 60_000 };
30
32
  /**
31
33
  * Rozkład startowy: 12 skończonych agentów implementacji, 44 skończonych i jeden żywy (od 4 min)
32
34
  * w Review, Poprawki bez agentów. Review ma 45 agentów: rozwinięta lista jej skończonych przewija panel na
@@ -52,7 +54,7 @@ export class ScenarioDriver {
52
54
  sends = 0;
53
55
  decisions = 0;
54
56
  answers = [];
55
- constructor(scenario, label) {
57
+ constructor(scenario, label, wait) {
56
58
  this.#blocksPrompts = scenario === 'prompt-blocked';
57
59
  this.events.push({ type: 'init', engineSessionId: randomUUID(), model: 'claude-fable-5-1' });
58
60
  this.events.push({ type: 'title', title: label });
@@ -70,11 +72,14 @@ export class ScenarioDriver {
70
72
  // „Skończone ostatnio".
71
73
  const now = Date.now();
72
74
  const at = (agoMs) => new Date(now - agoMs).toISOString();
73
- const notice = demoStandbyNotice(18 * 60_000, SCENARIO_STANDBY_NAME);
75
+ const standingMs = wait === undefined ? 18 * 60_000 : STANDBY_WAIT_AGO_MS[wait];
76
+ // The start of the turn, 7 min before the standby, as in the plain scenario.
77
+ const startedMs = standingMs + 7 * 60_000;
78
+ const notice = demoStandbyNotice(standingMs, SCENARIO_STANDBY_NAME);
74
79
  this.events.push({ type: 'history', messages: [
75
- { role: 'user', at: at(26 * 60_000),
80
+ { role: 'user', at: at(startedMs + 60_000),
76
81
  blocks: [{ type: 'text', text: foreign('Policz pokrycie testami modułu transkryptu.') }] },
77
- { role: 'assistant', at: at(25 * 60_000), blocks: [{ type: 'text', text: foreign('Puszczam subagenta w tle.') }] },
82
+ { role: 'assistant', at: at(startedMs), blocks: [{ type: 'text', text: foreign('Puszczam subagenta w tle.') }] },
78
83
  { role: 'user', at: at(notice.agoMs), blocks: demoBlocks(notice.blocks), notice: notice.notice },
79
84
  { role: 'assistant', at: at(notice.agoMs - 2000),
80
85
  blocks: [{
@@ -82,13 +87,17 @@ export class ScenarioDriver {
82
87
  }] },
83
88
  ] });
84
89
  // Stoi od 18 min i czeka na dwie własne komendy; druga bez treści (serwer bywa, że jej nie zna).
85
- this.#standby = {
86
- startedAt: at(25 * 60_000), waitingSince: at(18 * 60_000), waiting: true,
87
- commands: [
90
+ // The variant stands on a wait loop of its own: a `pgrep` that matches its own shell and a `sleep`.
91
+ const commands = wait === undefined
92
+ ? [
88
93
  { id: `${SCENARIO_STANDBY_TASK_ID}-cmd-1`, command: 'pnpm test -- --coverage', startedAt: at(21 * 60_000) },
89
94
  { id: `${SCENARIO_STANDBY_TASK_ID}-cmd-2`, startedAt: at(19 * 60_000) },
90
- ],
91
- };
95
+ ]
96
+ : [
97
+ { id: `${SCENARIO_STANDBY_TASK_ID}-cmd-1`, command: "pgrep -f 'demo-build'", startedAt: at(standingMs + 3 * 60_000) },
98
+ { id: `${SCENARIO_STANDBY_TASK_ID}-cmd-2`, command: 'sleep 30', startedAt: at(standingMs + 60_000) },
99
+ ];
100
+ this.#standby = { startedAt: at(startedMs), waitingSince: at(standingMs), waiting: true, commands };
92
101
  }
93
102
  if (scenario === 'artifacts')
94
103
  this.#pushArtifacts();
@@ -169,7 +178,7 @@ export class ScenarioDriver {
169
178
  say('user', 2 * hour + 60_000, 'Dodaj eksport notatek do CSV i otwórz PR.'),
170
179
  say('assistant', 2 * hour - 5000, 'PR z eksportem otwarty.'),
171
180
  ] });
172
- this.events.push({ type: 'pull-requests', pullRequests: demoPullRequests(now) });
181
+ this.events.push({ type: 'pull-requests', ...demoPullRequests(now) });
173
182
  }
174
183
  /**
175
184
  * Scenario `scheduled-tasks` (the inspector's scheduled tasks section): a short history, then a one-shot and a
@@ -188,17 +197,22 @@ export class ScenarioDriver {
188
197
  ] });
189
198
  this.events.push({ type: 'scheduled-tasks', scheduledTasks: demoScheduledTasks(now) });
190
199
  }
191
- /** Lista zadań scenariusza `standby`: jeden subagent, w postoju albo (po `agent-wake`) pracujący. */
200
+ /**
201
+ * Lista zadań scenariusza `standby`: jeden subagent, w postoju albo (po `agent-wake`) pracujący. The wait stage comes
202
+ * from `ownCommandWaitOf` with the clock of this emission, as `merge.ts` sets it on production lists.
203
+ */
192
204
  #pushStandby() {
193
205
  const agent = this.#standby;
194
206
  if (agent === null)
195
207
  return;
196
- this.events.push({ type: 'background-tasks', tasks: [{
197
- id: SCENARIO_STANDBY_TASK_ID, kind: 'agent', description: SCENARIO_STANDBY_NAME, agentType: 'general-purpose',
198
- model: 'claude-opus-5-5', startedAt: agent.startedAt,
199
- ...(agent.waiting ? { waitingSince: agent.waitingSince } : {}),
200
- ...(agent.commands.length > 0 ? { ownTasks: agent.commands.map((command) => ({ ...command })) } : {}),
201
- }] });
208
+ const task = {
209
+ id: SCENARIO_STANDBY_TASK_ID, kind: 'agent', description: SCENARIO_STANDBY_NAME, agentType: 'general-purpose',
210
+ model: 'claude-opus-5-5', startedAt: agent.startedAt,
211
+ ...(agent.waiting ? { waitingSince: agent.waitingSince } : {}),
212
+ ...(agent.commands.length > 0 ? { ownTasks: agent.commands.map((command) => ({ ...command })) } : {}),
213
+ };
214
+ const stage = ownCommandWaitOf(task, Date.now());
215
+ this.events.push({ type: 'background-tasks', tasks: [stage === undefined ? task : { ...task, ownCommandWait: stage }] });
202
216
  }
203
217
  /**
204
218
  * `agent-wake`: pierwsza własna komenda agenta się skończyła, więc agent ruszył sam. Jedzie w górę bez
@@ -19,7 +19,8 @@ import { DEMO_DIFF_FILES, demoAheadBehind } from '../drivers/mock-driver.js';
19
19
  import { toolCallSemantics, writeDiffText } from '../drivers/tool-text.js';
20
20
  import { createArtifactsTracker } from '../herdr/background/artifacts.js';
21
21
  import { noticeFromText } from '../herdr/background/notice.js';
22
- import { sessionPullRequests } from '../herdr/background/pull-requests.js';
22
+ import { CLI_SHAPES } from '../herdr/background/cli-shapes.js';
23
+ import { parsePullRequestUrl, pullRequestLinks } from '../herdr/background/pull-requests.js';
23
24
  import { createScheduledTasksTracker } from '../herdr/background/scheduled-tasks.js';
24
25
  /** Katalog-korzeń projektów demo (allow-lista `GET /api/projects` w trybie demo). */
25
26
  export const DEMO_PROJECTS_ROOT = '/Users/demo/Projects';
@@ -164,7 +165,7 @@ function seedKit(content, now) {
164
165
  { kind: 'image', name: '', bytes: 0, mime: 'image/png', file: BRIDGE_GONE_FILE },
165
166
  ],
166
167
  chartImage: (alt) => ({ type: 'image', dataUrl: demoImages().chart, alt }),
167
- pullRequests: (calls) => pullRequestsOfCalls(now, calls),
168
+ pullRequests: (links) => pullRequestsOfLinks(now, links),
168
169
  artifacts: (publications) => artifactsOfPublications(now, publications),
169
170
  };
170
171
  }
@@ -303,50 +304,73 @@ export function demoPullRequestStates(content) {
303
304
  ...content.pullRequestStates ?? [],
304
305
  ]);
305
306
  }
307
+ /** The `gh` login of the demo's fixed GitHub: the author of every demo PR. It stays in the server's memory. */
308
+ export const DEMO_GITHUB_LOGIN = 'demo';
306
309
  /**
307
- * Pull requesty sterowanego scenariusza odbioru `pull-requests` (`scenarios.ts`): PR z `--title` utworzony
308
- * 2 h temu, PR z `--fill` (bez tytułu) sprzed doby i PR z `--draft` sprzed ponad dwóch dób (stan `draft` z mapy
309
- * {@link demoPullRequestStates}), najnowszy pierwszy. Listę składa z wpisów pliku rozmowy (wywołanie
310
- * `Bash` i jego wynik) ta sama funkcja co czytnik na produkcji (`sessionPullRequests`), więc zmiana rozpoznania wyjdzie
311
- * też w demo. Repozytoria są syntetyczne.
310
+ * Time of the first entry of every demo conversation and creation time of every demo PR on the demo's fixed GitHub
311
+ * (the epoch): only the window check reads it, so the demo lists do not depend on the server's uptime.
312
+ */
313
+ const DEMO_CONVERSATION_START_MS = 0;
314
+ /**
315
+ * The demo's fixed GitHub (`bootstrap/pr-status.ts`): every demo PR, authored by {@link DEMO_GITHUB_LOGIN}, with the
316
+ * state of {@link demoPullRequestStates} and the title its card shows (the bare PR has neither).
317
+ *
318
+ * The demo has no GitHub clock: every PR counts as created at {@link DEMO_CONVERSATION_START_MS}, the time of the
319
+ * first entry of every demo conversation ({@link pullRequestsOfLinks}). A conversation lists a PR only when it was
320
+ * created at or after that entry, so the demo PRs stay on their lists however long the server runs.
321
+ */
322
+ export function demoGitHub(content) {
323
+ const states = demoPullRequestStates(content);
324
+ const titles = new Map([
325
+ [DEMO_PULL_REQUESTS.titled, DEMO_PULL_REQUESTS.title],
326
+ [DEMO_PULL_REQUESTS.draft, DEMO_PULL_REQUESTS.draftTitle],
327
+ ...content.pullRequestTitles ?? [],
328
+ ]);
329
+ const urls = new Set([DEMO_PULL_REQUESTS.bare, ...states.keys(), ...titles.keys()]);
330
+ const prs = new Map([...urls].map((url) => {
331
+ const state = states.get(url);
332
+ const title = titles.get(url);
333
+ return [url, {
334
+ author: DEMO_GITHUB_LOGIN, createdAtMs: DEMO_CONVERSATION_START_MS,
335
+ ...(state === undefined ? {} : { state }), ...(title === undefined ? {} : { title }),
336
+ }];
337
+ }));
338
+ return { viewer: DEMO_GITHUB_LOGIN, prs };
339
+ }
340
+ /**
341
+ * Linked PRs of the controlled `pull-requests` scenario (`scenarios.ts`): the titled PR linked 2 h ago, the bare one
342
+ * a day ago and the draft over two days ago, newest first. The set goes through the production reader rule
343
+ * ({@link pullRequestsOfLinks}); titles and states come from the demo's fixed GitHub ({@link demoGitHub}).
344
+ * The repositories are synthetic.
312
345
  */
313
346
  export function demoPullRequests(now) {
314
- return pullRequestsOfCalls(now, [
315
- {
316
- command: `gh pr create --draft --title "${DEMO_PULL_REQUESTS.draftTitle}"`, output: DEMO_PULL_REQUESTS.draft,
317
- agoMs: 50 * 60 * MIN,
318
- },
319
- {
320
- command: 'git push -u origin docs-csv && gh pr create --fill',
321
- output: `\nCreating pull request for docs-csv into main in acme/widget-docs\n\n${DEMO_PULL_REQUESTS.bare}`,
322
- agoMs: 26 * 60 * MIN,
323
- },
324
- {
325
- command: `gh pr create --title "${DEMO_PULL_REQUESTS.title}" --body "Exports notes as CSV."`,
326
- output: DEMO_PULL_REQUESTS.titled, agoMs: 2 * 60 * MIN,
327
- },
347
+ return pullRequestsOfLinks(now, [
348
+ { url: DEMO_PULL_REQUESTS.draft, agoMs: 50 * 60 * MIN },
349
+ { url: DEMO_PULL_REQUESTS.bare, agoMs: 26 * 60 * MIN },
350
+ { url: DEMO_PULL_REQUESTS.titled, agoMs: 2 * 60 * MIN },
328
351
  ]);
329
352
  }
330
353
  /**
331
- * PR list of a demo conversation: each call becomes a `Bash` call entry and its result entry in the shape of the
332
- * conversation file, and the production reader (`sessionPullRequests`) builds the list from them.
354
+ * Linked PRs of a demo conversation: a first entry at {@link DEMO_CONVERSATION_START_MS}, then each link as a link
355
+ * entry in the shape of the conversation file; the production rule ({@link pullRequestLinks}) builds the set and the
356
+ * window. The card shows the PRs the demo's fixed GitHub ({@link demoGitHub}) gives the demo login as author, with its titles.
333
357
  */
334
- function pullRequestsOfCalls(now, calls) {
358
+ function pullRequestsOfLinks(now, links) {
335
359
  const iso = (agoMs) => new Date(now - agoMs).toISOString();
336
- return sessionPullRequests(calls.flatMap(({ command, output, agoMs }, index) => {
337
- const id = `demo-pr-${String(index)}`;
338
- return [
339
- JSON.stringify({
340
- type: 'assistant', timestamp: iso(agoMs + 5000),
341
- message: { role: 'assistant', content: [{ type: 'tool_use', id, name: 'Bash', input: { command } }] },
342
- }),
343
- JSON.stringify({
344
- type: 'user', timestamp: iso(agoMs),
345
- message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: output }] },
346
- toolUseResult: { stdout: output, stderr: '', interrupted: false, isImage: false },
347
- }),
348
- ];
349
- }));
360
+ const LINK = CLI_SHAPES.prLink.literals;
361
+ const start = new Date(DEMO_CONVERSATION_START_MS).toISOString();
362
+ const read = pullRequestLinks([
363
+ JSON.stringify({ type: 'user', timestamp: start, message: { role: 'user', content: 'demo' } }),
364
+ ...links.map(({ url, agoMs }) => {
365
+ const pr = parsePullRequestUrl(url);
366
+ return JSON.stringify({
367
+ type: LINK.type, sessionId: 'demo', [LINK.number]: pr?.number, [LINK.url]: url, [LINK.repository]: pr?.repo,
368
+ timestamp: iso(agoMs),
369
+ });
370
+ }),
371
+ ]);
372
+ const pullRequests = read.linked;
373
+ return read.windowStart === null ? { pullRequests } : { pullRequests, windowStart: read.windowStart };
350
374
  }
351
375
  /**
352
376
  * Artifact list of a demo conversation: each publication becomes a result entry of the `Artifact` tool in the shape
@@ -1,6 +1,6 @@
1
- import { PULL_REQUESTS_BACKLOG_MS, pullRequestsSignature } from '../../herdr/background/index.js';
1
+ import { PULL_REQUESTS_BACKLOG_MS, pullRequestLinksSignature } from '../../herdr/background/index.js';
2
2
  export function createPullRequestPollState(prReader, prPollMs) {
3
- return { prReader, prPollMs, prTimer: null, prReading: false, prAgain: false, prSent: pullRequestsSignature([]) };
3
+ return { prReader, prPollMs, prTimer: null, prReading: false, prAgain: false, prSent: pullRequestLinksSignature({ linked: [], windowStart: null }) };
4
4
  }
5
5
  /**
6
6
  * Zamawia odczyt plików rozmowy pod kątem PR-ów za `delayMs`. Sygnały, które przyjdą, zanim zegar
@@ -21,7 +21,7 @@ export function schedulePullRequests(state, deps, delayMs = state.prPollMs) {
21
21
  }, delayMs);
22
22
  }
23
23
  /**
24
- * Jeden odczyt PR-ów i wypłata listy, gdy różni się od wysłanej (pierwsza idzie zawsze). Zaległość odczytu
24
+ * One PR read and the payout of the links when they differ from the ones sent (the set or the window). Zaległość odczytu
25
25
  * (budżet bajtów) zamawia następny po krótkiej przerwie, bez czekania na sygnał.
26
26
  */
27
27
  export async function readPullRequests(state, deps) {
@@ -41,10 +41,10 @@ export async function readPullRequests(state, deps) {
41
41
  if (read === null)
42
42
  return;
43
43
  backlog = read.backlog;
44
- const signature = pullRequestsSignature(read.pullRequests);
44
+ const signature = pullRequestLinksSignature(read.links);
45
45
  if (signature !== state.prSent) {
46
46
  state.prSent = signature;
47
- deps.emit(read.pullRequests);
47
+ deps.emit(read.links);
48
48
  }
49
49
  }
50
50
  finally {
@@ -85,6 +85,10 @@ export class QueueTakeBack {
85
85
  return this.#refuse('pane');
86
86
  if (this.#field.holdsField())
87
87
  return this.#refuse('busy');
88
+ if (await this.#port.startDialogStands())
89
+ return this.#refuse('dialog');
90
+ if (this.#port.disposed())
91
+ return this.#refuse('pane');
88
92
  // The last Enter from Rarog's queue first: a hook may still hand its text back to the field.
89
93
  while (this.#queue.submitUnsettled()) {
90
94
  await this.#sleep(this.#pollMs);