runwork 0.10.2 → 0.10.3

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.
@@ -1,4 +1,4 @@
1
- import { Command } from 'commander';
1
+ import { Command, Option } from 'commander';
2
2
  import { execFileSync } from 'child_process';
3
3
  import { readFileSync, writeFileSync, existsSync } from 'fs';
4
4
  import { join } from 'path';
@@ -9,6 +9,11 @@ import { syncWithRemote } from '../git/sync.js';
9
9
  import { ensureGitIdentity } from '../git/identity.js';
10
10
  import { requireGit } from '../git/preflight.js';
11
11
  import { startLogTailer } from '../logs/tailer.js';
12
+ import { startPreviewUrlPoller } from '../dev/preview-url-poller.js';
13
+ import { buildSessionFile, getSessionState, readSessionFile, removeSessionFile, removeSessionFileIfOwned, writeSessionFile, } from '../dev/session.js';
14
+ import { INTERNAL_DETACHED_CHILD_FLAG, isInternalDetachedChild, runAsDetachedParent, stripInternalChildFlag, } from '../dev/detach.js';
15
+ import { stopSession } from '../dev/stop.js';
16
+ import { formatStartedAgo, getAttachLogPaths, getCurrentPreviewUrl, renderLogLine, resolveAttachTarget, startLogTail, startSessionFileWatch, } from '../dev/attach.js';
12
17
  import { populateTypes } from '../types-manager.js';
13
18
  import { loadManifest, generateManifest, saveManifest, detectUserEdits } from '../template/manifest.js';
14
19
  import { extractZip } from '../utils/zip.js';
@@ -16,9 +21,10 @@ import { removeNestedGitDirs } from '../utils/fs.js';
16
21
  import { getDevBanner, getKeyboardHints, getInfoPanel } from '../ui/banner.js';
17
22
  import { createStatusLine } from '../ui/status-line.js';
18
23
  import { createKeyboardListener } from '../ui/keyboard.js';
19
- import { bold, dim, green, yellow, cyan } from '../ui/colors.js';
24
+ import { bold, dim, green, yellow, cyan, red } from '../ui/colors.js';
20
25
  import { shouldOutputJson, jsonLine } from '../utils/output.js';
21
26
  import { buildDevSessionGuide } from '../utils/agent-guidance.js';
27
+ import { VERSION } from '../generated/version.js';
22
28
  async function populateSkill(projectDir, client, appId) {
23
29
  try {
24
30
  const { skill } = await client.getAppSkill(appId);
@@ -99,12 +105,61 @@ function commitAndPushRestoredFiles(cwd, files) {
99
105
  }
100
106
  export async function execDev(options) {
101
107
  const useJson = options?.json ?? false;
108
+ const mode = options?.mode ?? 'foreground';
102
109
  requireGit('dev');
103
110
  const config = readConfig();
104
111
  const creds = requireAuth();
105
112
  const client = new ApiClient(creds);
106
113
  const cwd = process.cwd();
107
114
  const ts = () => new Date().toISOString();
115
+ // --restart: stop any pre-existing session before starting a new one.
116
+ // We do this BEFORE the "already running" check so the user's intent
117
+ // is respected even when a healthy session is already in place.
118
+ if (options?.restart) {
119
+ const stopOutcome = await stopSession(cwd, config.appId);
120
+ if (!useJson && stopOutcome.result === 'stopped') {
121
+ console.log(dim(`Stopped previous dev session (PID ${stopOutcome.pid}).`));
122
+ }
123
+ if (useJson && (stopOutcome.result === 'stopped' || stopOutcome.result === 'stale-cleaned')) {
124
+ jsonLine({
125
+ event: 'session_stopped',
126
+ pid: 'pid' in stopOutcome ? stopOutcome.pid : undefined,
127
+ timestamp: ts(),
128
+ });
129
+ }
130
+ }
131
+ // Idempotency check: read the session file before doing any work. If a
132
+ // live session is already running for this app on this machine, exit
133
+ // success with a structured event so the caller (human or agent) knows
134
+ // the URL and can move on. Stale files are cleaned up silently.
135
+ const existing = getSessionState(cwd, config.appId);
136
+ if (existing.state === 'alive') {
137
+ const f = existing.file;
138
+ if (useJson) {
139
+ jsonLine({
140
+ event: 'already_running',
141
+ previewUrl: f.previewUrl,
142
+ pid: f.pid,
143
+ sessionId: f.sessionId,
144
+ mode: f.mode,
145
+ timestamp: ts(),
146
+ });
147
+ }
148
+ else {
149
+ console.log(`Dev session already running (PID ${f.pid}, mode: ${f.mode}).`);
150
+ console.log(` Preview: ${green(f.previewUrl || '(starting up)')}`);
151
+ console.log(dim(` Follow logs: runwork dev attach`));
152
+ console.log(dim(` Stop: runwork dev stop`));
153
+ console.log(dim(` Start fresh: runwork dev --restart`));
154
+ }
155
+ return;
156
+ }
157
+ if (existing.state === 'stale') {
158
+ removeSessionFile(cwd);
159
+ if (!useJson) {
160
+ console.log(dim(`Cleaned up dead session from a previous run (reason: ${existing.reason}).`));
161
+ }
162
+ }
108
163
  // Seed a local git identity so the very first commit cannot fail on a
109
164
  // fresh machine where `git config --global user.email/.name` has never
110
165
  // been set (extremely common on Windows after a clean install).
@@ -257,12 +312,30 @@ export async function execDev(options) {
257
312
  console.warn(yellow('Push failed. Continuing with current state...'));
258
313
  }
259
314
  }
315
+ // The session POST returns a snapshot of the preview URL at boot time.
316
+ // Sandboxes can rotate that URL mid-session (instance replacement,
317
+ // tunnel restart), so we treat this as the *initial* value and refresh
318
+ // it via `getDevStatus` -- the same source `runwork info` reads from.
319
+ // That keeps `dev` and `info` in agreement.
320
+ let currentPreviewUrl = session.previewUrl;
321
+ // Write the session file as soon as we have the URL. This is the
322
+ // rendezvous moment for `runwork dev --detach` -- the parent is polling
323
+ // `.runwork/dev-session.json` and exits 0 when this file appears with a
324
+ // non-empty previewUrl matching the child's PID.
325
+ writeSessionFile(cwd, buildSessionFile({
326
+ pid: process.pid,
327
+ sessionId: session.sessionId,
328
+ appId: config.appId,
329
+ previewUrl: currentPreviewUrl,
330
+ cliVersion: VERSION,
331
+ mode,
332
+ }));
260
333
  // Emit session_started (JSON) or show banner (human)
261
334
  if (useJson) {
262
- jsonLine({ event: 'session_started', previewUrl: session.previewUrl, appName: config.appName, timestamp: ts(), guide: buildDevSessionGuide() });
335
+ jsonLine({ event: 'session_started', previewUrl: currentPreviewUrl, appName: config.appName, timestamp: ts(), guide: buildDevSessionGuide() });
263
336
  }
264
337
  else {
265
- console.log(getDevBanner({ appName: config.appName, previewUrl: session.previewUrl, workspaceName: config.workspaceName }));
338
+ console.log(getDevBanner({ appName: config.appName, previewUrl: currentPreviewUrl, workspaceName: config.workspaceName }));
266
339
  console.log(getKeyboardHints());
267
340
  console.log('');
268
341
  console.log(dim(' ─────────────────────────────────────────────'));
@@ -277,16 +350,58 @@ export async function execDev(options) {
277
350
  return;
278
351
  const filterLabel = logFilter === 'all' ? 'All' : logFilter === 'events' ? 'Events' : 'Runtime';
279
352
  const sep = '\x1b[90m\u2502\x1b[39m';
280
- statusLine.update(`${bold(config.appName)} ${sep} ${green(session.previewUrl)} ${sep} ${cyan(`${syncedCount} synced`)} ${sep} ${filterLabel} ${sep} \x1b[90mo\x1b[39m:open \x1b[90mi\x1b[39m:info \x1b[90ma/e/r\x1b[39m:filter \x1b[90mq\x1b[39m:quit`);
353
+ statusLine.update(`${bold(config.appName)} ${sep} ${green(currentPreviewUrl)} ${sep} ${cyan(`${syncedCount} synced`)} ${sep} ${filterLabel} ${sep} \x1b[90mo\x1b[39m:open \x1b[90mi\x1b[39m:info \x1b[90ma/e/r\x1b[39m:filter \x1b[90mq\x1b[39m:quit`);
281
354
  }
282
355
  if (statusLine)
283
356
  updateStatus();
357
+ const previewUrlPoller = startPreviewUrlPoller({
358
+ client,
359
+ appId: config.appId,
360
+ initialUrl: currentPreviewUrl,
361
+ onChange: (next, prev) => {
362
+ currentPreviewUrl = next;
363
+ // Persist the rotated URL into the session file so `runwork info`,
364
+ // detached parent processes, and other observers see the same
365
+ // preview URL we're showing in the status line.
366
+ const current = readSessionFile(cwd);
367
+ if (current && current.pid === process.pid) {
368
+ writeSessionFile(cwd, { ...current, previewUrl: next });
369
+ }
370
+ if (useJson) {
371
+ jsonLine({
372
+ event: 'preview_url_changed',
373
+ previewUrl: next,
374
+ previousUrl: prev,
375
+ appName: config.appName,
376
+ timestamp: ts(),
377
+ });
378
+ }
379
+ else {
380
+ console.log(dim(`Preview URL changed: ${next}`));
381
+ updateStatus();
382
+ }
383
+ },
384
+ });
284
385
  let logTailer;
285
386
  const keyboard = useJson ? null : createKeyboardListener();
286
387
  const cleanup = async () => {
388
+ // Remove the session file FIRST. If a Windows console-close-event
389
+ // truncates our cleanup window, or if we crash later in this handler,
390
+ // at least the file is gone -- the next `runwork dev` will see a
391
+ // clean slate. Stale-detection on next-startup is the primary recovery
392
+ // path; this is just polish for the graceful-exit case.
393
+ //
394
+ // Use the PID-guarded variant: if a startup race ended with another
395
+ // process owning the session file, we must NOT delete it -- that
396
+ // would leave the winner's session orphaned.
397
+ try {
398
+ removeSessionFileIfOwned(cwd, process.pid);
399
+ }
400
+ catch { /* best-effort */ }
287
401
  if (!useJson)
288
402
  console.log('\nStopping...');
289
403
  logTailer?.stop();
404
+ previewUrlPoller.stop();
290
405
  await stopAutoCommit();
291
406
  statusLine?.destroy();
292
407
  keyboard?.stop();
@@ -299,7 +414,7 @@ export async function execDev(options) {
299
414
  switch (action) {
300
415
  case 'o':
301
416
  case 'p':
302
- import('open').then(m => m.default(session.previewUrl));
417
+ import('open').then(m => m.default(currentPreviewUrl));
303
418
  break;
304
419
  case 'a':
305
420
  logFilter = 'all';
@@ -319,7 +434,7 @@ export async function execDev(options) {
319
434
  case 'i':
320
435
  console.log(getInfoPanel({
321
436
  appName: config.appName,
322
- previewUrl: session.previewUrl,
437
+ previewUrl: currentPreviewUrl,
323
438
  workspaceName: config.workspaceName,
324
439
  directory: cwd,
325
440
  }));
@@ -358,7 +473,505 @@ export const devCommand = new Command('dev')
358
473
  .description('Start local development with live sync, preview sandbox, and file watching')
359
474
  .option('--no-logs', 'Disable automatic log tailing')
360
475
  .option('--logs-only-file', 'Write logs to file only, not terminal')
476
+ .option('--detach', 'Start the dev session in the background and exit. Logs go to .runwork/dev-{stdout,stderr}.log')
477
+ .option('--restart', 'Stop any existing dev session first, then start a fresh one')
478
+ // Hidden internal flag passed by `runwork dev --detach` when it spawns
479
+ // its detached child. Not for end users -- registered here only so
480
+ // commander does not throw "unknown option" when the child receives it.
481
+ .addOption(new Option(INTERNAL_DETACHED_CHILD_FLAG).hideHelp())
361
482
  .action(async (options, command) => {
362
483
  const globalJson = shouldOutputJson(command.optsWithGlobals().json);
363
- await execDev({ ...options, json: globalJson });
484
+ // The internal child marker is parsed manually because we want it
485
+ // hidden from --help and from commander's option list. Its presence
486
+ // means: "this process is the detached child of a `--detach` parent;
487
+ // skip the parent-spawn branch and run the actual dev work."
488
+ const isChild = isInternalDetachedChild(process.argv);
489
+ if (options.detach && !isChild) {
490
+ await runDevDetachParent({
491
+ json: globalJson,
492
+ restart: options.restart,
493
+ });
494
+ return;
495
+ }
496
+ await execDev({
497
+ ...options,
498
+ json: globalJson,
499
+ mode: isChild ? 'detached' : 'foreground',
500
+ restart: options.restart,
501
+ });
502
+ });
503
+ /**
504
+ * Parent half of `runwork dev --detach`. Reads the app config to know
505
+ * which appId we're spawning a child for, dispatches to the detach
506
+ * orchestrator in `src/dev/detach.ts`, and renders the outcome.
507
+ *
508
+ * The parent does not do any of the dev work itself -- it is a thin
509
+ * observer that exists only long enough to confirm the child has a
510
+ * preview URL. See `docs/plans/2026-05-06-runwork-dev-lifecycle-design.md`
511
+ * for the full handshake contract.
512
+ */
513
+ async function runDevDetachParent(opts) {
514
+ const config = readConfig();
515
+ const cwd = process.cwd();
516
+ const ts = () => new Date().toISOString();
517
+ // --restart: stop the existing session before spawning a child.
518
+ if (opts.restart) {
519
+ const stopOutcome = await stopSession(cwd, config.appId);
520
+ if (!opts.json && stopOutcome.result === 'stopped') {
521
+ console.log(dim(`Stopped previous dev session (PID ${stopOutcome.pid}).`));
522
+ }
523
+ }
524
+ // Idempotency: if a live session is already running on this machine,
525
+ // don't spawn a second child -- just report it.
526
+ const existing = getSessionState(cwd, config.appId);
527
+ if (existing.state === 'alive') {
528
+ const f = existing.file;
529
+ if (opts.json) {
530
+ jsonLine({
531
+ event: 'already_running',
532
+ previewUrl: f.previewUrl,
533
+ pid: f.pid,
534
+ sessionId: f.sessionId,
535
+ mode: f.mode,
536
+ timestamp: ts(),
537
+ });
538
+ }
539
+ else {
540
+ console.log(`Dev session already running (PID ${f.pid}, mode: ${f.mode}).`);
541
+ console.log(` Preview: ${green(f.previewUrl || '(starting up)')}`);
542
+ console.log(dim(` Follow logs: runwork dev attach`));
543
+ }
544
+ return;
545
+ }
546
+ if (existing.state === 'stale') {
547
+ removeSessionFile(cwd);
548
+ }
549
+ if (opts.json) {
550
+ jsonLine({ event: 'starting', mode: 'detached', timestamp: ts() });
551
+ }
552
+ else {
553
+ console.log(dim('Starting dev session in background...'));
554
+ }
555
+ // Construct the child's args from our own process.argv. We strip the
556
+ // marker (so the parent can't accidentally fall into the child path
557
+ // itself if invoked through a wrapper) and then add it back exactly
558
+ // once.
559
+ //
560
+ // process.argv[0] is the executable, which we replace with
561
+ // `process.execPath` at spawn time. We forward everything from argv[1]
562
+ // onwards. This works for both Node (`node script.js dev --detach` ->
563
+ // ["script.js", "dev", "--detach"]) and Bun-standalone binaries
564
+ // (`runwork dev --detach` -> ["dev", "--detach"]) because in both cases
565
+ // re-spawning with execPath + argv.slice(1) reproduces the same
566
+ // invocation.
567
+ const userArgs = stripInternalChildFlag(process.argv.slice(1));
568
+ const childArgs = [...userArgs, INTERNAL_DETACHED_CHILD_FLAG];
569
+ const outcome = await runAsDetachedParent({
570
+ appDir: cwd,
571
+ expectedAppId: config.appId,
572
+ childArgs,
573
+ });
574
+ switch (outcome.result) {
575
+ case 'started': {
576
+ const f = outcome.file;
577
+ if (opts.json) {
578
+ jsonLine({
579
+ event: 'session_started',
580
+ previewUrl: f.previewUrl,
581
+ pid: f.pid,
582
+ sessionId: f.sessionId,
583
+ mode: f.mode,
584
+ timestamp: ts(),
585
+ guide: buildDevSessionGuide(),
586
+ });
587
+ }
588
+ else {
589
+ console.log('');
590
+ console.log(`Dev session running in background (PID ${f.pid}).`);
591
+ console.log(` Preview: ${green(f.previewUrl)}`);
592
+ console.log(dim(` Stop with: runwork dev stop`));
593
+ console.log(dim(` Logs: tail -f .runwork/dev-stdout.log`));
594
+ console.log('');
595
+ }
596
+ return;
597
+ }
598
+ case 'wrong-pid': {
599
+ // Race: another process won the session-file write. Treat as
600
+ // "already running" -- the user's intent is satisfied. Our spawned
601
+ // child will detect the same file at its own startup probe and
602
+ // exit cleanly without doing duplicate work.
603
+ const f = outcome.file;
604
+ if (opts.json) {
605
+ jsonLine({
606
+ event: 'already_running',
607
+ previewUrl: f.previewUrl,
608
+ pid: f.pid,
609
+ sessionId: f.sessionId,
610
+ mode: f.mode,
611
+ timestamp: ts(),
612
+ });
613
+ }
614
+ else {
615
+ console.log(`Another dev session already running (PID ${f.pid}).`);
616
+ console.log(` Preview: ${green(f.previewUrl)}`);
617
+ }
618
+ return;
619
+ }
620
+ case 'child-exited': {
621
+ const message = `Detached dev session exited before becoming ready.`;
622
+ if (opts.json) {
623
+ jsonLine({
624
+ event: 'error',
625
+ phase: 'detach-child-exited',
626
+ timestamp: ts(),
627
+ error: {
628
+ message,
629
+ diagnosis: 'The detached child process exited (typically due to missing auth, missing git, network failure, or a sync conflict) before it could publish a preview URL.',
630
+ suggestions: [
631
+ 'Inspect the child stderr at .runwork/dev-stderr.log',
632
+ 'Run `runwork doctor` to verify auth and connectivity',
633
+ 'Try `runwork dev` (foreground) to see the failure inline',
634
+ ],
635
+ childLogTail: outcome.childLogTail,
636
+ },
637
+ });
638
+ }
639
+ else {
640
+ console.error(yellow(message));
641
+ console.error(dim(' Inspect .runwork/dev-stderr.log or run `runwork dev` to see what failed.'));
642
+ if (outcome.childLogTail) {
643
+ console.error(dim(' Tail of child stderr:'));
644
+ for (const line of outcome.childLogTail.split('\n').slice(-10)) {
645
+ if (line)
646
+ console.error(dim(` ${line}`));
647
+ }
648
+ }
649
+ }
650
+ process.exit(1);
651
+ return;
652
+ }
653
+ case 'timeout': {
654
+ const message = `Detached dev session did not become ready within 90s.`;
655
+ if (opts.json) {
656
+ jsonLine({
657
+ event: 'error',
658
+ phase: 'detach',
659
+ timestamp: ts(),
660
+ error: {
661
+ message,
662
+ diagnosis: 'The detached child process was spawned but never wrote a session file with a preview URL. The sandbox boot may have failed.',
663
+ suggestions: [
664
+ 'Inspect the child stderr at .runwork/dev-stderr.log',
665
+ 'Run `runwork doctor` to verify auth and connectivity',
666
+ 'Try `runwork dev` (foreground) to see the failure inline',
667
+ ],
668
+ childLogTail: outcome.childLogTail,
669
+ },
670
+ });
671
+ }
672
+ else {
673
+ console.error(yellow(message));
674
+ console.error(dim(' Inspect .runwork/dev-stderr.log or run `runwork dev` to see what failed.'));
675
+ if (outcome.childLogTail) {
676
+ console.error(dim(' Tail of child stderr:'));
677
+ for (const line of outcome.childLogTail.split('\n').slice(-10)) {
678
+ if (line)
679
+ console.error(dim(` ${line}`));
680
+ }
681
+ }
682
+ }
683
+ process.exit(1);
684
+ return;
685
+ }
686
+ case 'spawn-failed': {
687
+ const message = outcome.error instanceof Error ? outcome.error.message : String(outcome.error);
688
+ if (opts.json) {
689
+ jsonLine({
690
+ event: 'error',
691
+ phase: 'detach-spawn',
692
+ timestamp: ts(),
693
+ error: {
694
+ message: `Failed to spawn detached child: ${message}`,
695
+ diagnosis: 'The CLI could not fork itself into a background process.',
696
+ suggestions: ['Run `runwork dev` (foreground) instead'],
697
+ },
698
+ });
699
+ }
700
+ else {
701
+ console.error(yellow(`Failed to start detached dev session: ${message}`));
702
+ console.error(dim(' Run `runwork dev` (foreground) instead.'));
703
+ }
704
+ process.exit(1);
705
+ return;
706
+ }
707
+ }
708
+ }
709
+ /**
710
+ * `runwork dev stop` -- subcommand of `dev`. Tears down a running
711
+ * session by reading the local session file. Idempotent.
712
+ */
713
+ const devStopCommand = new Command('stop')
714
+ .description('Stop the dev session running for this app')
715
+ .action(async (_opts, command) => {
716
+ const useJson = shouldOutputJson(command.optsWithGlobals().json);
717
+ const config = readConfig();
718
+ const cwd = process.cwd();
719
+ const ts = () => new Date().toISOString();
720
+ const outcome = await stopSession(cwd, config.appId);
721
+ switch (outcome.result) {
722
+ case 'no-session':
723
+ if (useJson) {
724
+ jsonLine({ event: 'session_stopped', result: 'no-session', timestamp: ts() });
725
+ }
726
+ else {
727
+ console.log('No dev session running here.');
728
+ }
729
+ return;
730
+ case 'stale-cleaned':
731
+ if (useJson) {
732
+ jsonLine({
733
+ event: 'session_stopped',
734
+ result: 'stale-cleaned',
735
+ reason: outcome.reason,
736
+ pid: outcome.pid,
737
+ timestamp: ts(),
738
+ });
739
+ }
740
+ else {
741
+ console.log(`Cleaned up stale session file (reason: ${outcome.reason}).`);
742
+ }
743
+ return;
744
+ case 'stopped':
745
+ if (useJson) {
746
+ jsonLine({
747
+ event: 'session_stopped',
748
+ result: 'stopped',
749
+ pid: outcome.pid,
750
+ gracefully: outcome.gracefully,
751
+ timestamp: ts(),
752
+ });
753
+ }
754
+ else {
755
+ const how = outcome.gracefully ? 'gracefully' : 'forcefully';
756
+ console.log(`Stopped dev session ${how} (PID ${outcome.pid}).`);
757
+ }
758
+ return;
759
+ case 'kill-failed': {
760
+ const msg = outcome.error instanceof Error ? outcome.error.message : String(outcome.error);
761
+ if (useJson) {
762
+ jsonLine({
763
+ event: 'error',
764
+ phase: 'dev-stop',
765
+ timestamp: ts(),
766
+ error: {
767
+ message: `Failed to stop PID ${outcome.pid}: ${msg}`,
768
+ diagnosis: 'The session file was removed but the process could not be killed by this CLI invocation.',
769
+ suggestions: [
770
+ `Manually kill the process: kill ${outcome.pid}`,
771
+ 'Verify with: ps -p ' + outcome.pid,
772
+ ],
773
+ },
774
+ });
775
+ }
776
+ else {
777
+ console.error(yellow(`Could not kill PID ${outcome.pid}: ${msg}`));
778
+ console.error(dim(' The session file has been removed; the process may need to be killed manually.'));
779
+ }
780
+ process.exit(1);
781
+ return;
782
+ }
783
+ }
784
+ });
785
+ devCommand.addCommand(devStopCommand);
786
+ /**
787
+ * `runwork dev attach` -- read-only join on a running dev session.
788
+ *
789
+ * The keyboard glue here is intentionally a near-copy of the foreground
790
+ * dev path's switch (we considered factoring it out and decided the
791
+ * inverted cleanup semantics would force a config-heavy abstraction --
792
+ * see the conversation in `docs/plans/2026-05-06-runwork-dev-lifecycle-design.md`).
793
+ *
794
+ * The hard rule: nothing this command does, EXCEPT the explicit `s`
795
+ * keypress, ever stops the attached session. Ctrl+C and `q` exit the
796
+ * attach UI but leave the dev session running.
797
+ */
798
+ const devAttachCommand = new Command('attach')
799
+ .description('Attach to a running dev session for this app: tail logs, see the preview URL, control via keys')
800
+ .option('--initial-lines <n>', 'How many trailing log lines to replay on connect (default 50)', (v) => parseInt(v, 10), 50)
801
+ .action(async (options, command) => {
802
+ const useJson = shouldOutputJson(command.optsWithGlobals().json);
803
+ const config = readConfig();
804
+ const cwd = process.cwd();
805
+ const ts = () => new Date().toISOString();
806
+ const target = resolveAttachTarget(cwd, config.appId);
807
+ if (target.result === 'no-session') {
808
+ if (useJson) {
809
+ jsonLine({ event: 'attach_no_session', timestamp: ts() });
810
+ }
811
+ else {
812
+ console.log('No dev session running here.');
813
+ console.log(dim(' Start one with `runwork dev` or `runwork dev --detach`.'));
814
+ }
815
+ return;
816
+ }
817
+ if (target.result === 'stale-cleaned') {
818
+ if (useJson) {
819
+ jsonLine({ event: 'attach_stale_cleaned', reason: target.reason, timestamp: ts() });
820
+ }
821
+ else {
822
+ console.log(`Found a stale session file (reason: ${target.reason}); cleaned up.`);
823
+ console.log(dim(' Nothing to attach to. Start a new session with `runwork dev`.'));
824
+ }
825
+ return;
826
+ }
827
+ const file = target.file;
828
+ if (useJson) {
829
+ jsonLine({
830
+ event: 'attach_started',
831
+ pid: file.pid,
832
+ sessionId: file.sessionId,
833
+ previewUrl: file.previewUrl,
834
+ mode: file.mode,
835
+ startedAt: file.startedAt,
836
+ timestamp: ts(),
837
+ });
838
+ }
839
+ else {
840
+ console.log('');
841
+ console.log(`Attached to dev session ${dim(`(PID ${file.pid}, mode: ${file.mode}, ${formatStartedAgo(file.startedAt)})`)}`);
842
+ console.log(` Preview: ${green(file.previewUrl || '(starting up)')}`);
843
+ console.log(dim(` Logs: .runwork/dev-stdout.log, dev-stderr.log`));
844
+ console.log('');
845
+ console.log(dim(' o:open i:info s:stop q:detach (Ctrl+C also detaches; session keeps running)'));
846
+ console.log('');
847
+ }
848
+ const colors = { dim, green, yellow, red, cyan };
849
+ const paths = getAttachLogPaths(cwd);
850
+ let stopping = false;
851
+ // Status line: only in human + TTY mode. The same caveats apply as
852
+ // foreground dev: createStatusLine returns a no-op when stdout
853
+ // is not a TTY.
854
+ const statusLine = useJson ? null : createStatusLine(process.stdout);
855
+ let displayedUrl = file.previewUrl;
856
+ function updateStatus() {
857
+ if (!statusLine)
858
+ return;
859
+ const sep = '\x1b[90m│\x1b[39m';
860
+ statusLine.update(`${bold(config.appName)} ${sep} ${green(displayedUrl || '(starting up)')} ${sep} ${cyan('attached')} ${sep} ${dim(`PID ${file.pid}`)} ${sep} \x1b[90mo\x1b[39m:open \x1b[90mi\x1b[39m:info \x1b[90ms\x1b[39m:stop \x1b[90mq\x1b[39m:detach`);
861
+ }
862
+ if (statusLine)
863
+ updateStatus();
864
+ const tail = startLogTail(paths.stdout, paths.stderr, {
865
+ initialLines: options.initialLines ?? 50,
866
+ onLine: (line, source) => {
867
+ if (useJson) {
868
+ // Pass-through: agents consuming attach in JSON mode see the
869
+ // raw NDJSON log lines plus a wrapper noting the source.
870
+ jsonLine({ event: 'log', source, line, timestamp: ts() });
871
+ return;
872
+ }
873
+ const rendered = renderLogLine(line, source, colors);
874
+ console.log(rendered.text);
875
+ },
876
+ onTruncated: () => {
877
+ // The detached child reopens log files in 'w' mode at session
878
+ // start, but a restart of the SAME PID shouldn't happen --
879
+ // restart kills the old PID, spawns a new one. So a truncation
880
+ // we observe is most likely "another process restarted the
881
+ // session." We surface it and let the session-file watch decide
882
+ // whether to fully exit (which it will when it sees the PID
883
+ // change).
884
+ if (!useJson)
885
+ console.log(yellow(' (log file was truncated -- session may have restarted)'));
886
+ },
887
+ });
888
+ const sessionWatch = startSessionFileWatch(cwd, file, {
889
+ expectedAppId: config.appId,
890
+ onUrlChanged: (next, prev) => {
891
+ displayedUrl = next;
892
+ if (useJson) {
893
+ jsonLine({ event: 'preview_url_changed', previewUrl: next, previousUrl: prev, timestamp: ts() });
894
+ }
895
+ else {
896
+ console.log(dim(` Preview URL changed: ${next}`));
897
+ updateStatus();
898
+ }
899
+ },
900
+ onSessionGone: () => {
901
+ if (stopping)
902
+ return;
903
+ if (useJson) {
904
+ jsonLine({ event: 'attach_session_ended', pid: file.pid, timestamp: ts() });
905
+ }
906
+ else {
907
+ console.log('');
908
+ console.log(yellow('Session ended. Detaching.'));
909
+ }
910
+ cleanupAttach('session-ended');
911
+ },
912
+ });
913
+ const keyboard = useJson ? null : createKeyboardListener();
914
+ function cleanupAttach(reason) {
915
+ if (stopping)
916
+ return;
917
+ stopping = true;
918
+ tail.stop();
919
+ sessionWatch.stop();
920
+ statusLine?.destroy();
921
+ keyboard?.stop();
922
+ // We never call removeSessionFile here -- attach does not own the
923
+ // session. The only path that ends a session is `s` -> stopSession,
924
+ // which removes the file itself.
925
+ void reason;
926
+ process.exit(0);
927
+ }
928
+ process.on('SIGINT', () => cleanupAttach('user'));
929
+ process.on('SIGTERM', () => cleanupAttach('user'));
930
+ if (keyboard) {
931
+ keyboard.start(async (action) => {
932
+ switch (action) {
933
+ case 'o':
934
+ case 'p': {
935
+ const url = getCurrentPreviewUrl(cwd, displayedUrl);
936
+ if (url)
937
+ import('open').then((m) => m.default(url));
938
+ break;
939
+ }
940
+ case 'i':
941
+ console.log(getInfoPanel({
942
+ appName: config.appName,
943
+ previewUrl: getCurrentPreviewUrl(cwd, displayedUrl),
944
+ workspaceName: config.workspaceName,
945
+ directory: cwd,
946
+ }));
947
+ break;
948
+ case 's': {
949
+ console.log(dim('Stopping dev session...'));
950
+ const outcome = await stopSession(cwd, config.appId);
951
+ if (outcome.result === 'stopped') {
952
+ console.log(`Stopped dev session (PID ${outcome.pid}).`);
953
+ }
954
+ else if (outcome.result === 'kill-failed') {
955
+ console.error(yellow(`Could not kill PID ${outcome.pid}.`));
956
+ }
957
+ cleanupAttach('stop');
958
+ break;
959
+ }
960
+ case 'quit':
961
+ cleanupAttach('user');
962
+ break;
963
+ // 'a' / 'e' / 'r' are no-ops in attach -- log filtering is a
964
+ // foreground-dev-only feature. The keys are still parsed
965
+ // centrally so they don't surface as null actions.
966
+ case 'a':
967
+ case 'e':
968
+ case 'r':
969
+ case null:
970
+ break;
971
+ }
972
+ });
973
+ }
974
+ // Block until cleanup runs.
975
+ await new Promise(() => { });
364
976
  });
977
+ devCommand.addCommand(devAttachCommand);