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.
- package/dist/commands/dev.d.ts +3 -0
- package/dist/commands/dev.js +621 -8
- package/dist/commands/info.d.ts +31 -0
- package/dist/commands/info.js +37 -0
- package/dist/dev/__tests__/attach.test.d.ts +1 -0
- package/dist/dev/__tests__/attach.test.js +296 -0
- package/dist/dev/__tests__/detach.test.d.ts +1 -0
- package/dist/dev/__tests__/detach.test.js +328 -0
- package/dist/dev/__tests__/preview-url-poller.test.d.ts +1 -0
- package/dist/dev/__tests__/preview-url-poller.test.js +149 -0
- package/dist/dev/__tests__/session.test.d.ts +1 -0
- package/dist/dev/__tests__/session.test.js +347 -0
- package/dist/dev/__tests__/stop.test.d.ts +1 -0
- package/dist/dev/__tests__/stop.test.js +172 -0
- package/dist/dev/attach.d.ts +120 -0
- package/dist/dev/attach.js +269 -0
- package/dist/dev/detach.d.ts +164 -0
- package/dist/dev/detach.js +247 -0
- package/dist/dev/preview-url-poller.d.ts +35 -0
- package/dist/dev/preview-url-poller.js +50 -0
- package/dist/dev/session.d.ts +158 -0
- package/dist/dev/session.js +252 -0
- package/dist/dev/stop.d.ts +52 -0
- package/dist/dev/stop.js +101 -0
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/ui/__tests__/keyboard.test.js +4 -0
- package/dist/ui/keyboard.d.ts +1 -1
- package/dist/ui/keyboard.js +4 -0
- package/package.json +1 -1
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ApiClient } from '../api/client.js';
|
|
2
|
+
export interface PreviewUrlPollerOptions {
|
|
3
|
+
client: ApiClient;
|
|
4
|
+
appId: string;
|
|
5
|
+
initialUrl: string;
|
|
6
|
+
/**
|
|
7
|
+
* Polling interval in ms. Defaults to 15s -- low enough to catch a
|
|
8
|
+
* sandbox URL rotation within one keypress's worth of attention, high
|
|
9
|
+
* enough that an idle dev session isn't generating noticeable API load.
|
|
10
|
+
*/
|
|
11
|
+
intervalMs?: number;
|
|
12
|
+
onChange: (next: string, prev: string) => void;
|
|
13
|
+
onError?: (err: unknown) => void;
|
|
14
|
+
}
|
|
15
|
+
export interface PreviewUrlPoller {
|
|
16
|
+
getCurrent(): string;
|
|
17
|
+
stop(): void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Periodically refreshes the preview URL from `GET /api/dev/status` so the
|
|
21
|
+
* `runwork dev` UI stays in agreement with `runwork info` even when the
|
|
22
|
+
* sandbox tunnel rotates mid-session.
|
|
23
|
+
*
|
|
24
|
+
* Two intentional behaviours:
|
|
25
|
+
*
|
|
26
|
+
* 1. Empty server responses are NOT propagated. The DO clears its
|
|
27
|
+
* preview-URL cache to "" while a sandbox is being replaced; flipping
|
|
28
|
+
* the status line to empty and back would just be flicker. We keep
|
|
29
|
+
* the last known good URL until the server reports a real new one.
|
|
30
|
+
*
|
|
31
|
+
* 2. Overlapping ticks are skipped. If a fetch takes longer than the
|
|
32
|
+
* interval (slow network, sandbox spin-up), we don't pile up requests
|
|
33
|
+
* -- the next tick simply no-ops until the in-flight one resolves.
|
|
34
|
+
*/
|
|
35
|
+
export declare function startPreviewUrlPoller(opts: PreviewUrlPollerOptions): PreviewUrlPoller;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Periodically refreshes the preview URL from `GET /api/dev/status` so the
|
|
3
|
+
* `runwork dev` UI stays in agreement with `runwork info` even when the
|
|
4
|
+
* sandbox tunnel rotates mid-session.
|
|
5
|
+
*
|
|
6
|
+
* Two intentional behaviours:
|
|
7
|
+
*
|
|
8
|
+
* 1. Empty server responses are NOT propagated. The DO clears its
|
|
9
|
+
* preview-URL cache to "" while a sandbox is being replaced; flipping
|
|
10
|
+
* the status line to empty and back would just be flicker. We keep
|
|
11
|
+
* the last known good URL until the server reports a real new one.
|
|
12
|
+
*
|
|
13
|
+
* 2. Overlapping ticks are skipped. If a fetch takes longer than the
|
|
14
|
+
* interval (slow network, sandbox spin-up), we don't pile up requests
|
|
15
|
+
* -- the next tick simply no-ops until the in-flight one resolves.
|
|
16
|
+
*/
|
|
17
|
+
export function startPreviewUrlPoller(opts) {
|
|
18
|
+
let current = opts.initialUrl;
|
|
19
|
+
const interval = opts.intervalMs ?? 15000;
|
|
20
|
+
let stopped = false;
|
|
21
|
+
let inFlight = false;
|
|
22
|
+
const tick = async () => {
|
|
23
|
+
if (stopped || inFlight)
|
|
24
|
+
return;
|
|
25
|
+
inFlight = true;
|
|
26
|
+
try {
|
|
27
|
+
const status = await opts.client.getDevStatus(opts.appId);
|
|
28
|
+
const next = status.previewUrl ?? '';
|
|
29
|
+
if (next && next !== current) {
|
|
30
|
+
const prev = current;
|
|
31
|
+
current = next;
|
|
32
|
+
opts.onChange(next, prev);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
opts.onError?.(err);
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
inFlight = false;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const handle = setInterval(() => { void tick(); }, interval);
|
|
43
|
+
return {
|
|
44
|
+
getCurrent: () => current,
|
|
45
|
+
stop: () => {
|
|
46
|
+
stopped = true;
|
|
47
|
+
clearInterval(handle);
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-app `runwork dev` session lifecycle primitives.
|
|
3
|
+
*
|
|
4
|
+
* The session file at `<app-dir>/.runwork/dev-session.json` is the durable
|
|
5
|
+
* truth about whether a dev session is running for the current app, on the
|
|
6
|
+
* current machine. Every dev-related command reads from it, writes to it,
|
|
7
|
+
* or treats it as the IPC channel during detach.
|
|
8
|
+
*
|
|
9
|
+
* This module is intentionally pure: it does not start, stop, or signal
|
|
10
|
+
* processes. It only reads/writes the file and reports whether what it
|
|
11
|
+
* finds is alive, stale, or absent. Callers (dev.ts, dev stop, etc.) act
|
|
12
|
+
* on that information.
|
|
13
|
+
*
|
|
14
|
+
* See `docs/plans/2026-05-06-runwork-dev-lifecycle-design.md` for the full
|
|
15
|
+
* lifecycle contract.
|
|
16
|
+
*/
|
|
17
|
+
export declare const SESSION_FILE_SCHEMA_VERSION = 1;
|
|
18
|
+
/**
|
|
19
|
+
* Tolerance (ms) when comparing the stored bootTime to the currently
|
|
20
|
+
* computed one. NTP corrections can shift `Date.now()` by a few seconds
|
|
21
|
+
* relative to `os.uptime()`. A reboot is always orders of magnitude
|
|
22
|
+
* larger than this tolerance.
|
|
23
|
+
*/
|
|
24
|
+
export declare const BOOT_TIME_TOLERANCE_MS = 60000;
|
|
25
|
+
export type SessionMode = 'foreground' | 'detached';
|
|
26
|
+
export interface SessionFile {
|
|
27
|
+
version: number;
|
|
28
|
+
pid: number;
|
|
29
|
+
sessionId: string;
|
|
30
|
+
appId: string;
|
|
31
|
+
previewUrl: string;
|
|
32
|
+
startedAt: number;
|
|
33
|
+
bootTime: number;
|
|
34
|
+
cliVersion: string;
|
|
35
|
+
mode: SessionMode;
|
|
36
|
+
}
|
|
37
|
+
export type SessionStaleReason = 'malformed' | 'version-mismatch' | 'app-id-mismatch' | 'boot-time-mismatch' | 'pid-dead';
|
|
38
|
+
export type SessionState = {
|
|
39
|
+
state: 'none';
|
|
40
|
+
} | {
|
|
41
|
+
state: 'alive';
|
|
42
|
+
file: SessionFile;
|
|
43
|
+
} | {
|
|
44
|
+
state: 'stale';
|
|
45
|
+
reason: SessionStaleReason;
|
|
46
|
+
file?: SessionFile;
|
|
47
|
+
};
|
|
48
|
+
export interface SessionPaths {
|
|
49
|
+
/** `<app-dir>/.runwork` */
|
|
50
|
+
dir: string;
|
|
51
|
+
/** `<app-dir>/.runwork/dev-session.json` */
|
|
52
|
+
file: string;
|
|
53
|
+
/** `<app-dir>/.runwork/dev-session.json.tmp` -- staging path for atomic writes */
|
|
54
|
+
tmpFile: string;
|
|
55
|
+
/** `<app-dir>/.runwork/dev-stdout.log` -- detached child's stdout sink */
|
|
56
|
+
stdoutLog: string;
|
|
57
|
+
/** `<app-dir>/.runwork/dev-stderr.log` -- detached child's stderr sink */
|
|
58
|
+
stderrLog: string;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Inject-able dependencies for testing. The defaults call into real OS
|
|
62
|
+
* primitives. Tests pass overrides to simulate dead PIDs, reboots, or
|
|
63
|
+
* arbitrary clocks without monkey-patching `process` or `os`.
|
|
64
|
+
*/
|
|
65
|
+
export interface SessionDeps {
|
|
66
|
+
bootTime?: () => number;
|
|
67
|
+
pidAlive?: (pid: number) => boolean;
|
|
68
|
+
}
|
|
69
|
+
export declare function getSessionPaths(appDir: string): SessionPaths;
|
|
70
|
+
/**
|
|
71
|
+
* System boot timestamp in ms. Computed purely from Node's `os.uptime()`
|
|
72
|
+
* (monotonic seconds since boot, available on every platform Node runs
|
|
73
|
+
* on) and the wall clock. No spawning, no native modules.
|
|
74
|
+
*
|
|
75
|
+
* Drift between `Date.now()` and `os.uptime()` from NTP corrections is
|
|
76
|
+
* absorbed by `BOOT_TIME_TOLERANCE_MS` at the comparison site.
|
|
77
|
+
*/
|
|
78
|
+
export declare function currentBootTime(): number;
|
|
79
|
+
export declare function isBootTimeStale(stored: number, deps?: SessionDeps): boolean;
|
|
80
|
+
/**
|
|
81
|
+
* Cross-platform PID liveness probe.
|
|
82
|
+
*
|
|
83
|
+
* - Unix: `process.kill(pid, 0)` is signal-zero, a permissions+existence
|
|
84
|
+
* probe. ESRCH for dead, EPERM for "alive but not ours."
|
|
85
|
+
* - Windows: Node maps signal 0 to `OpenProcess(PROCESS_QUERY_LIMITED_-`
|
|
86
|
+
* `INFORMATION)`. Returns success iff the PID exists and the caller
|
|
87
|
+
* has rights, throws otherwise.
|
|
88
|
+
*
|
|
89
|
+
* On any error we return `false`. EPERM in particular ("alive but
|
|
90
|
+
* unprivileged") means the PID belongs to someone else now, so it's not
|
|
91
|
+
* our session even if it's a real process. The bootTime guard catches the
|
|
92
|
+
* rare "PID got reused after a reboot, we still own it" case.
|
|
93
|
+
*/
|
|
94
|
+
export declare function isPidAlive(pid: number): boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Read and parse the session file. Returns `null` for a missing file or
|
|
97
|
+
* any IO/parse error. The caller decides what "missing" vs "malformed"
|
|
98
|
+
* means -- use `getSessionState()` for that distinction.
|
|
99
|
+
*/
|
|
100
|
+
export declare function readSessionFile(appDir: string): SessionFile | null;
|
|
101
|
+
/**
|
|
102
|
+
* Write the session file atomically. Writes to `<file>.tmp` first then
|
|
103
|
+
* renames into place. POSIX `rename()` and Windows `MoveFileEx` are both
|
|
104
|
+
* atomic on the same volume, which a sibling temp file always is.
|
|
105
|
+
*
|
|
106
|
+
* Creates `.runwork/` if it doesn't exist. The directory is gitignored at
|
|
107
|
+
* the project-template level.
|
|
108
|
+
*/
|
|
109
|
+
export declare function writeSessionFile(appDir: string, data: SessionFile): void;
|
|
110
|
+
/**
|
|
111
|
+
* Conditional removal: only deletes the session file when its `pid`
|
|
112
|
+
* field matches the caller's. Use this from per-process cleanup paths
|
|
113
|
+
* where another process (e.g., the winner of a startup race) may have
|
|
114
|
+
* overwritten the file with a different owner. Returns `true` when we
|
|
115
|
+
* actually removed it.
|
|
116
|
+
*
|
|
117
|
+
* `removeSessionFile` is the unconditional primitive; this is the
|
|
118
|
+
* "be-a-good-citizen" wrapper for in-process cleanup handlers.
|
|
119
|
+
*/
|
|
120
|
+
export declare function removeSessionFileIfOwned(appDir: string, pid: number): boolean;
|
|
121
|
+
/**
|
|
122
|
+
* Idempotent removal. Missing file is not an error. We also clear any
|
|
123
|
+
* leftover temp file from a crashed mid-write -- those aren't load-bearing
|
|
124
|
+
* but they're noise and they confuse `ls -la .runwork/`.
|
|
125
|
+
*/
|
|
126
|
+
export declare function removeSessionFile(appDir: string): void;
|
|
127
|
+
/**
|
|
128
|
+
* Determine the live state of the session file in the given app directory.
|
|
129
|
+
*
|
|
130
|
+
* Checks are ordered cheap-to-expensive. The `pidAlive` syscall is last
|
|
131
|
+
* so a malformed or wrong-version file short-circuits before we touch
|
|
132
|
+
* the OS at all.
|
|
133
|
+
*
|
|
134
|
+
* 1. File missing -> `none`
|
|
135
|
+
* 2. File malformed / truncated -> `stale: malformed`
|
|
136
|
+
* 3. Schema version mismatch -> `stale: version-mismatch`
|
|
137
|
+
* 4. App ID mismatch -> `stale: app-id-mismatch`
|
|
138
|
+
* 5. Boot time outside tolerance -> `stale: boot-time-mismatch`
|
|
139
|
+
* 6. PID not alive -> `stale: pid-dead`
|
|
140
|
+
* 7. Otherwise -> `alive`
|
|
141
|
+
*/
|
|
142
|
+
export declare function getSessionState(appDir: string, expectedAppId: string, deps?: SessionDeps): SessionState;
|
|
143
|
+
/**
|
|
144
|
+
* Convenience constructor for a fresh session file. Fills in version,
|
|
145
|
+
* startedAt, and bootTime from the runtime; everything else is supplied
|
|
146
|
+
* by the caller. Test code can pass a `deps.bootTime` override to inject
|
|
147
|
+
* a deterministic value.
|
|
148
|
+
*/
|
|
149
|
+
export declare function buildSessionFile(input: {
|
|
150
|
+
pid: number;
|
|
151
|
+
sessionId: string;
|
|
152
|
+
appId: string;
|
|
153
|
+
previewUrl: string;
|
|
154
|
+
cliVersion: string;
|
|
155
|
+
mode: SessionMode;
|
|
156
|
+
startedAt?: number;
|
|
157
|
+
deps?: SessionDeps;
|
|
158
|
+
}): SessionFile;
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-app `runwork dev` session lifecycle primitives.
|
|
3
|
+
*
|
|
4
|
+
* The session file at `<app-dir>/.runwork/dev-session.json` is the durable
|
|
5
|
+
* truth about whether a dev session is running for the current app, on the
|
|
6
|
+
* current machine. Every dev-related command reads from it, writes to it,
|
|
7
|
+
* or treats it as the IPC channel during detach.
|
|
8
|
+
*
|
|
9
|
+
* This module is intentionally pure: it does not start, stop, or signal
|
|
10
|
+
* processes. It only reads/writes the file and reports whether what it
|
|
11
|
+
* finds is alive, stale, or absent. Callers (dev.ts, dev stop, etc.) act
|
|
12
|
+
* on that information.
|
|
13
|
+
*
|
|
14
|
+
* See `docs/plans/2026-05-06-runwork-dev-lifecycle-design.md` for the full
|
|
15
|
+
* lifecycle contract.
|
|
16
|
+
*/
|
|
17
|
+
import * as fs from 'fs';
|
|
18
|
+
import * as os from 'os';
|
|
19
|
+
import * as path from 'path';
|
|
20
|
+
export const SESSION_FILE_SCHEMA_VERSION = 1;
|
|
21
|
+
/**
|
|
22
|
+
* Tolerance (ms) when comparing the stored bootTime to the currently
|
|
23
|
+
* computed one. NTP corrections can shift `Date.now()` by a few seconds
|
|
24
|
+
* relative to `os.uptime()`. A reboot is always orders of magnitude
|
|
25
|
+
* larger than this tolerance.
|
|
26
|
+
*/
|
|
27
|
+
export const BOOT_TIME_TOLERANCE_MS = 60_000;
|
|
28
|
+
const realDeps = {
|
|
29
|
+
bootTime: currentBootTime,
|
|
30
|
+
pidAlive: isPidAlive,
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Resolve a `SessionDeps` against the real defaults, ignoring any
|
|
34
|
+
* `undefined` values in the caller-supplied object. Spreading
|
|
35
|
+
* `{ ...realDeps, ...deps }` directly would let `{ bootTime: undefined }`
|
|
36
|
+
* overwrite the real default with `undefined`, which then crashes when we
|
|
37
|
+
* try to call it. This helper keeps the defaults intact.
|
|
38
|
+
*/
|
|
39
|
+
function resolveDeps(deps) {
|
|
40
|
+
if (!deps)
|
|
41
|
+
return realDeps;
|
|
42
|
+
return {
|
|
43
|
+
bootTime: deps.bootTime ?? realDeps.bootTime,
|
|
44
|
+
pidAlive: deps.pidAlive ?? realDeps.pidAlive,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export function getSessionPaths(appDir) {
|
|
48
|
+
const dir = path.join(appDir, '.runwork');
|
|
49
|
+
return {
|
|
50
|
+
dir,
|
|
51
|
+
file: path.join(dir, 'dev-session.json'),
|
|
52
|
+
tmpFile: path.join(dir, 'dev-session.json.tmp'),
|
|
53
|
+
stdoutLog: path.join(dir, 'dev-stdout.log'),
|
|
54
|
+
stderrLog: path.join(dir, 'dev-stderr.log'),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* System boot timestamp in ms. Computed purely from Node's `os.uptime()`
|
|
59
|
+
* (monotonic seconds since boot, available on every platform Node runs
|
|
60
|
+
* on) and the wall clock. No spawning, no native modules.
|
|
61
|
+
*
|
|
62
|
+
* Drift between `Date.now()` and `os.uptime()` from NTP corrections is
|
|
63
|
+
* absorbed by `BOOT_TIME_TOLERANCE_MS` at the comparison site.
|
|
64
|
+
*/
|
|
65
|
+
export function currentBootTime() {
|
|
66
|
+
return Date.now() - os.uptime() * 1000;
|
|
67
|
+
}
|
|
68
|
+
export function isBootTimeStale(stored, deps = {}) {
|
|
69
|
+
const d = resolveDeps(deps);
|
|
70
|
+
return Math.abs(d.bootTime() - stored) > BOOT_TIME_TOLERANCE_MS;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Cross-platform PID liveness probe.
|
|
74
|
+
*
|
|
75
|
+
* - Unix: `process.kill(pid, 0)` is signal-zero, a permissions+existence
|
|
76
|
+
* probe. ESRCH for dead, EPERM for "alive but not ours."
|
|
77
|
+
* - Windows: Node maps signal 0 to `OpenProcess(PROCESS_QUERY_LIMITED_-`
|
|
78
|
+
* `INFORMATION)`. Returns success iff the PID exists and the caller
|
|
79
|
+
* has rights, throws otherwise.
|
|
80
|
+
*
|
|
81
|
+
* On any error we return `false`. EPERM in particular ("alive but
|
|
82
|
+
* unprivileged") means the PID belongs to someone else now, so it's not
|
|
83
|
+
* our session even if it's a real process. The bootTime guard catches the
|
|
84
|
+
* rare "PID got reused after a reboot, we still own it" case.
|
|
85
|
+
*/
|
|
86
|
+
export function isPidAlive(pid) {
|
|
87
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
88
|
+
return false;
|
|
89
|
+
try {
|
|
90
|
+
process.kill(pid, 0);
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Validate that a parsed value matches `SessionFile`. Catches schema drift,
|
|
99
|
+
* truncated writes, and tampered files. Anything other than a perfect match
|
|
100
|
+
* is reported as `malformed` -- we don't try to repair partial files.
|
|
101
|
+
*/
|
|
102
|
+
function validateSessionFile(raw) {
|
|
103
|
+
if (!raw || typeof raw !== 'object')
|
|
104
|
+
return false;
|
|
105
|
+
const r = raw;
|
|
106
|
+
return (typeof r.version === 'number' &&
|
|
107
|
+
typeof r.pid === 'number' &&
|
|
108
|
+
typeof r.sessionId === 'string' &&
|
|
109
|
+
typeof r.appId === 'string' &&
|
|
110
|
+
typeof r.previewUrl === 'string' &&
|
|
111
|
+
typeof r.startedAt === 'number' &&
|
|
112
|
+
typeof r.bootTime === 'number' &&
|
|
113
|
+
typeof r.cliVersion === 'string' &&
|
|
114
|
+
(r.mode === 'foreground' || r.mode === 'detached'));
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Read and parse the session file. Returns `null` for a missing file or
|
|
118
|
+
* any IO/parse error. The caller decides what "missing" vs "malformed"
|
|
119
|
+
* means -- use `getSessionState()` for that distinction.
|
|
120
|
+
*/
|
|
121
|
+
export function readSessionFile(appDir) {
|
|
122
|
+
const { file } = getSessionPaths(appDir);
|
|
123
|
+
let raw;
|
|
124
|
+
try {
|
|
125
|
+
raw = fs.readFileSync(file, 'utf-8');
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
let parsed;
|
|
131
|
+
try {
|
|
132
|
+
parsed = JSON.parse(raw);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
if (!validateSessionFile(parsed))
|
|
138
|
+
return null;
|
|
139
|
+
return parsed;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Write the session file atomically. Writes to `<file>.tmp` first then
|
|
143
|
+
* renames into place. POSIX `rename()` and Windows `MoveFileEx` are both
|
|
144
|
+
* atomic on the same volume, which a sibling temp file always is.
|
|
145
|
+
*
|
|
146
|
+
* Creates `.runwork/` if it doesn't exist. The directory is gitignored at
|
|
147
|
+
* the project-template level.
|
|
148
|
+
*/
|
|
149
|
+
export function writeSessionFile(appDir, data) {
|
|
150
|
+
const paths = getSessionPaths(appDir);
|
|
151
|
+
fs.mkdirSync(paths.dir, { recursive: true });
|
|
152
|
+
// We hold the JSON in memory before writing, so a serialization error
|
|
153
|
+
// never leaves a half-written tmp file on disk.
|
|
154
|
+
const json = JSON.stringify(data, null, 2);
|
|
155
|
+
fs.writeFileSync(paths.tmpFile, json, { encoding: 'utf-8' });
|
|
156
|
+
fs.renameSync(paths.tmpFile, paths.file);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Conditional removal: only deletes the session file when its `pid`
|
|
160
|
+
* field matches the caller's. Use this from per-process cleanup paths
|
|
161
|
+
* where another process (e.g., the winner of a startup race) may have
|
|
162
|
+
* overwritten the file with a different owner. Returns `true` when we
|
|
163
|
+
* actually removed it.
|
|
164
|
+
*
|
|
165
|
+
* `removeSessionFile` is the unconditional primitive; this is the
|
|
166
|
+
* "be-a-good-citizen" wrapper for in-process cleanup handlers.
|
|
167
|
+
*/
|
|
168
|
+
export function removeSessionFileIfOwned(appDir, pid) {
|
|
169
|
+
const file = readSessionFile(appDir);
|
|
170
|
+
if (!file)
|
|
171
|
+
return false;
|
|
172
|
+
if (file.pid !== pid)
|
|
173
|
+
return false;
|
|
174
|
+
removeSessionFile(appDir);
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Idempotent removal. Missing file is not an error. We also clear any
|
|
179
|
+
* leftover temp file from a crashed mid-write -- those aren't load-bearing
|
|
180
|
+
* but they're noise and they confuse `ls -la .runwork/`.
|
|
181
|
+
*/
|
|
182
|
+
export function removeSessionFile(appDir) {
|
|
183
|
+
const { file, tmpFile } = getSessionPaths(appDir);
|
|
184
|
+
for (const p of [file, tmpFile]) {
|
|
185
|
+
try {
|
|
186
|
+
fs.unlinkSync(p);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// ENOENT is the happy path; any other error is also intentionally
|
|
190
|
+
// swallowed -- removal is best-effort cleanup, not a load-bearing
|
|
191
|
+
// step. The next `runwork dev` will detect a stale file via the
|
|
192
|
+
// PID/bootTime checks regardless.
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Determine the live state of the session file in the given app directory.
|
|
198
|
+
*
|
|
199
|
+
* Checks are ordered cheap-to-expensive. The `pidAlive` syscall is last
|
|
200
|
+
* so a malformed or wrong-version file short-circuits before we touch
|
|
201
|
+
* the OS at all.
|
|
202
|
+
*
|
|
203
|
+
* 1. File missing -> `none`
|
|
204
|
+
* 2. File malformed / truncated -> `stale: malformed`
|
|
205
|
+
* 3. Schema version mismatch -> `stale: version-mismatch`
|
|
206
|
+
* 4. App ID mismatch -> `stale: app-id-mismatch`
|
|
207
|
+
* 5. Boot time outside tolerance -> `stale: boot-time-mismatch`
|
|
208
|
+
* 6. PID not alive -> `stale: pid-dead`
|
|
209
|
+
* 7. Otherwise -> `alive`
|
|
210
|
+
*/
|
|
211
|
+
export function getSessionState(appDir, expectedAppId, deps = {}) {
|
|
212
|
+
const { file: filePath } = getSessionPaths(appDir);
|
|
213
|
+
if (!fs.existsSync(filePath))
|
|
214
|
+
return { state: 'none' };
|
|
215
|
+
const file = readSessionFile(appDir);
|
|
216
|
+
if (!file)
|
|
217
|
+
return { state: 'stale', reason: 'malformed' };
|
|
218
|
+
if (file.version !== SESSION_FILE_SCHEMA_VERSION) {
|
|
219
|
+
return { state: 'stale', reason: 'version-mismatch', file };
|
|
220
|
+
}
|
|
221
|
+
if (file.appId !== expectedAppId) {
|
|
222
|
+
return { state: 'stale', reason: 'app-id-mismatch', file };
|
|
223
|
+
}
|
|
224
|
+
if (isBootTimeStale(file.bootTime, deps)) {
|
|
225
|
+
return { state: 'stale', reason: 'boot-time-mismatch', file };
|
|
226
|
+
}
|
|
227
|
+
const d = resolveDeps(deps);
|
|
228
|
+
if (!d.pidAlive(file.pid)) {
|
|
229
|
+
return { state: 'stale', reason: 'pid-dead', file };
|
|
230
|
+
}
|
|
231
|
+
return { state: 'alive', file };
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Convenience constructor for a fresh session file. Fills in version,
|
|
235
|
+
* startedAt, and bootTime from the runtime; everything else is supplied
|
|
236
|
+
* by the caller. Test code can pass a `deps.bootTime` override to inject
|
|
237
|
+
* a deterministic value.
|
|
238
|
+
*/
|
|
239
|
+
export function buildSessionFile(input) {
|
|
240
|
+
const d = resolveDeps(input.deps);
|
|
241
|
+
return {
|
|
242
|
+
version: SESSION_FILE_SCHEMA_VERSION,
|
|
243
|
+
pid: input.pid,
|
|
244
|
+
sessionId: input.sessionId,
|
|
245
|
+
appId: input.appId,
|
|
246
|
+
previewUrl: input.previewUrl,
|
|
247
|
+
startedAt: input.startedAt ?? Date.now(),
|
|
248
|
+
bootTime: d.bootTime(),
|
|
249
|
+
cliVersion: input.cliVersion,
|
|
250
|
+
mode: input.mode,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stop a running dev session, identified by the on-disk session file.
|
|
3
|
+
*
|
|
4
|
+
* Termination is platform-aware but the design does NOT depend on the
|
|
5
|
+
* child's cleanup handler running. We always remove the session file
|
|
6
|
+
* ourselves at the end so the next `runwork dev` invocation sees a clean
|
|
7
|
+
* slate even on Windows (no SIGTERM equivalent) or on a kill-9'd Unix
|
|
8
|
+
* process.
|
|
9
|
+
*/
|
|
10
|
+
import { type SessionDeps, type SessionStaleReason } from './session.js';
|
|
11
|
+
export type StopOutcome = {
|
|
12
|
+
result: 'no-session';
|
|
13
|
+
} | {
|
|
14
|
+
result: 'stale-cleaned';
|
|
15
|
+
reason: SessionStaleReason;
|
|
16
|
+
pid?: number;
|
|
17
|
+
} | {
|
|
18
|
+
result: 'stopped';
|
|
19
|
+
pid: number;
|
|
20
|
+
gracefully: boolean;
|
|
21
|
+
} | {
|
|
22
|
+
result: 'kill-failed';
|
|
23
|
+
pid: number;
|
|
24
|
+
error: unknown;
|
|
25
|
+
};
|
|
26
|
+
export interface StopDeps extends SessionDeps {
|
|
27
|
+
killProcess?: (pid: number, signal?: NodeJS.Signals | 0) => void;
|
|
28
|
+
sleep?: (ms: number) => Promise<void>;
|
|
29
|
+
platform?: NodeJS.Platform;
|
|
30
|
+
/**
|
|
31
|
+
* Maximum total time to wait for the SIGTERM'd child to exit gracefully
|
|
32
|
+
* before falling back to SIGKILL. Unix-only; ignored on Windows.
|
|
33
|
+
*/
|
|
34
|
+
graceTimeoutMs?: number;
|
|
35
|
+
/** Polling interval while waiting for the process to die. */
|
|
36
|
+
pollIntervalMs?: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Stop a dev session that may or may not exist for the given app dir.
|
|
40
|
+
*
|
|
41
|
+
* - `state: 'none'` -> exit-code-0 no-op, no session to stop.
|
|
42
|
+
* - `state: 'stale'` -> remove the file, no kill needed (the PID is
|
|
43
|
+
* either dead, mismatched, or a different app altogether).
|
|
44
|
+
* - `state: 'alive'` -> Unix: SIGTERM, wait up to graceTimeoutMs,
|
|
45
|
+
* SIGKILL fallback. Windows: TerminateProcess (signal-less kill);
|
|
46
|
+
* Node has no graceful-shutdown signal that survives the cross-process
|
|
47
|
+
* boundary on Windows.
|
|
48
|
+
*
|
|
49
|
+
* In every "found a file" path the file is removed before returning, so
|
|
50
|
+
* the next `runwork dev` sees a clean slate regardless of how things went.
|
|
51
|
+
*/
|
|
52
|
+
export declare function stopSession(appDir: string, expectedAppId: string, deps?: StopDeps): Promise<StopOutcome>;
|
package/dist/dev/stop.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stop a running dev session, identified by the on-disk session file.
|
|
3
|
+
*
|
|
4
|
+
* Termination is platform-aware but the design does NOT depend on the
|
|
5
|
+
* child's cleanup handler running. We always remove the session file
|
|
6
|
+
* ourselves at the end so the next `runwork dev` invocation sees a clean
|
|
7
|
+
* slate even on Windows (no SIGTERM equivalent) or on a kill-9'd Unix
|
|
8
|
+
* process.
|
|
9
|
+
*/
|
|
10
|
+
import { getSessionPaths, getSessionState, isPidAlive as defaultIsPidAlive, removeSessionFile, } from './session.js';
|
|
11
|
+
import * as fs from 'fs';
|
|
12
|
+
const defaultStopDeps = {
|
|
13
|
+
killProcess: (pid, signal) => {
|
|
14
|
+
process.kill(pid, signal);
|
|
15
|
+
},
|
|
16
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
17
|
+
platform: process.platform,
|
|
18
|
+
graceTimeoutMs: 5_000,
|
|
19
|
+
pollIntervalMs: 100,
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Stop a dev session that may or may not exist for the given app dir.
|
|
23
|
+
*
|
|
24
|
+
* - `state: 'none'` -> exit-code-0 no-op, no session to stop.
|
|
25
|
+
* - `state: 'stale'` -> remove the file, no kill needed (the PID is
|
|
26
|
+
* either dead, mismatched, or a different app altogether).
|
|
27
|
+
* - `state: 'alive'` -> Unix: SIGTERM, wait up to graceTimeoutMs,
|
|
28
|
+
* SIGKILL fallback. Windows: TerminateProcess (signal-less kill);
|
|
29
|
+
* Node has no graceful-shutdown signal that survives the cross-process
|
|
30
|
+
* boundary on Windows.
|
|
31
|
+
*
|
|
32
|
+
* In every "found a file" path the file is removed before returning, so
|
|
33
|
+
* the next `runwork dev` sees a clean slate regardless of how things went.
|
|
34
|
+
*/
|
|
35
|
+
export async function stopSession(appDir, expectedAppId, deps = {}) {
|
|
36
|
+
const d = { ...defaultStopDeps, ...deps };
|
|
37
|
+
// StopDeps extends SessionDeps, so we can pass `deps` straight through
|
|
38
|
+
// to getSessionState. Constructing a separate `{ bootTime, pidAlive }`
|
|
39
|
+
// object would smuggle in `undefined` values when the caller didn't
|
|
40
|
+
// override them, which then overwrite the real defaults in getSessionState's
|
|
41
|
+
// own spread. Forwarding the object as-is keeps the defaults intact.
|
|
42
|
+
const state = getSessionState(appDir, expectedAppId, deps);
|
|
43
|
+
if (state.state === 'none') {
|
|
44
|
+
return { result: 'no-session' };
|
|
45
|
+
}
|
|
46
|
+
if (state.state === 'stale') {
|
|
47
|
+
removeSessionFile(appDir);
|
|
48
|
+
return { result: 'stale-cleaned', reason: state.reason, pid: state.file?.pid };
|
|
49
|
+
}
|
|
50
|
+
const { file } = state;
|
|
51
|
+
const pid = file.pid;
|
|
52
|
+
// Unix: SIGTERM, wait, SIGKILL fallback.
|
|
53
|
+
// Windows: signal-less kill (== TerminateProcess via Node).
|
|
54
|
+
const isWindows = d.platform === 'win32';
|
|
55
|
+
const livenessProbe = deps.pidAlive ?? defaultIsPidAlive;
|
|
56
|
+
try {
|
|
57
|
+
if (isWindows) {
|
|
58
|
+
d.killProcess(pid);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
d.killProcess(pid, 'SIGTERM');
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
// Even if the kill failed (PID died between state-read and kill, or
|
|
66
|
+
// permission denied), we still want to remove the file so the user
|
|
67
|
+
// isn't stuck. Surface the error as a warning-grade outcome, but
|
|
68
|
+
// clean up.
|
|
69
|
+
removeSessionFile(appDir);
|
|
70
|
+
return { result: 'kill-failed', pid, error: err };
|
|
71
|
+
}
|
|
72
|
+
let gracefully = false;
|
|
73
|
+
if (!isWindows) {
|
|
74
|
+
const deadline = Date.now() + d.graceTimeoutMs;
|
|
75
|
+
while (Date.now() < deadline) {
|
|
76
|
+
if (!livenessProbe(pid)) {
|
|
77
|
+
gracefully = true;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
// The child cleans up its own session file on SIGTERM, so the file
|
|
81
|
+
// disappearing is also an acceptable "we're done" signal.
|
|
82
|
+
if (!fs.existsSync(getSessionPaths(appDir).file)) {
|
|
83
|
+
gracefully = true;
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
await d.sleep(d.pollIntervalMs);
|
|
87
|
+
}
|
|
88
|
+
if (!gracefully) {
|
|
89
|
+
try {
|
|
90
|
+
d.killProcess(pid, 'SIGKILL');
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// Already dead, race-condition'd, or no permission. Either way,
|
|
94
|
+
// we proceed to remove the file -- the goal is "this session is
|
|
95
|
+
// gone from this machine's perspective."
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
removeSessionFile(appDir);
|
|
100
|
+
return { result: 'stopped', pid, gracefully };
|
|
101
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.10.
|
|
1
|
+
export declare const VERSION = "0.10.3";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Auto-generated by scripts/embed-types.ts -- do not edit
|
|
2
|
-
export const VERSION = "0.10.
|
|
2
|
+
export const VERSION = "0.10.3";
|
|
@@ -27,4 +27,8 @@ describe('parseKeypress', () => {
|
|
|
27
27
|
it('detects "i" for info', () => {
|
|
28
28
|
expect(parseKeypress(Buffer.from('i'))).toBe('i');
|
|
29
29
|
});
|
|
30
|
+
it('detects "s" for stop (used by `runwork dev attach`)', () => {
|
|
31
|
+
expect(parseKeypress(Buffer.from('s'))).toBe('s');
|
|
32
|
+
expect(parseKeypress(Buffer.from('S'))).toBe('s');
|
|
33
|
+
});
|
|
30
34
|
});
|
package/dist/ui/keyboard.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type KeyAction = 'o' | 'p' | 'a' | 'e' | 'r' | 'i' | 'quit' | null;
|
|
1
|
+
export type KeyAction = 'o' | 'p' | 'a' | 'e' | 'r' | 'i' | 's' | 'quit' | null;
|
|
2
2
|
/** Parse a raw stdin buffer into a named action. */
|
|
3
3
|
export declare function parseKeypress(data: Buffer): KeyAction;
|
|
4
4
|
export interface KeyboardListener {
|