dsh-ris-ide 1.7.2 → 1.8.0

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 (79) hide show
  1. package/README.md +43 -4
  2. package/bin/check-listing.mjs +247 -0
  3. package/bin/proxy-janitor.mjs +183 -0
  4. package/bin/risd.mjs +287 -0
  5. package/bin/run-with-log.ps1 +43 -5
  6. package/lib/client-codemirror.js +92 -66
  7. package/lib/client.js +774 -89
  8. package/lib/index.js +2256 -21
  9. package/lib/janitor.js +377 -0
  10. package/lib/proxy.js +1577 -0
  11. package/lib/proxybridge-bundle.js +798 -0
  12. package/lib/redirector.js +2558 -0
  13. package/lib/risd/build.js +91 -0
  14. package/lib/risd/debug.js +374 -0
  15. package/lib/risd/git.js +207 -0
  16. package/lib/risd/leases.js +124 -0
  17. package/lib/risd/lifecycle.js +148 -0
  18. package/lib/risd/log.js +59 -0
  19. package/lib/risd/ping.js +94 -0
  20. package/lib/risd/programs.js +348 -0
  21. package/lib/risd/server.js +1478 -0
  22. package/lib/risd/state.js +137 -0
  23. package/lib/risd/ui.js +1705 -0
  24. package/lib/risd/view.js +79 -0
  25. package/lib/risd-client.js +282 -0
  26. package/lib/standalone/window.html +14 -16
  27. package/lib/startup.js +114 -0
  28. package/package.json +7 -2
  29. package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
  30. package/test/client-build.test.mjs +113 -0
  31. package/test/client-viewer.test.mjs +314 -20
  32. package/test/companion.test.mjs +65 -0
  33. package/test/dsh-origin.test.mjs +140 -0
  34. package/test/dsh-window-refresh.test.mjs +100 -0
  35. package/test/harness.test.mjs +9 -0
  36. package/test/host-noloop.test.mjs +74 -0
  37. package/test/host-tail.test.mjs +54 -5
  38. package/test/host-window.test.mjs +4 -4
  39. package/test/inherit-engine.test.mjs +175 -0
  40. package/test/install-phase.test.mjs +36 -0
  41. package/test/janitor.test.mjs +172 -0
  42. package/test/lifecycle.test.mjs +109 -0
  43. package/test/merge-owners.test.mjs +155 -0
  44. package/test/proxy-restart.test.mjs +37 -0
  45. package/test/proxy-route.test.mjs +599 -0
  46. package/test/proxy-window.test.mjs +45 -0
  47. package/test/proxy.test.mjs +914 -0
  48. package/test/proxybridge-bundle.test.mjs +687 -0
  49. package/test/redirector-bundle.test.mjs +391 -0
  50. package/test/redirector.test.mjs +571 -0
  51. package/test/risd-api.test.mjs +470 -0
  52. package/test/risd-bridge-degrade.test.mjs +101 -0
  53. package/test/risd-build.test.mjs +20 -0
  54. package/test/risd-cli-home.test.mjs +50 -0
  55. package/test/risd-client.test.mjs +130 -0
  56. package/test/risd-debug.test.mjs +261 -0
  57. package/test/risd-election.test.mjs +104 -0
  58. package/test/risd-engine.test.mjs +132 -0
  59. package/test/risd-entry.test.mjs +118 -0
  60. package/test/risd-git.test.mjs +109 -0
  61. package/test/risd-handoff.test.mjs +116 -0
  62. package/test/risd-heal.test.mjs +50 -0
  63. package/test/risd-helpers.mjs +108 -0
  64. package/test/risd-host-p2.test.mjs +147 -0
  65. package/test/risd-janitor-guard.test.mjs +46 -0
  66. package/test/risd-lease.test.mjs +83 -0
  67. package/test/risd-lifecycle.test.mjs +210 -0
  68. package/test/risd-log-follow.test.mjs +227 -0
  69. package/test/risd-mode.test.mjs +161 -0
  70. package/test/risd-ping.test.mjs +99 -0
  71. package/test/risd-programs.test.mjs +169 -0
  72. package/test/risd-review-p2.test.mjs +217 -0
  73. package/test/risd-shutdown.test.mjs +97 -0
  74. package/test/risd-teardown.test.mjs +87 -0
  75. package/test/risd-tools.test.mjs +211 -0
  76. package/test/risd-ui.test.mjs +445 -0
  77. package/test/risd-write.test.mjs +170 -0
  78. package/test/startup-reconcile.test.mjs +100 -0
  79. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A teardown that times out must leave the janitor ARMED.
3
+ *
4
+ * Review A-P0-2: stop() waited at most 5s for the network teardown and then
5
+ * disarmed the watcher unconditionally. On WSL the bridge probe can hang for
6
+ * seconds, so the timeout path was the normal one — and it left the engine, its
7
+ * pidfile and the port behind with nothing left to finish the job.
8
+ *
9
+ * The test drives an in-process daemon with a teardown that never resolves (the
10
+ * slow-mount shape) and a short timeout: the watcher must still be armed after
11
+ * stop() returned.
12
+ */
13
+ import assert from 'node:assert/strict'
14
+ import { mkdtempSync, rmSync } from 'node:fs'
15
+ import { tmpdir } from 'node:os'
16
+ import { join } from 'node:path'
17
+ import test from 'node:test'
18
+
19
+ const home = mkdtempSync(join(tmpdir(), 'risd-janitor-guard-'))
20
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
21
+
22
+ const { startRisd } = await import('../lib/risd/server.js')
23
+ const { armJanitor, disarmJanitor, janitorStatus } = await import('../lib/janitor.js')
24
+
25
+ test.after(() => {
26
+ disarmJanitor()
27
+ rmSync(home, { recursive: true, force: true })
28
+ })
29
+
30
+ test('a timed-out teardown keeps the janitor armed', async (t) => {
31
+ const started = await startRisd({
32
+ home,
33
+ port: 0,
34
+ version: 'test',
35
+ teardownTimeoutMs: 120,
36
+ // A mounted `/mnt/c` makes the bridge probe hang; a never-resolving teardown
37
+ // reproduces that shape without touching the real machine.
38
+ teardown: () => new Promise(() => {}),
39
+ })
40
+ assert.equal(started.ok, true)
41
+ assert.equal(janitorStatus().running, true, 'the daemon arms the watcher on start')
42
+ // Let the armed watcher be real, then stop the daemon; the network teardown will
43
+ // block on the bridge probe long past the 120ms budget.
44
+ await started.stop({})
45
+ assert.equal(janitorStatus().running, true, 'a timed-out teardown must leave the watcher to finish the job')
46
+ })
@@ -0,0 +1,83 @@
1
+ /**
2
+ * risd leases: liveness is "is the owner pid still there", not "did we see an
3
+ * exit signal".
4
+ *
5
+ * Unit half: the registry with an injected `alive` predicate, so the exact
6
+ * sweep semantics (idempotent acquire, callback once, release removes the key)
7
+ * can be tested without waiting on the clock.
8
+ *
9
+ * Integration half: a lease taken for a child process disappears within one
10
+ * poll interval (3s) after that child is killed — the behaviour Ctrl+C and
11
+ * SIGKILL both rely on.
12
+ */
13
+ import assert from 'node:assert/strict'
14
+ import test from 'node:test'
15
+ import { spawn } from 'node:child_process'
16
+ import { RISD_API_VERSION } from '../lib/risd/state.js'
17
+ import { createLeaseRegistry, LEASE_POLL_MS } from '../lib/risd/leases.js'
18
+ import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
19
+
20
+ test('acquire is idempotent per owner/session/workspace and release is exact', () => {
21
+ const gone = []
22
+ const registry = createLeaseRegistry({ alive: () => true, onGone: (lease) => gone.push(lease.id) })
23
+ const first = registry.acquire({ ownerPid: 11, sessionId: 's', cwd: '/w' })
24
+ const again = registry.acquire({ ownerPid: 11, sessionId: 's', cwd: '/w' })
25
+ assert.equal(again.id, first.id)
26
+ assert.equal(registry.count(), 1)
27
+
28
+ const other = registry.acquire({ ownerPid: 11, sessionId: 's2', cwd: '/w' })
29
+ assert.notEqual(other.id, first.id)
30
+ assert.equal(registry.count(), 2)
31
+
32
+ assert.equal(registry.release(first.id), true)
33
+ assert.equal(registry.release(first.id), false)
34
+ assert.equal(registry.count(), 1)
35
+ assert.deepEqual(gone, [], 'release is not death: no onGone callback')
36
+ })
37
+
38
+ test('a dead owner is swept after one poll and onGone fires once', async () => {
39
+ const alive = new Set([21, 22])
40
+ const gone = []
41
+ const registry = createLeaseRegistry({ pollMs: 20, alive: (pid) => alive.has(pid), onGone: (lease) => gone.push(lease.ownerPid) })
42
+ registry.start()
43
+ registry.acquire({ ownerPid: 21, cwd: '/w' })
44
+ registry.acquire({ ownerPid: 22, cwd: '/w' })
45
+ alive.delete(21)
46
+ await sleep(80)
47
+ registry.stop()
48
+ assert.deepEqual(registry.list().map((lease) => lease.ownerPid), [22])
49
+ assert.deepEqual(gone, [21])
50
+ })
51
+
52
+ test('the daemon forgets a lease whose owner process is killed', async (t) => {
53
+ const home = makeHome('risd-lease-')
54
+ t.after(() => removeHome(home))
55
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
56
+ t.after(() => daemon.stop())
57
+
58
+ const victim = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
59
+ t.after(() => victim.kill('SIGKILL'))
60
+ const headers = { authorization: `Bearer ${daemon.state.token}`, 'x-risd-api-version': String(RISD_API_VERSION), 'content-type': 'application/json' }
61
+ const created = await fetch(`${daemon.state.url}/v1/leases`, {
62
+ method: 'POST',
63
+ headers,
64
+ body: JSON.stringify({ ownerPid: victim.pid, sessionId: 's', cwd: '/tmp/ws' }),
65
+ })
66
+ assert.equal(created.status, 200)
67
+ const lease = (await created.json()).lease
68
+ assert.equal(lease.ownerPid, victim.pid)
69
+
70
+ const before = await (await fetch(`${daemon.state.url}/v1/status?cwd=/tmp/ws`, { headers })).json()
71
+ assert.equal(before.daemon.leases, 1)
72
+
73
+ victim.kill('SIGKILL')
74
+ const deadline = Date.now() + LEASE_POLL_MS + 3000
75
+ let count = 1
76
+ while (Date.now() < deadline) {
77
+ const body = await (await fetch(`${daemon.state.url}/v1/status?cwd=/tmp/ws`, { headers })).json()
78
+ count = body.daemon.leases
79
+ if (count === 0) break
80
+ await sleep(200)
81
+ }
82
+ assert.equal(count, 0, 'the lease must be swept within one poll interval')
83
+ })
@@ -0,0 +1,210 @@
1
+ // Lifecycle settings: which resources follow dsh, and which follow the daemon.
2
+ // Defaults must preserve the behaviour that existed before the setting (proxy
3
+ // follows dsh, everything else stops with the daemon), and a broken policy file
4
+ // must never take the daemon down.
5
+ import assert from 'node:assert/strict'
6
+ import test from 'node:test'
7
+ import { chmodSync, existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+
10
+ import {
11
+ LIFECYCLE_DEFAULTS,
12
+ lifecyclePath,
13
+ mergeLifecycle,
14
+ normalizeLifecycle,
15
+ readLifecycle,
16
+ writeLifecycle,
17
+ } from '../lib/risd/lifecycle.js'
18
+ import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
19
+
20
+ test('defaults match the behaviour from before the setting existed', () => {
21
+ const { value, errors } = normalizeLifecycle({})
22
+ assert.deepEqual(errors, [])
23
+ assert.deepEqual(value, LIFECYCLE_DEFAULTS)
24
+ assert.equal(value.daemon.followDsh, true)
25
+ assert.equal(value.proxy.followDsh, true)
26
+ assert.equal(value.programs.followDsh, false, 'closing the last dsh must not stop JVMs by default')
27
+ assert.equal(value.debug.followDsh, false)
28
+ })
29
+
30
+ test('partial input keeps the untouched defaults and rejects non-booleans', () => {
31
+ const partial = normalizeLifecycle({ programs: { followDsh: true } })
32
+ assert.deepEqual(partial.errors, [])
33
+ assert.equal(partial.value.programs.followDsh, true)
34
+ assert.equal(partial.value.proxy.followDsh, true)
35
+
36
+ // Following the daemon is forced (m07741): the old key is rejected, not stored.
37
+ const forced = normalizeLifecycle({ proxy: { followDsh: true, followDaemon: false }, programs: { followDaemon: false } })
38
+ assert.equal(forced.changed, false)
39
+ assert.equal(forced.errors.length, 2)
40
+ assert.match(forced.errors.join(';'), /proxy\.followDaemon 不再支持:所有资源强制跟随 daemon/)
41
+ assert.equal('followDaemon' in forced.value.proxy, false)
42
+ assert.equal('followDaemon' in forced.value.programs, false)
43
+
44
+ const bad = normalizeLifecycle({ proxy: { followDsh: 'yes' }, debug: 'nope' })
45
+ assert.equal(bad.changed, false)
46
+ assert.equal(bad.errors.length, 2)
47
+ assert.match(bad.errors.join(';'), /proxy\.followDsh 必须是 true\/false/)
48
+ assert.match(bad.errors.join(';'), /debug 必须是对象/)
49
+ })
50
+
51
+ test('a partial save merges over the policy in force', () => {
52
+ // POST /v1/config used to normalize the body alone, so saving one checkbox reset
53
+ // the other three resources to their defaults (review A2-P2-1).
54
+ const current = normalizeLifecycle({ proxy: { followDsh: false }, debug: { followDsh: true } }).value
55
+ const merged = normalizeLifecycle(mergeLifecycle(current, { programs: { followDsh: true } })).value
56
+ assert.equal(merged.programs.followDsh, true, 'the submitted resource changed')
57
+ assert.equal(merged.proxy.followDsh, false, 'the untouched resource kept its value')
58
+ assert.equal(merged.debug.followDsh, true, 'the untouched resource kept its value')
59
+ assert.equal(merged.daemon.followDsh, true)
60
+ })
61
+
62
+ test('unknown resources and keys are rejected instead of silently saved', () => {
63
+ const unknownResource = normalizeLifecycle({ engine: { followDsh: true } })
64
+ assert.equal(unknownResource.changed, false)
65
+ assert.match(unknownResource.errors.join(';'), /engine 不是生命周期资源/)
66
+ assert.equal('engine' in unknownResource.value, false)
67
+
68
+ const unknownKey = normalizeLifecycle({ proxy: { followDsh: true, keepAlive: true } })
69
+ assert.equal(unknownKey.changed, false)
70
+ assert.match(unknownKey.errors.join(';'), /proxy\.keepAlive 不是可配置项/)
71
+ })
72
+
73
+ test('a missing file reads as defaults; a broken file still yields defaults', () => {
74
+ const home = makeHome('risd-life-')
75
+ try {
76
+ const missing = readLifecycle(home)
77
+ assert.equal(missing.exists, false)
78
+ assert.deepEqual(missing.value, LIFECYCLE_DEFAULTS)
79
+
80
+ writeFileSync(lifecyclePath(home), '{ not json')
81
+ const broken = readLifecycle(home)
82
+ assert.equal(broken.exists, true)
83
+ assert.deepEqual(broken.value, LIFECYCLE_DEFAULTS, 'a bad file must not stop the daemon')
84
+ assert.match(broken.errors.join(';'), /无法解析/)
85
+ } finally { removeHome(home) }
86
+ })
87
+
88
+ test('write persists atomically with 0600 and reads back', () => {
89
+ const home = makeHome('risd-life-')
90
+ try {
91
+ const written = writeLifecycle(home, { programs: { followDsh: true } })
92
+ assert.deepEqual(written.errors, [])
93
+ assert.equal(written.value.programs.followDsh, true)
94
+ const path = lifecyclePath(home)
95
+ assert.ok(existsSync(path))
96
+ assert.equal(statSync(path).mode & 0o777, 0o600)
97
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
98
+ assert.equal(parsed.programs.followDsh, true)
99
+ const again = readLifecycle(home)
100
+ assert.equal(again.value.proxy.followDsh, true)
101
+ } finally { removeHome(home) }
102
+ })
103
+
104
+ test('POST /v1/config stores the policy and GET /v1/config returns it', async () => {
105
+ const home = makeHome('risd-life-')
106
+ const daemon = await startRisdProcess({ home })
107
+ try {
108
+ const { port, token } = daemon.state
109
+ const headers = { authorization: `Bearer ${token}`, 'x-risd-api-version': '1', 'content-type': 'application/json' }
110
+ const before = await (await fetch(`http://127.0.0.1:${port}/v1/config`, { headers })).json()
111
+ assert.equal(before.ok, true)
112
+ assert.deepEqual(before.lifecycle, LIFECYCLE_DEFAULTS)
113
+
114
+ const saved = await fetch(`http://127.0.0.1:${port}/v1/config`, {
115
+ method: 'POST',
116
+ headers,
117
+ body: JSON.stringify({ lifecycle: { daemon: { followDsh: false }, programs: { followDsh: true } } }),
118
+ })
119
+ assert.equal(saved.status, 200)
120
+ const savedBody = await saved.json()
121
+ assert.equal(savedBody.ok, true)
122
+ assert.equal(savedBody.lifecycle.daemon.followDsh, false)
123
+ assert.equal(savedBody.lifecycle.programs.followDsh, true)
124
+ assert.equal(existsSync(join(home, 'risd-lifecycle.json')), true)
125
+
126
+ const after = await (await fetch(`http://127.0.0.1:${port}/v1/config`, { headers })).json()
127
+ assert.equal(after.lifecycle.daemon.followDsh, false)
128
+ assert.equal(after.lifecycle.programs.followDsh, true)
129
+
130
+ const bad = await fetch(`http://127.0.0.1:${port}/v1/config`, {
131
+ method: 'POST',
132
+ headers,
133
+ body: JSON.stringify({ lifecycle: { proxy: { followDsh: 'true' } } }),
134
+ })
135
+ assert.equal(bad.status, 400)
136
+ assert.match((await bad.json()).message, /followDsh 必须是 true\/false/)
137
+
138
+ const forced = await fetch(`http://127.0.0.1:${port}/v1/config`, {
139
+ method: 'POST',
140
+ headers,
141
+ body: JSON.stringify({ lifecycle: { proxy: { followDaemon: false } } }),
142
+ })
143
+ assert.equal(forced.status, 400)
144
+ assert.match((await forced.json()).message, /followDaemon 不再支持/)
145
+ } finally {
146
+ await daemon.stop()
147
+ await sleep(100)
148
+ removeHome(home)
149
+ }
150
+ })
151
+
152
+ test('POST /v1/config rejects unknown resources, keys and non-object resources (review A3-P1-2)', async () => {
153
+ // The HTTP path used to whitelist-copy the patch before validating it, so a typo
154
+ // or a wrong shape answered 200 and was silently dropped. normalizeLifecycle's
155
+ // messages must reach the caller.
156
+ const home = makeHome('risd-life-')
157
+ const daemon = await startRisdProcess({ home })
158
+ try {
159
+ const { port, token } = daemon.state
160
+ const headers = { authorization: `Bearer ${token}`, 'x-risd-api-version': '1', 'content-type': 'application/json' }
161
+ const post = (lifecycle) => fetch(`http://127.0.0.1:${port}/v1/config`, {
162
+ method: 'POST',
163
+ headers,
164
+ body: JSON.stringify({ lifecycle }),
165
+ })
166
+ const cases = [
167
+ [{ engine: { followDsh: true } }, /engine 不是生命周期资源/],
168
+ [{ proxy: { followDsh: true, keepAlive: true } }, /proxy\.keepAlive 不是可配置项/],
169
+ [{ daemon: { followDaemon: false } }, /daemon\.followDaemon 不再支持/],
170
+ [{ proxy: true }, /proxy 必须是对象/],
171
+ [null, /lifecycle 必须是对象/],
172
+ [[], /lifecycle 必须是对象/],
173
+ ]
174
+ for (const [lifecycle, expected] of cases) {
175
+ const response = await post(lifecycle)
176
+ assert.equal(response.status, 400, `lifecycle=${JSON.stringify(lifecycle)}`)
177
+ assert.match((await response.json()).message, expected)
178
+ }
179
+ // Nothing invalid was written: the file still holds the defaults.
180
+ const after = await (await fetch(`http://127.0.0.1:${port}/v1/config`, { headers })).json()
181
+ assert.deepEqual(after.lifecycle, LIFECYCLE_DEFAULTS)
182
+ assert.deepEqual(after.lifecycleErrors, [])
183
+ } finally {
184
+ await daemon.stop()
185
+ await sleep(100)
186
+ removeHome(home)
187
+ }
188
+ })
189
+
190
+ test('a broken lifecycle file is reported by GET /v1/config (review A3-P2-8)', async () => {
191
+ // A hand-edited file that cannot be parsed runs on defaults; the page must be able
192
+ // to say why instead of showing defaults as if they were saved policy.
193
+ const home = makeHome('risd-life-')
194
+ const daemon = await startRisdProcess({ home })
195
+ try {
196
+ writeFileSync(join(home, 'risd-lifecycle.json'), '{ this is not json', { mode: 0o600 })
197
+ const { port, token } = daemon.state
198
+ const headers = { authorization: `Bearer ${token}`, 'x-risd-api-version': '1' }
199
+ const body = await (await fetch(`http://127.0.0.1:${port}/v1/config`, { headers })).json()
200
+ assert.equal(body.ok, true)
201
+ assert.deepEqual(body.lifecycle, LIFECYCLE_DEFAULTS)
202
+ assert.ok(Array.isArray(body.lifecycleErrors) && body.lifecycleErrors.length >= 1)
203
+ assert.match(body.lifecycleErrors.join('; '), /无法解析/)
204
+ } finally {
205
+ await daemon.stop()
206
+ await sleep(100)
207
+ removeHome(home)
208
+ }
209
+ })
210
+
@@ -0,0 +1,227 @@
1
+ // Daemon-side log follow: SSE frames with byte offsets, so a reconnecting panel can
2
+ // resume without replaying the whole file. Rotation/truncation restarts at 0 with a
3
+ // `reset` frame; a stopped program drains and then ends.
4
+ import assert from 'node:assert/strict'
5
+ import { spawn } from 'node:child_process'
6
+ import { appendFileSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { request } from 'node:http'
8
+ import { tmpdir } from 'node:os'
9
+ import { join } from 'node:path'
10
+ import { after, before, test } from 'node:test'
11
+ import { sleep, startRisdProcess } from './risd-helpers.mjs'
12
+ import { startLogFollow } from '../lib/risd/programs.js'
13
+
14
+ let daemon
15
+ let workspace
16
+ let logPath
17
+
18
+ function openStream(params, { token } = {}) {
19
+ const query = new URLSearchParams({ cwd: workspace, id: 'demo', ...params })
20
+ const events = []
21
+ const waiters = []
22
+ const req = request({
23
+ host: '127.0.0.1',
24
+ port: daemon.state.port,
25
+ path: `/v1/programs/log/stream?${query.toString()}`,
26
+ method: 'GET',
27
+ headers: token === undefined
28
+ ? {}
29
+ : { authorization: `Bearer ${token}`, 'x-risd-api-version': '1', accept: 'text/event-stream' },
30
+ }, (res) => {
31
+ let buffer = ''
32
+ res.setEncoding('utf8')
33
+ res.on('data', (chunk) => {
34
+ buffer += chunk
35
+ let index = buffer.indexOf('\n\n')
36
+ while (index >= 0) {
37
+ const raw = buffer.slice(0, index)
38
+ buffer = buffer.slice(index + 2)
39
+ const event = {}
40
+ for (const line of raw.split('\n')) {
41
+ if (line.startsWith('event:')) event.type = line.slice(6).trim()
42
+ else if (line.startsWith('data:')) event.data = JSON.parse(line.slice(5).trim())
43
+ }
44
+ if (event.type !== undefined && event.type !== 'ping') {
45
+ events.push(event)
46
+ for (const waiter of [...waiters]) {
47
+ if (waiter.predicate(event)) {
48
+ waiters.splice(waiters.indexOf(waiter), 1)
49
+ waiter.resolve(event)
50
+ }
51
+ }
52
+ }
53
+ index = buffer.indexOf('\n\n')
54
+ }
55
+ })
56
+ res.on('end', () => { for (const waiter of waiters.splice(0)) waiter.reject(new Error('stream ended')) })
57
+ })
58
+ req.on('error', () => {})
59
+ req.end()
60
+ return {
61
+ events,
62
+ status: null,
63
+ waitFor(predicate, timeoutMs = 6000) {
64
+ const existing = events.find(predicate)
65
+ if (existing !== undefined) return Promise.resolve(existing)
66
+ return new Promise((resolve, reject) => {
67
+ const waiter = { predicate, resolve, reject }
68
+ waiters.push(waiter)
69
+ setTimeout(() => {
70
+ const index = waiters.indexOf(waiter)
71
+ if (index >= 0) { waiters.splice(index, 1); reject(new Error(`timeout; events=${JSON.stringify(events)}`)) }
72
+ }, timeoutMs).unref?.()
73
+ })
74
+ },
75
+ close() { req.destroy() },
76
+ }
77
+ }
78
+
79
+ before(async () => {
80
+ workspace = mkdtempSync(join(tmpdir(), 'risd-log-follow-'))
81
+ mkdirSync(join(workspace, '.dsh-ris-ide'), { recursive: true })
82
+ writeFileSync(join(workspace, '.dsh-ris-ide', 'config.json'), `${JSON.stringify({
83
+ version: 1,
84
+ programs: [{
85
+ id: 'demo',
86
+ name: 'demo',
87
+ kind: 'custom',
88
+ dir: workspace,
89
+ logName: 'demo',
90
+ startCommand: 'true',
91
+ }],
92
+ })}\n`, 'utf8')
93
+ logPath = join(workspace, 'logs', 'demo.log')
94
+ mkdirSync(join(workspace, 'logs'), { recursive: true })
95
+ daemon = await startRisdProcess({ port: 0 })
96
+ })
97
+
98
+ after(async () => {
99
+ if (daemon !== undefined) await daemon.stop()
100
+ if (workspace !== undefined) rmSync(workspace, { recursive: true, force: true })
101
+ })
102
+
103
+ test('the stream starts with the tail and then follows appended bytes by offset', async () => {
104
+ writeFileSync(logPath, 'first line\n', 'utf8')
105
+ const stream = openStream({}, { token: daemon.state.token })
106
+ const first = await stream.waitFor((event) => event.type === 'log')
107
+ assert.match(first.data.text, /first line/)
108
+ const offset = first.data.nextOffset
109
+ assert.ok(offset >= 'first line\n'.length)
110
+ appendFileSync(logPath, 'second line\n', 'utf8')
111
+ const second = await stream.waitFor((event) => event.type === 'log' && event.data.offset === offset)
112
+ assert.equal(second.data.text, 'second line\n')
113
+ assert.ok(second.data.nextOffset > offset)
114
+ stream.close()
115
+ })
116
+
117
+ test('passing an offset resumes without replaying older bytes', async () => {
118
+ writeFileSync(logPath, 'a\n', 'utf8')
119
+ const stream = openStream({ offset: '2' }, { token: daemon.state.token })
120
+ appendFileSync(logPath, 'b\n', 'utf8')
121
+ const frame = await stream.waitFor((event) => event.type === 'log')
122
+ assert.equal(frame.data.text, 'b\n')
123
+ assert.equal(frame.data.offset, 2)
124
+ stream.close()
125
+ })
126
+
127
+ test('truncation restarts the follower with a reset frame', async () => {
128
+ writeFileSync(logPath, 'longer content here\n', 'utf8')
129
+ const stream = openStream({}, { token: daemon.state.token })
130
+ await stream.waitFor((event) => event.type === 'log')
131
+ writeFileSync(logPath, 'x\n', 'utf8')
132
+ const reset = await stream.waitFor((event) => event.type === 'reset')
133
+ assert.equal(reset.data.offset, 0)
134
+ assert.equal(reset.data.text, 'x\n')
135
+ stream.close()
136
+ })
137
+
138
+ test('a stopped program ends the stream after the grace window', async () => {
139
+ writeFileSync(logPath, 'done\n', 'utf8')
140
+ const stream = openStream({}, { token: daemon.state.token })
141
+ await stream.waitFor((event) => event.type === 'log')
142
+ const end = await stream.waitFor((event) => event.type === 'end', 8000)
143
+ assert.equal(end.data.reason, 'stopped')
144
+ stream.close()
145
+ })
146
+
147
+ test('the stream requires the token and API version', async () => {
148
+ const res = await new Promise((resolve) => {
149
+ const query = new URLSearchParams({ cwd: workspace, id: 'demo' })
150
+ const req = request({
151
+ host: '127.0.0.1', port: daemon.state.port, path: `/v1/programs/log/stream?${query.toString()}`, method: 'GET',
152
+ }, (response) => {
153
+ response.resume()
154
+ response.on('end', () => resolve({ status: response.statusCode }))
155
+ })
156
+ req.on('error', () => resolve({ status: 0 }))
157
+ req.end()
158
+ })
159
+ assert.equal(res.status, 401)
160
+ })
161
+
162
+ test('an offset past EOF says reset instead of replaying the tail', async () => {
163
+ writeFileSync(logPath, 'tiny\n', 'utf8')
164
+ const stream = openStream({ offset: '9999' }, { token: daemon.state.token })
165
+ const reset = await stream.waitFor((event) => event.type === 'reset')
166
+ assert.equal(reset.data.offset, 0)
167
+ assert.equal(reset.data.text, 'tiny\n')
168
+ assert.equal(reset.data.nextOffset, 'tiny\n'.length)
169
+ stream.close()
170
+ })
171
+
172
+ test('a same-size rotation is a reset, not silence', async () => {
173
+ writeFileSync(logPath, '0123456789\n', 'utf8')
174
+ const stream = openStream({}, { token: daemon.state.token })
175
+ await stream.waitFor((event) => event.type === 'log')
176
+ const rotated = `${logPath}.rotated`
177
+ writeFileSync(rotated, 'abcdefghij\n', 'utf8') // same byte length, different inode
178
+ renameSync(rotated, logPath)
179
+ const reset = await stream.waitFor((event) => event.type === 'reset', 4000)
180
+ assert.equal(reset.data.text, 'abcdefghij\n')
181
+ stream.close()
182
+ })
183
+
184
+ test('a slow alive check never overlaps the next tick', async () => {
185
+ writeFileSync(logPath, '', 'utf8')
186
+ let inFlight = 0
187
+ let peak = 0
188
+ const follow = startLogFollow({ logPath, running: { alive: false } }, {
189
+ intervalMs: 20,
190
+ stoppedGraceMs: 10_000,
191
+ alive: async () => {
192
+ inFlight += 1
193
+ peak = Math.max(peak, inFlight)
194
+ await sleep(60)
195
+ inFlight -= 1
196
+ return true
197
+ },
198
+ }, () => {})
199
+ await sleep(300)
200
+ follow.stop()
201
+ assert.equal(peak, 1, 'ticks are chained, so alive checks never run concurrently')
202
+ })
203
+
204
+ test('the wrapper pid keeps the follower alive while the service pid is gone', async () => {
205
+ const dead = spawn(process.execPath, ['-e', 'setInterval(() => {}, 60000)'], { stdio: 'ignore' })
206
+ await new Promise((resolve) => dead.once('spawn', resolve))
207
+ dead.kill('SIGKILL')
208
+ await new Promise((resolve) => dead.once('exit', resolve))
209
+ const wrapper = spawn(process.execPath, ['-e', 'setInterval(() => {}, 60000)'], { stdio: 'ignore' })
210
+ await new Promise((resolve) => wrapper.once('spawn', resolve))
211
+ const pidPath = `${logPath}.pid`
212
+ writeFileSync(pidPath, `${dead.pid} ${wrapper.pid} ${Date.now()}\n`, 'utf8')
213
+ try {
214
+ writeFileSync(logPath, 'shutdown in progress\n', 'utf8')
215
+ const stream = openStream({}, { token: daemon.state.token })
216
+ await stream.waitFor((event) => event.type === 'log')
217
+ await sleep(700)
218
+ assert.equal(stream.events.some((event) => event.type === 'end'), false, 'not ended while the wrapper drains')
219
+ wrapper.kill('SIGKILL')
220
+ const end = await stream.waitFor((event) => event.type === 'end', 8000)
221
+ assert.equal(end.data.reason, 'stopped')
222
+ stream.close()
223
+ } finally {
224
+ try { wrapper.kill('SIGKILL') } catch { /* already gone */ }
225
+ rmSync(pidPath, { force: true })
226
+ }
227
+ })