dsh-ris-ide 1.7.0 → 1.7.2
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/README.md +3 -3
- package/lib/client-codemirror.js +18 -0
- package/lib/client.js +1192 -123
- package/lib/index.js +1555 -52
- package/lib/standalone/window.html +89 -14
- package/package.json +1 -1
- package/skills/dsh-ris-ide-debug/SKILL.md +2 -2
- package/test/client-viewer.test.mjs +589 -33
- package/test/clipboard.test.mjs +254 -0
- package/test/host-search.test.mjs +125 -1
- package/test/host-tail.test.mjs +198 -21
- package/test/windows.test.mjs +198 -0
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tree's copy mirrored onto the OS clipboard so a file manager can paste it.
|
|
3
|
+
*
|
|
4
|
+
* A web page cannot publish a file list (Chromium refuses `text/uri-list` on
|
|
5
|
+
* `Clipboard.write`, and a synthetic `copy` event only yields Chrome's private
|
|
6
|
+
* flavour), so the Host builds the platform command. These tests pin the command
|
|
7
|
+
* shape and the route contract — never the real clipboard, which belongs to the
|
|
8
|
+
* developer's desktop, not to CI.
|
|
9
|
+
*/
|
|
10
|
+
import { test } from 'node:test'
|
|
11
|
+
import assert from 'node:assert/strict'
|
|
12
|
+
import { createServer } from 'node:http'
|
|
13
|
+
import { readFile } from 'node:fs/promises'
|
|
14
|
+
|
|
15
|
+
import { __test } from '../lib/index.js'
|
|
16
|
+
|
|
17
|
+
const {
|
|
18
|
+
CLIPBOARD_FILES_PATH,
|
|
19
|
+
CLIPBOARD_READ_PATH,
|
|
20
|
+
CLIPBOARD_MAX_ENTRIES,
|
|
21
|
+
CLIPBOARD_MAX_PAYLOAD,
|
|
22
|
+
CLIPBOARD_STAGE_DIR,
|
|
23
|
+
clipboardScope,
|
|
24
|
+
stageClipboardCopy,
|
|
25
|
+
pruneClipboardStage,
|
|
26
|
+
clipboardStageMapping,
|
|
27
|
+
windowsClipboardScript,
|
|
28
|
+
windowsClipboardReadScript,
|
|
29
|
+
parseClipboardRead,
|
|
30
|
+
clipboardPathsToLinux,
|
|
31
|
+
readSystemFileClipboard,
|
|
32
|
+
writeSystemFileClipboard,
|
|
33
|
+
serveClipboardFiles,
|
|
34
|
+
serveClipboardRead,
|
|
35
|
+
isWsl,
|
|
36
|
+
} = __test
|
|
37
|
+
|
|
38
|
+
test('the clipboard route is one POST under the plugin prefix', () => {
|
|
39
|
+
assert.equal(CLIPBOARD_FILES_PATH, '/dsh-ris-ide/clipboard/files')
|
|
40
|
+
assert.equal(typeof serveClipboardFiles, 'function')
|
|
41
|
+
assert.equal(CLIPBOARD_MAX_ENTRIES, 200, 'one copy is a selection, not a whole disk')
|
|
42
|
+
assert.equal(CLIPBOARD_MAX_PAYLOAD, 256 * 1024, 'the stdin payload is bounded too')
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
test('the PowerShell script writes CF_HDROP with the intent Explorer reads', () => {
|
|
46
|
+
const copy = windowsClipboardScript(false)
|
|
47
|
+
assert.match(copy, /Add-Type -AssemblyName System\.Windows\.Forms/, 'the clipboard API comes from WinForms')
|
|
48
|
+
assert.match(copy, /\$data\.SetData\('FileDrop', \[string\[\]\]\$lines\)/, 'paths go in as a FileDrop list')
|
|
49
|
+
assert.match(copy, /\$data\.SetData\('Preferred DropEffect', \[byte\[\]\]@\(1,0,0,0\)\)/, 'copy is DROPEFFECT_COPY')
|
|
50
|
+
assert.match(copy, /\[System\.Windows\.Forms\.Clipboard\]::SetDataObject\(\$data, \$true\)/, 'the data is flushed, so it survives the PowerShell process')
|
|
51
|
+
assert.match(windowsClipboardScript(true), /\[byte\[\]\]@\(2,0,0,0\)/, 'cut is DROPEFFECT_MOVE')
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
test('no file name can reach the PowerShell script as code', async () => {
|
|
55
|
+
const source = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
|
|
56
|
+
// The script is a constant: the paths ride on stdin, one per line.
|
|
57
|
+
assert.match(source, /\[Console\]::OpenStandardInput\(\)/, 'the list is read from stdin')
|
|
58
|
+
assert.match(source, /\[Text\.Encoding\]::UTF8\.GetString/, 'stdin bytes are decoded as UTF-8')
|
|
59
|
+
assert.equal(/windowsPaths\.map\(powershellLiteral\)/.test(source), false, 'no path is interpolated into the script')
|
|
60
|
+
assert.equal(/function powershellLiteral/.test(source), false, 'the literal quoter is gone with the interpolation')
|
|
61
|
+
// …and the list is handed over as stdin, never as an argument vector entry.
|
|
62
|
+
assert.match(source, /'powershell\.exe', \['-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', encoded\], `\$\{windowsPaths\.join\('\\n'\)\}\\n`\)/)
|
|
63
|
+
// The route refuses names the line protocol cannot express.
|
|
64
|
+
assert.match(source, /复制到系统剪贴板不支持路径里的换行或控制字符/)
|
|
65
|
+
assert.match(source, /CLIPBOARD_MAX_PAYLOAD/)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
test('the Host owns the platform call, the client only asks for it', async () => {
|
|
69
|
+
assert.equal(typeof writeSystemFileClipboard, 'function')
|
|
70
|
+
assert.equal(typeof isWsl(), 'boolean', 'WSL detection is a platform fact, never request data')
|
|
71
|
+
const source = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
|
|
72
|
+
assert.match(source, /isLoopbackRequest\(req\)\) throw new TailError\('forbidden'/, 'the route is loopback-fenced')
|
|
73
|
+
assert.match(source, /paths\.length > CLIPBOARD_MAX_ENTRIES/, 'the count is capped')
|
|
74
|
+
assert.match(source, /'wslpath'/, 'WSL paths are translated for the Windows clipboard')
|
|
75
|
+
assert.match(source, /'linux-xclip'/, 'a GNOME desktop gets the copy|cut flavour')
|
|
76
|
+
assert.match(source, /'linux-wl-copy'/, 'a plain Wayland desktop falls back to text/uri-list')
|
|
77
|
+
assert.match(source, /'macos-appkit'/, 'Finder pasteboard is written through JXA')
|
|
78
|
+
// Every child process is spawned without a shell, with a hard timeout.
|
|
79
|
+
assert.equal(/shell: true/.test(source), false, 'no child is run through a shell')
|
|
80
|
+
assert.match(source, /child\.kill\('SIGKILL'\)/, 'a stuck helper is killed')
|
|
81
|
+
// macOS gets the paths as argv, not as JXA source.
|
|
82
|
+
assert.match(source, /'osascript', \['-l', 'JavaScript', '-e', script, \.\.\.paths\]/)
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
test('the route rejects relative, missing, control-character and oversized lists before touching the clipboard', async () => {
|
|
86
|
+
const server = createServer((req, res) => { void serveClipboardFiles(undefined, req, res, {}) })
|
|
87
|
+
await new Promise((resolvePromise) => server.listen(0, '127.0.0.1', resolvePromise))
|
|
88
|
+
const base = `http://127.0.0.1:${server.address().port}/dsh-ris-ide/clipboard/files`
|
|
89
|
+
const post = (body) => fetch(base, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
|
|
90
|
+
try {
|
|
91
|
+
assert.equal((await post({ paths: ['notes.txt'] })).status, 400, 'a relative path has no meaning on the OS clipboard')
|
|
92
|
+
assert.equal((await post({ paths: ['/definitely/not/here.txt'] })).status, 404, 'a stale row must not put a ghost on the clipboard')
|
|
93
|
+
assert.equal((await post({ paths: ['/tmp/it\nis.txt'] })).status, 400, 'a line break would split one name into two entries')
|
|
94
|
+
assert.equal((await post({ paths: ['/tmp/it\u0000is.txt'] })).status, 400, 'a NUL cannot survive a text channel')
|
|
95
|
+
const tooMany = Array.from({ length: CLIPBOARD_MAX_ENTRIES + 1 }, (_, index) => `/tmp/clip-${index}.txt`)
|
|
96
|
+
assert.equal((await post({ paths: tooMany })).status, 400, 'the cap is enforced')
|
|
97
|
+
assert.equal((await post({ paths: [] })).status, 400, 'an empty list is a caller bug')
|
|
98
|
+
// A COPY must be staged first, and staging needs the workspace. Without it the
|
|
99
|
+
// route refuses rather than publishing the originals.
|
|
100
|
+
const { mkdtemp, writeFile } = await import('node:fs/promises')
|
|
101
|
+
const { tmpdir } = await import('node:os')
|
|
102
|
+
const { join } = await import('node:path')
|
|
103
|
+
const real = join(await mkdtemp(join(tmpdir(), 'dsh-clip-route-')), 'a.txt')
|
|
104
|
+
await writeFile(real, 'x', 'utf8')
|
|
105
|
+
const noWorkspace = await post({ paths: [real] })
|
|
106
|
+
assert.equal(noWorkspace.status, 400, 'a copy that cannot be staged is refused')
|
|
107
|
+
assert.match((await noWorkspace.json()).message, /sessionId/, 'the message says why')
|
|
108
|
+
} finally {
|
|
109
|
+
await new Promise((resolvePromise) => server.close(resolvePromise))
|
|
110
|
+
}
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
test('the clipboard scope is read from the query string, like every tree route', () => {
|
|
114
|
+
const query = new URL('http://dsh.internal/dsh-ris-ide/clipboard/files?sessionId=session-1&cwd=%2Fw')
|
|
115
|
+
// The page puts the scope in the QUERY (that is how `clipboardQuery` builds it).
|
|
116
|
+
// Reading only the body made copy answer "复制到系统剪贴板需要 sessionId".
|
|
117
|
+
assert.deepEqual(clipboardScope({}, query), { sessionId: 'session-1', cwd: '/w' }, 'a page-built query resolves')
|
|
118
|
+
assert.deepEqual(clipboardScope({ sessionId: 'body', cwd: '/b' }, new URL('http://dsh.internal/x')), { sessionId: 'body', cwd: '/b' }, 'a body still works')
|
|
119
|
+
assert.deepEqual(clipboardScope({ sessionId: 'body' }, query), { sessionId: 'body', cwd: '/w' }, 'the body wins per field, the query fills the gap')
|
|
120
|
+
assert.deepEqual(clipboardScope({}, new URL('http://dsh.internal/x')), { sessionId: '', cwd: '' }, 'nothing carried reads as empty scope')
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
test('the clipboard can be READ back: Explorer copies reach the tree on WSL', () => {
|
|
124
|
+
assert.equal(CLIPBOARD_READ_PATH, '/dsh-ris-ide/clipboard/read')
|
|
125
|
+
assert.equal(typeof serveClipboardRead, 'function')
|
|
126
|
+
assert.equal(typeof readSystemFileClipboard, 'function')
|
|
127
|
+
// The read script is a constant too — it prints, it never interpolates a path.
|
|
128
|
+
const script = windowsClipboardReadScript()
|
|
129
|
+
assert.match(script, /Add-Type -AssemblyName System\.Windows\.Forms/)
|
|
130
|
+
assert.match(script, /GetDataObject\(\)/)
|
|
131
|
+
assert.match(script, /\$data\.GetData\("FileDrop"\)/)
|
|
132
|
+
assert.match(script, /"F:" \+ \[string\]\$file/, 'one line per file, so a name is never escaped as code')
|
|
133
|
+
assert.match(script, /"T:" \+ \[Convert\]::ToBase64String/, 'the text flavour is base64, so newlines survive')
|
|
134
|
+
const parsed = parseClipboardRead([
|
|
135
|
+
'F:' + ['C:', 'Users', 'dev', 'Desktop', 'README.md'].join('\\'),
|
|
136
|
+
'F:' + ['', '', 'wsl.localhost', 'Ubuntu-24.04', 'home', 'user', 'AGENTS.md'].join('\\'),
|
|
137
|
+
`T:${Buffer.from('hello\nworld', 'utf8').toString('base64')}`,
|
|
138
|
+
].join('\r\n'))
|
|
139
|
+
assert.deepEqual(parsed.files, [
|
|
140
|
+
['C:', 'Users', 'dev', 'Desktop', 'README.md'].join('\\'),
|
|
141
|
+
['', '', 'wsl.localhost', 'Ubuntu-24.04', 'home', 'user', 'AGENTS.md'].join('\\'),
|
|
142
|
+
])
|
|
143
|
+
assert.equal(parsed.text, 'hello\nworld')
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
test('Windows clipboard paths map to paths this filesystem can import', () => {
|
|
147
|
+
const wslRoot = ['', '', 'wsl.localhost', 'Ubuntu-24.04'].join('\\')
|
|
148
|
+
const otherRoot = ['', '', 'wsl.localhost', 'OtherDistro'].join('\\')
|
|
149
|
+
const serverRoot = ['', '', 'server', 'share'].join('\\')
|
|
150
|
+
const mapped = clipboardPathsToLinux([
|
|
151
|
+
wslRoot + '\\' + ['home', 'user', 'AGENTS.md'].join('\\'),
|
|
152
|
+
['', '', 'wsl$', 'Ubuntu-24.04'].join('\\') + '\\' + ['tmp', 'a b.txt'].join('\\'),
|
|
153
|
+
['C:', 'Users', 'dev', 'Desktop', 'README.md'].join('\\'),
|
|
154
|
+
otherRoot + '\\' + ['home', 'x.txt'].join('\\'),
|
|
155
|
+
serverRoot + '\\' + 'x.txt',
|
|
156
|
+
'/already/linux',
|
|
157
|
+
'/already/linux',
|
|
158
|
+
], { distro: 'Ubuntu-24.04' })
|
|
159
|
+
assert.deepEqual(mapped, [
|
|
160
|
+
'/' + ['home', 'user', 'AGENTS.md'].join('/'),
|
|
161
|
+
'/' + ['tmp', 'a b.txt'].join('/'),
|
|
162
|
+
'/' + ['mnt', 'c', 'Users', 'dev', 'Desktop', 'README.md'].join('/'),
|
|
163
|
+
'/already/linux',
|
|
164
|
+
], 'a foreign distro or an SMB share is not visible here; duplicates collapse')
|
|
165
|
+
assert.deepEqual(clipboardPathsToLinux([]), [])
|
|
166
|
+
assert.deepEqual(clipboardPathsToLinux('not a list'), [])
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
test('reading the clipboard is a loopback-fenced GET, never a write', async () => {
|
|
170
|
+
const source = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
|
|
171
|
+
assert.match(source, /const CLIPBOARD_READ_PATH = `\$\{ROUTE_PREFIX\}\/clipboard\/read`/)
|
|
172
|
+
assert.match(source, /if \(pathname === CLIPBOARD_READ_PATH\) \{/, 'the dispatch knows the route')
|
|
173
|
+
assert.match(source, /message: 'GET only'/, 'only a read is allowed on it')
|
|
174
|
+
assert.match(source, /async function serveClipboardRead\(ctx, req, res\) \{[\s\S]{0,400}isLoopbackRequest\(req\)\) throw new TailError\('forbidden'/,
|
|
175
|
+
'the same loopback fence as the write route')
|
|
176
|
+
assert.match(source, /'macos-appkit'[\s\S]{0,2000}'linux-wl-paste'/, 'each platform reads the flavour it wrote')
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
test('a COPY is published from a hidden staging area, never from the originals', async () => {
|
|
180
|
+
const { mkdtemp, mkdir, writeFile, readFile, stat, readdir } = await import('node:fs/promises')
|
|
181
|
+
const { tmpdir } = await import('node:os')
|
|
182
|
+
const { join } = await import('node:path')
|
|
183
|
+
const root = await mkdtemp(join(tmpdir(), 'dsh-clip-'))
|
|
184
|
+
const sourceFile = join(root, 'AGENTS.md')
|
|
185
|
+
await writeFile(sourceFile, '# agents\n', 'utf8')
|
|
186
|
+
const folder = join(root, 'docs')
|
|
187
|
+
await mkdir(folder)
|
|
188
|
+
await writeFile(join(folder, 'note.txt'), 'note', 'utf8')
|
|
189
|
+
|
|
190
|
+
const stage = await stageClipboardCopy(root, [sourceFile, folder])
|
|
191
|
+
assert.notEqual(stage, null, 'staging succeeds inside one filesystem')
|
|
192
|
+
assert.equal(stage.staged.length, 2)
|
|
193
|
+
assert.deepEqual(stage.originals, [sourceFile, folder])
|
|
194
|
+
assert.ok(stage.staged[0].startsWith(join(root, CLIPBOARD_STAGE_DIR)), 'the copy lives under the hidden stage')
|
|
195
|
+
assert.notEqual(stage.staged[0], sourceFile, 'the clipboard points at the copy, not the original')
|
|
196
|
+
// A plain file is a HARDLINK: same inode, no extra bytes, originals untouched.
|
|
197
|
+
assert.equal((await stat(stage.staged[0])).ino, (await stat(sourceFile)).ino, 'files are hard-linked, not duplicated')
|
|
198
|
+
assert.equal(await readFile(stage.staged[0], 'utf8'), '# agents\n')
|
|
199
|
+
assert.equal(await readFile(sourceFile, 'utf8'), '# agents\n', 'the original is still there')
|
|
200
|
+
// A directory cannot be hard-linked, but each FILE inside it is: the staged tree
|
|
201
|
+
// is a mirror of names, so a big folder costs inodes instead of bytes.
|
|
202
|
+
assert.equal((await stat(stage.staged[1])).isDirectory(), true)
|
|
203
|
+
assert.equal((await stat(join(stage.staged[1], 'note.txt'))).ino, (await stat(join(folder, 'note.txt'))).ino,
|
|
204
|
+
'files inside a staged folder are hard links too')
|
|
205
|
+
assert.equal(await readFile(join(stage.staged[1], 'note.txt'), 'utf8'), 'note')
|
|
206
|
+
assert.equal(await readFile(join(folder, 'note.txt'), 'utf8'), 'note')
|
|
207
|
+
|
|
208
|
+
// The manifest translates a staged path back to the original: Ctrl+C → Ctrl+V
|
|
209
|
+
// inside the tree must keep looking like the original selection.
|
|
210
|
+
const mapping = await clipboardStageMapping(root)
|
|
211
|
+
assert.equal(mapping.get(stage.staged[0]), sourceFile)
|
|
212
|
+
assert.equal(mapping.get(stage.staged[1]), folder)
|
|
213
|
+
|
|
214
|
+
// Old batches are pruned: the staging area cannot grow without bound.
|
|
215
|
+
for (let index = 0; index < 5; index += 1) await stageClipboardCopy(root, [sourceFile])
|
|
216
|
+
await pruneClipboardStage(root)
|
|
217
|
+
const batches = (await readdir(join(root, CLIPBOARD_STAGE_DIR), { withFileTypes: true }))
|
|
218
|
+
.filter((entry) => entry.isDirectory())
|
|
219
|
+
assert.ok(batches.length <= 3, 'only the recent batches survive')
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
test('only a COPY is staged; a cut still publishes the real file', async () => {
|
|
223
|
+
const source = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
|
|
224
|
+
assert.match(source, /if \(body\.cut !== true\) \{[\s\S]{0,600}stageClipboardCopy\(root, paths\)/,
|
|
225
|
+
'copy goes through the staging area')
|
|
226
|
+
assert.match(source, /published = stage\.staged/, 'the clipboard gets the staged paths, not the originals')
|
|
227
|
+
assert.match(source, /const mapping = await clipboardStageMapping\(root\)/, 'a read translates staged paths back')
|
|
228
|
+
assert.match(source, /files\.map\(\(path\) => mapping\.get\(resolve\(path\)\) \?\? path\)/)
|
|
229
|
+
assert.match(source, /if \(dirent\.name === IDE_STATE_DIR\) continue/, 'the state folder (trash/cache/stage) is never a tree row')
|
|
230
|
+
assert.match(source, /'\.dsh-ris-ide',/, 'the watcher ignores its churn')
|
|
231
|
+
})
|
|
232
|
+
|
|
233
|
+
test('the copy route reads the workspace scope the page actually sends', async () => {
|
|
234
|
+
const source = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
|
|
235
|
+
// The page builds `?sessionId&cwd` (see `clipboardQuery`). Reading only the JSON
|
|
236
|
+
// body made every real copy fail with "复制到系统剪贴板需要 sessionId".
|
|
237
|
+
assert.match(source, /const scope = clipboardScope\(body, url\)/, 'the route parses the query string')
|
|
238
|
+
assert.match(source, /const root = clipboardRoot\(ctx, scope\.sessionId, scope\.cwd\)/, 'the scope feeds the staging root')
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
test('a copy that cannot be staged fails instead of publishing the originals', async () => {
|
|
242
|
+
const source = await readFile(new URL('../lib/index.js', import.meta.url), 'utf8')
|
|
243
|
+
// The old shape — stage, and on failure quietly hand out the real paths — is the
|
|
244
|
+
// silent downgrade that lets Explorer move files out of the workspace.
|
|
245
|
+
assert.equal(/stage === null[\s\S]{0,160}published = paths/.test(source), false,
|
|
246
|
+
'no silent fallback to the originals')
|
|
247
|
+
assert.equal(/stageClipboardCopy\(root, paths\)\n\s+if \(stage === null\)/.test(source), false)
|
|
248
|
+
assert.match(source, /超过 \$\{megabytes\} MB,已取消复制到系统剪贴板/, 'the toast stays short but says the copy was cancelled')
|
|
249
|
+
assert.match(source, /复制到系统剪贴板需要 sessionId/, 'without a workspace there is nothing to stage into')
|
|
250
|
+
// A real refusal is an error the page reports, not a "copied" toast.
|
|
251
|
+
const client = await readFile(new URL('../lib/client.js', import.meta.url), 'utf8')
|
|
252
|
+
assert.match(client, /notify\('没能放到系统剪贴板:' \+ messageOf\(problem\)/)
|
|
253
|
+
assert.match(client, /if \(code === 'unsupported'\) \{/, 'only "no backend at all" still writes the paths as text')
|
|
254
|
+
})
|
|
@@ -22,7 +22,8 @@ import { __test } from '../lib/index.js'
|
|
|
22
22
|
|
|
23
23
|
const {
|
|
24
24
|
handleRequest, searchWorkspaceContent,
|
|
25
|
-
CONTENT_SEARCH_PATH,
|
|
25
|
+
CONTENT_SEARCH_PATH, SEARCH_STREAM_PATH, CONTENT_SEARCH_STREAM_PATH,
|
|
26
|
+
RUN_TEST_PATH, START_PATH, STOP_PATH, PROGRAMS_PATH,
|
|
26
27
|
runTestOutput, RUN_TEST_HEAD_CHARS, RUN_TEST_TAIL_CHARS, RUN_TEST_MAX_RECORDS,
|
|
27
28
|
HARD_MAX_BYTES, PID_SUFFIX, IS_WINDOWS,
|
|
28
29
|
} = __test
|
|
@@ -157,6 +158,129 @@ test('GET /search-content serves hits and rejects a missing q or the wrong metho
|
|
|
157
158
|
}, root)
|
|
158
159
|
})
|
|
159
160
|
|
|
161
|
+
// ── Streamed search routes (async paging) ──────────────────────────────────
|
|
162
|
+
|
|
163
|
+
/** Read one NDJSON search answer into its frames, in arrival order. */
|
|
164
|
+
async function readNdjson(response) {
|
|
165
|
+
const frames = []
|
|
166
|
+
const reader = response.body.getReader()
|
|
167
|
+
const decoder = new TextDecoder()
|
|
168
|
+
let buffer = ''
|
|
169
|
+
for (;;) {
|
|
170
|
+
const { done, value } = await reader.read()
|
|
171
|
+
if (done) break
|
|
172
|
+
buffer += decoder.decode(value, { stream: true })
|
|
173
|
+
let index = buffer.indexOf('\n')
|
|
174
|
+
while (index !== -1) {
|
|
175
|
+
const line = buffer.slice(0, index).trim()
|
|
176
|
+
buffer = buffer.slice(index + 1)
|
|
177
|
+
if (line !== '') frames.push(JSON.parse(line))
|
|
178
|
+
index = buffer.indexOf('\n')
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return frames
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Two nested repo roots (`aa-repo`, `bb-repo`), each holding one matching file. */
|
|
185
|
+
async function makeTwoRootFixture(label) {
|
|
186
|
+
const root = await mkdtemp(join(scratch, `${label}-`))
|
|
187
|
+
for (const name of ['aa-repo', 'bb-repo']) {
|
|
188
|
+
const dir = join(root, name)
|
|
189
|
+
await mkdir(dir, { recursive: true })
|
|
190
|
+
await writeFile(join(dir, 'agent-one.txt'), 'needle one\nsecond needle\n')
|
|
191
|
+
await writeFile(join(dir, 'other.txt'), 'nothing here\n')
|
|
192
|
+
execFileSync('git', ['init', '-q'], { cwd: dir })
|
|
193
|
+
execFileSync('git', ['add', '-A'], { cwd: dir })
|
|
194
|
+
}
|
|
195
|
+
return root
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
test('createOrderedPages spends the row budget in root order, not arrival order', () => {
|
|
199
|
+
// Roots answer concurrently: rows of a LATER root must never consume the budget
|
|
200
|
+
// before an earlier root has been emitted, or the streamed prefix would differ
|
|
201
|
+
// from the (sequential) batch answer. Roots 2 and 1 fill their buffers first.
|
|
202
|
+
const pages = []
|
|
203
|
+
let full = 0
|
|
204
|
+
const emitter = __test.createOrderedPages(3, 2, (page) => pages.push(page), { maxItems: 3, onFull: () => { full += 1 } })
|
|
205
|
+
emitter.push(2, ['c1', 'c2', 'c3'])
|
|
206
|
+
emitter.push(1, ['b1', 'b2', 'b3'])
|
|
207
|
+
assert.deepEqual(pages, [], 'a non-head root only buffers, whatever arrives first')
|
|
208
|
+
emitter.push(0, ['a1', 'a2', 'a3'])
|
|
209
|
+
assert.deepEqual(pages, [['a1', 'a2']], 'the head root pages as it fills')
|
|
210
|
+
emitter.finish(0)
|
|
211
|
+
assert.deepEqual(pages, [['a1', 'a2'], ['a3']], 'its remainder goes out as a short page')
|
|
212
|
+
assert.equal(full, 1, 'the third row spends the budget and closes the emitter')
|
|
213
|
+
assert.equal(emitter.total(), 3)
|
|
214
|
+
assert.equal(emitter.isClosed(), true)
|
|
215
|
+
// Nothing leaks in after the budget is spent, and later roots cannot emit.
|
|
216
|
+
emitter.push(2, ['c4'])
|
|
217
|
+
emitter.finish(1)
|
|
218
|
+
emitter.finish(2)
|
|
219
|
+
assert.deepEqual(pages, [['a1', 'a2'], ['a3']])
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
test('GET /search/stream pages the filename matches in tree order and ends with done', async () => {
|
|
223
|
+
const root = await makeTwoRootFixture('stream-name')
|
|
224
|
+
await withServer(async ({ base }) => {
|
|
225
|
+
const response = await fetch(`${base}${SEARCH_STREAM_PATH}?sessionId=s1&q=agent&pageSize=1&limit=10`)
|
|
226
|
+
assert.equal(response.status, 200)
|
|
227
|
+
assert.match(String(response.headers.get('content-type')), /application\/x-ndjson/)
|
|
228
|
+
const frames = await readNdjson(response)
|
|
229
|
+
assert.equal(frames[0].type, 'start')
|
|
230
|
+
assert.equal(frames[0].root, root)
|
|
231
|
+
assert.equal(frames[0].repoCount, 2, 'two nested repo roots are searched')
|
|
232
|
+
const pages = frames.filter((frame) => frame.type === 'page')
|
|
233
|
+
assert.equal(pages.length, 2, 'pageSize=1 ⇒ one page per matching root')
|
|
234
|
+
assert.deepEqual(pages.map((page) => page.items), [
|
|
235
|
+
[join(root, 'aa-repo', 'agent-one.txt')],
|
|
236
|
+
[join(root, 'bb-repo', 'agent-one.txt')],
|
|
237
|
+
], 'pages follow the repo-root order, never the completion order')
|
|
238
|
+
const done = frames.at(-1)
|
|
239
|
+
assert.equal(done.type, 'done')
|
|
240
|
+
assert.equal(done.matches, 2)
|
|
241
|
+
assert.equal(done.files, 4)
|
|
242
|
+
assert.equal(done.truncated, false)
|
|
243
|
+
}, root)
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
test('GET /search-content/stream pages grep hits and keeps the batch validation', async () => {
|
|
247
|
+
const root = await makeTwoRootFixture('stream-content')
|
|
248
|
+
await withServer(async ({ base }) => {
|
|
249
|
+
const response = await fetch(`${base}${CONTENT_SEARCH_STREAM_PATH}?sessionId=s1&q=needle&pageSize=1&limit=10`)
|
|
250
|
+
assert.equal(response.status, 200)
|
|
251
|
+
const frames = await readNdjson(response)
|
|
252
|
+
const hits = frames.filter((frame) => frame.type === 'page').flatMap((frame) => frame.items)
|
|
253
|
+
assert.deepEqual(hits.map((hit) => `${hit.path.slice(root.length + 1)}:${hit.line}`), [
|
|
254
|
+
'aa-repo/agent-one.txt:1',
|
|
255
|
+
'aa-repo/agent-one.txt:2',
|
|
256
|
+
'bb-repo/agent-one.txt:1',
|
|
257
|
+
'bb-repo/agent-one.txt:2',
|
|
258
|
+
])
|
|
259
|
+
assert.deepEqual(frames.at(-1), { type: 'done', files: 2, matches: 4, truncated: false })
|
|
260
|
+
|
|
261
|
+
// A content search still needs a query, and the stream routes stay GET-only.
|
|
262
|
+
const missingQ = await fetch(`${base}${CONTENT_SEARCH_STREAM_PATH}?sessionId=s1`)
|
|
263
|
+
assert.equal(missingQ.status, 400)
|
|
264
|
+
assert.equal((await missingQ.json()).code, 'bad-request')
|
|
265
|
+
const wrongMethod = await postJson(base, SEARCH_STREAM_PATH, { sessionId: 's1', q: 'needle' })
|
|
266
|
+
assert.equal(wrongMethod.status, 405)
|
|
267
|
+
const noSession = await fetch(`${base}${SEARCH_STREAM_PATH}?q=needle`)
|
|
268
|
+
assert.equal(noSession.status, 400)
|
|
269
|
+
}, root)
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
test('GET /search/stream stops early at limit and reports truncated', async () => {
|
|
273
|
+
const root = await makeTwoRootFixture('stream-limit')
|
|
274
|
+
await withServer(async ({ base }) => {
|
|
275
|
+
const response = await fetch(`${base}${SEARCH_STREAM_PATH}?sessionId=s1&q=agent&pageSize=2&limit=1`)
|
|
276
|
+
const frames = await readNdjson(response)
|
|
277
|
+
const items = frames.filter((frame) => frame.type === 'page').flatMap((frame) => frame.items)
|
|
278
|
+
assert.equal(items.length, 1)
|
|
279
|
+
assert.equal(frames.at(-1).type, 'done')
|
|
280
|
+
assert.equal(frames.at(-1).truncated, true, 'limit=1 is reached before the second root answers')
|
|
281
|
+
}, root)
|
|
282
|
+
})
|
|
283
|
+
|
|
160
284
|
// ── Run-test route: validation ──────────────────────────────────────────────
|
|
161
285
|
|
|
162
286
|
/** A cwd holding one real Maven module (`mod/pom.xml`). */
|