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,5 @@
1
1
  import { Command } from 'commander';
2
+ import { type SessionMode, type SessionStaleReason } from '../dev/session.js';
2
3
  import type { WorkspaceAllData } from '../types.js';
3
4
  interface BlueprintEntity {
4
5
  entityName: string;
@@ -75,6 +76,30 @@ interface MergedFileStorage {
75
76
  enabled: boolean;
76
77
  sources: string[];
77
78
  }
79
+ /**
80
+ * Local dev-session view: what the on-disk session file (if any) says
81
+ * about a session managed by THIS machine. Independent of the server's
82
+ * preview status, which can disagree (e.g. the server reports the
83
+ * sandbox is up because someone else's session is running it).
84
+ */
85
+ interface LocalDevSession {
86
+ /** No session file present in this app dir. */
87
+ state: 'none';
88
+ }
89
+ interface LocalDevSessionAlive {
90
+ state: 'alive';
91
+ pid: number;
92
+ sessionId: string;
93
+ previewUrl: string;
94
+ mode: SessionMode;
95
+ startedAt: number;
96
+ }
97
+ interface LocalDevSessionStale {
98
+ state: 'stale';
99
+ reason: SessionStaleReason;
100
+ pid?: number;
101
+ }
102
+ type LocalDevState = LocalDevSession | LocalDevSessionAlive | LocalDevSessionStale;
78
103
  interface InfoOutput {
79
104
  app: {
80
105
  id: string;
@@ -89,6 +114,12 @@ interface InfoOutput {
89
114
  url: string | null;
90
115
  active: boolean;
91
116
  };
117
+ /**
118
+ * Local dev session state from `.runwork/dev-session.json`. May
119
+ * disagree with `preview` if the server reports a sandbox running but
120
+ * this machine is not the one driving it (or vice versa).
121
+ */
122
+ localDevSession: LocalDevState;
92
123
  production: {
93
124
  url: null;
94
125
  deployed: boolean;
@@ -9,6 +9,24 @@ import { VERSION } from '../generated/version.js';
9
9
  import { requireAuth } from '../auth/store.js';
10
10
  import { ApiClient } from '../api/client.js';
11
11
  import { resolveWorkspace } from '../workspace/resolve.js';
12
+ import { getSessionState } from '../dev/session.js';
13
+ function readLocalDevSession(appDir, appId) {
14
+ if (!appId)
15
+ return { state: 'none' };
16
+ const s = getSessionState(appDir, appId);
17
+ if (s.state === 'none')
18
+ return { state: 'none' };
19
+ if (s.state === 'stale')
20
+ return { state: 'stale', reason: s.reason, pid: s.file?.pid };
21
+ return {
22
+ state: 'alive',
23
+ pid: s.file.pid,
24
+ sessionId: s.file.sessionId,
25
+ previewUrl: s.file.previewUrl,
26
+ mode: s.file.mode,
27
+ startedAt: s.file.startedAt,
28
+ };
29
+ }
12
30
  function tryReadConfig() {
13
31
  if (!existsSync('.runwork.json'))
14
32
  return null;
@@ -222,6 +240,23 @@ function printHumanOutput(data) {
222
240
  console.log(` ${dim(pad('Preview:'))}${dim('(not running)')}`);
223
241
  }
224
242
  console.log(` ${dim(pad('Production:'))}${dim('(not available)')}`);
243
+ // Local dev session view: what's running on THIS machine, from the
244
+ // session file. This may disagree with the server's "preview"
245
+ // status above; that's diagnostic, not a bug.
246
+ const local = data.localDevSession;
247
+ if (local.state === 'alive') {
248
+ const startedSec = Math.round((Date.now() - local.startedAt) / 1000);
249
+ const ago = startedSec < 60 ? `${startedSec}s ago`
250
+ : startedSec < 3600 ? `${Math.floor(startedSec / 60)}m ago`
251
+ : `${Math.floor(startedSec / 3600)}h ago`;
252
+ console.log(` ${dim(pad('Dev session:'))}${green('running')} ${dim(`(PID ${local.pid}, ${local.mode}, started ${ago})`)}`);
253
+ }
254
+ else if (local.state === 'stale') {
255
+ console.log(` ${dim(pad('Dev session:'))}${yellow('stale')} ${dim(`(reason: ${local.reason}; run \`runwork dev stop\` to clean up)`)}`);
256
+ }
257
+ else {
258
+ console.log(` ${dim(pad('Dev session:'))}${dim('(none on this machine)')}`);
259
+ }
225
260
  }
226
261
  console.log('');
227
262
  // Integrations
@@ -374,6 +409,7 @@ export const infoCommand = new Command('info')
374
409
  process.stderr.write('Warning: failed to fetch workspace registries\n');
375
410
  }
376
411
  const registries = buildRegistries(blueprint, serverData, appId ?? '');
412
+ const localDevSession = readLocalDevSession(process.cwd(), appId);
377
413
  const output = {
378
414
  app: appId ? {
379
415
  id: appId,
@@ -385,6 +421,7 @@ export const infoCommand = new Command('info')
385
421
  name: workspaceName,
386
422
  },
387
423
  preview,
424
+ localDevSession,
388
425
  production: { url: null, deployed: false },
389
426
  integrations,
390
427
  registries,
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,296 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
+ import * as fs from 'fs';
3
+ import * as os from 'os';
4
+ import * as path from 'path';
5
+ import { formatStartedAgo, getAttachLogPaths, getCurrentPreviewUrl, renderLogLine, resolveAttachTarget, startLogTail, startSessionFileWatch, } from '../attach.js';
6
+ import { buildSessionFile, getSessionPaths, writeSessionFile, } from '../session.js';
7
+ function tmpAppDir() {
8
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'runwork-attach-test-'));
9
+ }
10
+ function makeSessionFile(overrides = {}) {
11
+ return buildSessionFile({
12
+ pid: process.pid,
13
+ sessionId: 'sess_test',
14
+ appId: 'test-app',
15
+ previewUrl: 'https://x.example',
16
+ cliVersion: '0.10.2',
17
+ mode: 'detached',
18
+ deps: { bootTime: () => Date.now() - os.uptime() * 1000 },
19
+ ...overrides,
20
+ });
21
+ }
22
+ describe('renderLogLine()', () => {
23
+ it('passes plain non-JSON stdout text through verbatim', () => {
24
+ expect(renderLogLine('hello world', 'stdout').text).toBe('hello world');
25
+ expect(renderLogLine('hello world', 'stdout').level).toBe('info');
26
+ });
27
+ it('marks plain stderr text as error level', () => {
28
+ const out = renderLogLine('boom', 'stderr');
29
+ expect(out.text).toBe('boom'); // identity colors
30
+ expect(out.level).toBe('error');
31
+ });
32
+ it('renders session_started with the URL', () => {
33
+ const json = JSON.stringify({ event: 'session_started', previewUrl: 'https://x.example' });
34
+ expect(renderLogLine(json, 'stdout').text).toContain('Dev session started');
35
+ expect(renderLogLine(json, 'stdout').text).toContain('https://x.example');
36
+ });
37
+ it('renders preview_url_changed with prev and next', () => {
38
+ const json = JSON.stringify({
39
+ event: 'preview_url_changed',
40
+ previewUrl: 'https://new',
41
+ previousUrl: 'https://old',
42
+ });
43
+ const r = renderLogLine(json, 'stdout');
44
+ expect(r.text).toContain('Preview URL changed');
45
+ expect(r.text).toContain('https://old');
46
+ expect(r.text).toContain('https://new');
47
+ expect(r.level).toBe('warn');
48
+ });
49
+ it('renders files_synced with a count + target', () => {
50
+ const json = JSON.stringify({ event: 'files_synced', count: 3, target: 'preview' });
51
+ expect(renderLogLine(json, 'stdout').text).toContain('Synced 3 file(s)');
52
+ expect(renderLogLine(json, 'stdout').text).toContain('preview');
53
+ });
54
+ it('renders error with phase + message + diagnosis', () => {
55
+ const json = JSON.stringify({
56
+ event: 'error',
57
+ phase: 'sync',
58
+ error: { message: 'merge conflict', diagnosis: 'rebase failed' },
59
+ });
60
+ const r = renderLogLine(json, 'stderr');
61
+ expect(r.text).toContain('ERROR (sync)');
62
+ expect(r.text).toContain('merge conflict');
63
+ expect(r.text).toContain('rebase failed');
64
+ expect(r.level).toBe('error');
65
+ });
66
+ it('falls through to compact JSON for unknown event types', () => {
67
+ const json = JSON.stringify({ event: 'something_new', foo: 'bar' });
68
+ const r = renderLogLine(json, 'stdout');
69
+ expect(r.text).toContain('something_new');
70
+ expect(r.text).toContain('bar');
71
+ });
72
+ it('does not crash on malformed JSON object lines', () => {
73
+ expect(() => renderLogLine('{', 'stdout')).not.toThrow();
74
+ expect(renderLogLine('{', 'stdout').text).toBe('{');
75
+ });
76
+ it('returns the empty line through unchanged', () => {
77
+ const r = renderLogLine('', 'stdout');
78
+ expect(r.text).toBe('');
79
+ });
80
+ });
81
+ describe('startLogTail()', () => {
82
+ let appDir;
83
+ beforeEach(() => {
84
+ appDir = tmpAppDir();
85
+ fs.mkdirSync(path.join(appDir, '.runwork'), { recursive: true });
86
+ });
87
+ afterEach(() => {
88
+ if (fs.existsSync(appDir)) {
89
+ fs.rmSync(appDir, { recursive: true, force: true });
90
+ }
91
+ });
92
+ it('replays the last N lines from existing logs on start', async () => {
93
+ const { stdout: stdoutPath } = getAttachLogPaths(appDir);
94
+ const lines = Array.from({ length: 20 }, (_, i) => `line${i}`).join('\n') + '\n';
95
+ fs.writeFileSync(stdoutPath, lines, 'utf-8');
96
+ const seen = [];
97
+ const tail = startLogTail(stdoutPath, getAttachLogPaths(appDir).stderr, {
98
+ initialLines: 5,
99
+ intervalMs: 50,
100
+ onLine: (line, source) => { seen.push({ line, source }); },
101
+ });
102
+ expect(seen).toHaveLength(5);
103
+ expect(seen.map((s) => s.line)).toEqual(['line15', 'line16', 'line17', 'line18', 'line19']);
104
+ expect(seen.every((s) => s.source === 'stdout')).toBe(true);
105
+ tail.stop();
106
+ });
107
+ it('picks up appended lines on subsequent ticks', async () => {
108
+ const { stdout: stdoutPath, stderr: stderrPath } = getAttachLogPaths(appDir);
109
+ fs.writeFileSync(stdoutPath, '', 'utf-8');
110
+ const seen = [];
111
+ const tail = startLogTail(stdoutPath, stderrPath, {
112
+ initialLines: 50,
113
+ intervalMs: 25,
114
+ onLine: (line) => { seen.push(line); },
115
+ });
116
+ fs.appendFileSync(stdoutPath, 'first\n', 'utf-8');
117
+ await new Promise((r) => setTimeout(r, 100));
118
+ expect(seen).toContain('first');
119
+ fs.appendFileSync(stdoutPath, 'second\nthird\n', 'utf-8');
120
+ await new Promise((r) => setTimeout(r, 100));
121
+ expect(seen).toContain('second');
122
+ expect(seen).toContain('third');
123
+ tail.stop();
124
+ });
125
+ it('fires onTruncated when the file is shrunk (e.g., new dev session opened it)', async () => {
126
+ const { stdout: stdoutPath, stderr: stderrPath } = getAttachLogPaths(appDir);
127
+ fs.writeFileSync(stdoutPath, 'one\ntwo\nthree\n', 'utf-8');
128
+ const onTruncated = vi.fn();
129
+ const tail = startLogTail(stdoutPath, stderrPath, {
130
+ initialLines: 50,
131
+ intervalMs: 25,
132
+ onLine: () => { },
133
+ onTruncated,
134
+ });
135
+ // Truncate the file.
136
+ fs.writeFileSync(stdoutPath, '', 'utf-8');
137
+ await new Promise((r) => setTimeout(r, 100));
138
+ expect(onTruncated).toHaveBeenCalled();
139
+ tail.stop();
140
+ });
141
+ it('handles missing stdout/stderr paths without throwing', () => {
142
+ expect(() => {
143
+ const tail = startLogTail(path.join(appDir, '.runwork', 'does-not-exist-stdout.log'), path.join(appDir, '.runwork', 'does-not-exist-stderr.log'), {
144
+ initialLines: 50,
145
+ intervalMs: 25,
146
+ onLine: () => { },
147
+ });
148
+ tail.stop();
149
+ }).not.toThrow();
150
+ });
151
+ it('stop() prevents further reads', async () => {
152
+ const { stdout: stdoutPath, stderr: stderrPath } = getAttachLogPaths(appDir);
153
+ fs.writeFileSync(stdoutPath, '', 'utf-8');
154
+ const seen = [];
155
+ const tail = startLogTail(stdoutPath, stderrPath, {
156
+ initialLines: 50,
157
+ intervalMs: 25,
158
+ onLine: (line) => { seen.push(line); },
159
+ });
160
+ tail.stop();
161
+ fs.appendFileSync(stdoutPath, 'after-stop\n', 'utf-8');
162
+ await new Promise((r) => setTimeout(r, 100));
163
+ expect(seen).not.toContain('after-stop');
164
+ });
165
+ });
166
+ describe('startSessionFileWatch()', () => {
167
+ let appDir;
168
+ beforeEach(() => {
169
+ appDir = tmpAppDir();
170
+ });
171
+ afterEach(() => {
172
+ if (fs.existsSync(appDir)) {
173
+ fs.rmSync(appDir, { recursive: true, force: true });
174
+ }
175
+ });
176
+ it('fires onUrlChanged when previewUrl rotates', async () => {
177
+ const initial = makeSessionFile({ previewUrl: 'https://old.example' });
178
+ writeSessionFile(appDir, initial);
179
+ const onUrlChanged = vi.fn();
180
+ const watch = startSessionFileWatch(appDir, initial, {
181
+ expectedAppId: 'test-app',
182
+ intervalMs: 25,
183
+ onUrlChanged,
184
+ });
185
+ // Mutate the file in place to simulate the URL poller updating it.
186
+ const updated = { ...initial, previewUrl: 'https://new.example' };
187
+ writeSessionFile(appDir, updated);
188
+ await new Promise((r) => setTimeout(r, 100));
189
+ expect(onUrlChanged).toHaveBeenCalledWith('https://new.example', 'https://old.example');
190
+ watch.stop();
191
+ });
192
+ it('fires onSessionGone when the file is removed', async () => {
193
+ const initial = makeSessionFile();
194
+ writeSessionFile(appDir, initial);
195
+ const onSessionGone = vi.fn();
196
+ const watch = startSessionFileWatch(appDir, initial, {
197
+ expectedAppId: 'test-app',
198
+ intervalMs: 25,
199
+ onSessionGone,
200
+ });
201
+ fs.rmSync(getSessionPaths(appDir).file);
202
+ await new Promise((r) => setTimeout(r, 100));
203
+ expect(onSessionGone).toHaveBeenCalled();
204
+ watch.stop();
205
+ });
206
+ it('fires onSessionGone when the PID changes (different session took over)', async () => {
207
+ const initial = makeSessionFile({ pid: 11111 });
208
+ writeSessionFile(appDir, initial);
209
+ const onSessionGone = vi.fn();
210
+ const onUrlChanged = vi.fn();
211
+ const watch = startSessionFileWatch(appDir, initial, {
212
+ expectedAppId: 'test-app',
213
+ intervalMs: 25,
214
+ onSessionGone,
215
+ onUrlChanged,
216
+ });
217
+ // A different process wrote a new file (e.g., user did `dev --restart`).
218
+ writeSessionFile(appDir, makeSessionFile({ pid: 22222 }));
219
+ await new Promise((r) => setTimeout(r, 100));
220
+ expect(onSessionGone).toHaveBeenCalled();
221
+ expect(onUrlChanged).not.toHaveBeenCalled();
222
+ watch.stop();
223
+ });
224
+ });
225
+ describe('formatStartedAgo()', () => {
226
+ const now = 1_700_000_000_000;
227
+ it('formats sub-minute durations in seconds', () => {
228
+ expect(formatStartedAgo(now - 5_000, now)).toBe('5s ago');
229
+ expect(formatStartedAgo(now - 59_000, now)).toBe('59s ago');
230
+ });
231
+ it('formats sub-hour durations in minutes', () => {
232
+ expect(formatStartedAgo(now - 60_000, now)).toBe('1m ago');
233
+ expect(formatStartedAgo(now - 30 * 60_000, now)).toBe('30m ago');
234
+ });
235
+ it('formats longer durations in hours', () => {
236
+ expect(formatStartedAgo(now - 60 * 60_000, now)).toBe('1h ago');
237
+ expect(formatStartedAgo(now - 5 * 60 * 60_000, now)).toBe('5h ago');
238
+ });
239
+ it('clamps negative deltas to 0', () => {
240
+ expect(formatStartedAgo(now + 10_000, now)).toBe('0s ago');
241
+ });
242
+ });
243
+ describe('resolveAttachTarget()', () => {
244
+ let appDir;
245
+ beforeEach(() => {
246
+ appDir = tmpAppDir();
247
+ });
248
+ afterEach(() => {
249
+ if (fs.existsSync(appDir)) {
250
+ fs.rmSync(appDir, { recursive: true, force: true });
251
+ }
252
+ });
253
+ it('returns "no-session" when no file exists', () => {
254
+ expect(resolveAttachTarget(appDir, 'test-app')).toEqual({ result: 'no-session' });
255
+ });
256
+ it('returns "stale-cleaned" and removes the file when state is stale', () => {
257
+ // Pid that almost certainly is not running; bootTime check will pass
258
+ // because process is alive in current test boot, but pid liveness
259
+ // will fail.
260
+ writeSessionFile(appDir, makeSessionFile({ pid: 2_147_483_640 }));
261
+ const out = resolveAttachTarget(appDir, 'test-app');
262
+ expect(out.result).toBe('stale-cleaned');
263
+ expect(fs.existsSync(getSessionPaths(appDir).file)).toBe(false);
264
+ });
265
+ it('returns "attached" with the file when state is alive', () => {
266
+ const file = makeSessionFile({ pid: process.pid });
267
+ writeSessionFile(appDir, file);
268
+ const out = resolveAttachTarget(appDir, 'test-app');
269
+ expect(out.result).toBe('attached');
270
+ if (out.result === 'attached') {
271
+ expect(out.file.pid).toBe(process.pid);
272
+ }
273
+ });
274
+ });
275
+ describe('getCurrentPreviewUrl()', () => {
276
+ let appDir;
277
+ beforeEach(() => {
278
+ appDir = tmpAppDir();
279
+ });
280
+ afterEach(() => {
281
+ if (fs.existsSync(appDir)) {
282
+ fs.rmSync(appDir, { recursive: true, force: true });
283
+ }
284
+ });
285
+ it('returns the file URL when one exists', () => {
286
+ writeSessionFile(appDir, makeSessionFile({ previewUrl: 'https://current' }));
287
+ expect(getCurrentPreviewUrl(appDir, 'https://fallback')).toBe('https://current');
288
+ });
289
+ it('returns the fallback when no file exists', () => {
290
+ expect(getCurrentPreviewUrl(appDir, 'https://fallback')).toBe('https://fallback');
291
+ });
292
+ it('returns the fallback when file URL is empty', () => {
293
+ writeSessionFile(appDir, makeSessionFile({ previewUrl: '' }));
294
+ expect(getCurrentPreviewUrl(appDir, 'https://fallback')).toBe('https://fallback');
295
+ });
296
+ });
@@ -0,0 +1 @@
1
+ export {};