-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathsmoke.spec.ts
More file actions
1301 lines (1227 loc) · 56.1 KB
/
Copy pathsmoke.spec.ts
File metadata and controls
1301 lines (1227 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Smoke spec: mounts the host plugin against a minimal fake context and
* exercises the real integrations — route registration, git against the
* actual repository, and a real directory listing. Runs with `pnpm test`.
*/
import { describe, expect, it, vi } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve as resolvePath } from 'node:path'
import { SettingsConflictError, type SettingsNamespace } from '@deepseek-ai/dsh-settings'
import { apply, mediaTypeForPath } from '../src/index.ts'
import { encodeHtmlUrl } from '../src/html-route.ts'
import * as git from '../src/git.ts'
import { listDirectory } from '../src/fs-tree.ts'
import { defaultShell, PtyManager, type SidebarPty } from '../src/pty-manager.ts'
import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
/** Symlink creation may require elevated privileges on Windows. */
const canCreateSymlink = (() => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-security-probe-'))
try {
mkdirSync(join(dir, 'target'))
symlinkSync(join(dir, 'target'), join(dir, 'link'))
return true
} catch {
return false
} finally {
rmSync(dir, { recursive: true, force: true })
}
})()
interface FakeContext {
webRuntime: { trustedHosts: readonly string[] }
webServer: {
register: (route: SidebarWebRoute) => () => void
registerUpgrade: (route: SidebarWebUpgradeRoute) => () => void
}
sessions: { get: (id: string) => { header: { cwd?: string } } | undefined }
tools: { register: (tool: unknown) => () => void }
effect: (fn: () => void | (() => void), label?: string) => void
/** The settings service never appears in the smoke context: the inject
* callback must never run (mirror of cordis' service-less inject). */
inject: (deps: readonly string[], callback: (sctx: never) => void) => () => void
/** Optional services (jobs/agents) are read lazily; absent → undefined. */
get: (key: string) => undefined
}
/**
* The login-shell test spawns a real pty whose bash may still be writing to
* the temp HOME (history files, etc.) when `disposeAll()` returns — `close()`
* only requests the kill and the process exit lands asynchronously in
* `onExit`. Deleting the directory immediately then races the shell and
* fails with ENOTEMPTY on CI. Wait for the spawned handle to report `exited`
* (bounded), then remove with a short retry loop as a belt-and-braces
* fallback for any straggler fd.
*/
async function rmTempDirAfterPtyExit(handle: { exited: boolean }, dir: string): Promise<void> {
const deadline = Date.now() + 2000
while (Date.now() < deadline && !handle.exited) {
await new Promise((resolve) => setTimeout(resolve, 50))
}
for (let attempt = 0; ; attempt++) {
try {
rmSync(dir, { recursive: true, force: true })
return
} catch (error) {
const busy = (error as NodeJS.ErrnoException).code === 'ENOTEMPTY' || (error as NodeJS.ErrnoException).code === 'EBUSY'
if (!busy || attempt >= 4) throw error
await new Promise((resolve) => setTimeout(resolve, 100 * (attempt + 1)))
}
}
}
describe('host plugin smoke', () => {
it('serves PDF with the browser-native content type', () => {
expect(mediaTypeForPath('/work/report.PDF')).toBe('application/pdf')
expect(mediaTypeForPath('/work/archive.bin')).toBe('application/octet-stream')
})
it('mounts the fenced routes', () => {
const routes: SidebarWebRoute[] = []
const upgrades: SidebarWebUpgradeRoute[] = []
const effects: Array<() => void | (() => void)> = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
webServer: {
register: (route) => { routes.push(route); return () => {} },
registerUpgrade: (route) => { upgrades.push(route); return () => {} },
},
sessions: { get: () => undefined },
tools: { register: () => () => {} },
// The DSH-vendored cordis runs the registration effect immediately and
// keeps its cleanup for disposal.
effect: (fn) => {
const cleanup = fn()
if (typeof cleanup === 'function') effects.push(cleanup)
},
// No settings service in the smoke context: the registration callback
// never runs (cordis' service-less inject behaves the same).
inject: () => () => {},
// No jobs/agents services: the jobs routes degrade to a 503.
get: () => undefined,
}
apply(ctx as never)
expect(routes.map(route => route.path)).toEqual([
'/sidebar/api',
'/sidebar/upload',
'/sidebar/bundle',
'/sidebar/file',
'/sidebar/html',
])
expect(upgrades.map(route => route.path)).toEqual(['/sidebar/ws/terminal', '/sidebar/ws/agent-terminals', '/sidebar/ws/agent-opens'])
// Teardown runs without throwing (pty manager has nothing open).
for (const cleanup of effects) cleanup()
})
it('serves HTML previews as UTF-8 without changing the file bytes', async () => {
const directory = mkdtempSync(join(tmpdir(), 'dsh-sidebar-html-utf8-'))
const path = join(directory, 'fragment.html')
const source = Buffer.from('<div>排序算法可视化</div>', 'utf8')
writeFileSync(path, source)
const routes: SidebarWebRoute[] = []
const effects: Array<() => void | (() => void)> = []
const ctx: FakeContext = {
webRuntime: { trustedHosts: [] },
webServer: {
register: (route) => { routes.push(route); return () => {} },
registerUpgrade: () => () => {},
},
sessions: { get: () => ({ header: { cwd: directory } }) },
tools: { register: () => () => {} },
effect: (fn) => {
const cleanup = fn()
if (typeof cleanup === 'function') effects.push(cleanup)
},
inject: () => () => {},
get: () => undefined,
}
try {
apply(ctx as never)
const route = routes.find(candidate => candidate.path === '/sidebar/html')!
const req = {
method: 'GET',
url: encodeHtmlUrl('s-html', path),
headers: { host: '127.0.0.1:3080' },
} as never
const response: { status?: number; headers?: Record<string, string>; chunks: Buffer[] } = { chunks: [] }
const res = {
writeHead: (status: number, headers?: Record<string, string>) => {
response.status = status
response.headers = headers
},
end: (chunk?: string | Buffer) => {
if (chunk !== undefined) response.chunks.push(Buffer.from(chunk))
},
} as never
await route.handler(req, res)
expect(response.status).toBe(200)
expect(Buffer.concat(response.chunks)).toEqual(source)
expect(response.headers?.['content-type']).toBe('text/html; charset=utf-8')
} finally {
for (const cleanup of effects) cleanup()
rmSync(directory, { recursive: true, force: true })
}
})
it('runs git status/log/branches against this repository', async () => {
const cwd = process.cwd()
const status = await git.status(cwd)
expect(status.isRepo).toBe(true)
expect(typeof status.branch).toBe('string')
expect(Array.isArray(status.entries)).toBe(true)
const log = await git.log(cwd)
expect(log.length).toBeGreaterThan(0)
expect(log[0]!.hash).toMatch(/^[0-9a-f]{7,}$/)
const branches = await git.branches(cwd)
expect(branches.names).toContain(branches.current)
})
it('enriches the log (full hash + refs) and renders commit diffs', async () => {
const cwd = process.cwd()
const log = await git.log(cwd)
const first = log[0]!
expect(first.hashFull).toMatch(/^[0-9a-f]{40}$/)
expect(typeof first.refs).toBe('string')
const patch = await git.commitDiff(cwd, first.hashFull)
expect(patch).toContain('diff --git')
})
it('pages the log lazily with skip/count', async () => {
const cwd = process.cwd()
const first = await git.log(cwd, 5, 0)
expect(first).toHaveLength(5)
const second = await git.log(cwd, 5, 5)
expect(second).toHaveLength(5)
// The pages are disjoint windows over the same ordered history.
expect(first[0]!.hashFull).not.toBe(second[0]!.hashFull)
const all = await git.log(cwd, 10, 0)
expect(all.slice(0, 5)).toEqual(first)
expect(all.slice(5)).toEqual(second)
// A skip past the end returns an empty page (the lazy loader's stop sign).
expect(await git.log(cwd, 5, 10_000)).toEqual([])
})
it('pty manager releases the quota on close and respawns after exit', async () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const first = manager.open('s1', 't1', process.cwd(), 80, 24)
expect(manager.keysOf('s1')).toHaveLength(1)
// Tab-close semantics (close frame): quota released immediately.
manager.scheduleClose(first.key, 0)
await new Promise(resolve => setTimeout(resolve, 50))
expect(manager.keysOf('s1')).toHaveLength(0)
// Reopen spawns a fresh process.
const second = manager.open('s1', 't1', process.cwd(), 80, 24)
expect(second).not.toBe(first)
expect(manager.keysOf('s1')).toHaveLength(1)
// After the shell exits, a reconnect respawns instead of reusing the dead handle.
second.pty.write('exit\r')
const deadline = Date.now() + 5000
while (!second.exited && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 100))
}
expect(second.exited).toBe(true)
const third = manager.open('s1', 't1', process.cwd(), 80, 24)
expect(third.exited).toBe(false)
expect(third).not.toBe(second)
} finally {
manager.disposeAll()
}
})
it('pty manager: exited zombie handles do not consume the quota', async () => {
const manager = new PtyManager(defaultShell(), 1)
try {
const first = manager.open('s3', 't1', process.cwd(), 80, 24)
first.pty.write('exit\r')
const deadline = Date.now() + 5000
while (!first.exited && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 100))
}
expect(first.exited).toBe(true)
// Quota is 1; the exited handle is swept, so a NEW tab can still spawn.
const second = manager.open('s3', 't2', process.cwd(), 80, 24)
expect(second.exited).toBe(false)
expect(manager.keysOf('s3')).toHaveLength(1)
} finally {
manager.disposeAll()
}
})
it('pty manager: a reconnect within the grace period cancels the pending close', async () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const handle = manager.open('s2', 't1', process.cwd(), 80, 24)
manager.scheduleClose(handle.key, 200)
manager.open('s2', 't1', process.cwd(), 80, 24)
await new Promise(resolve => setTimeout(resolve, 400))
expect(manager.get(handle.key)).toBeDefined()
} finally {
manager.disposeAll()
}
})
it('pty manager: a parked pty survives past the reconnect grace (session switch)', async () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const handle = manager.open('s2', 't1', process.cwd(), 80, 24)
manager.park(handle.key)
expect(manager.isParked(handle.key)).toBe(true)
// A parked pty does NOT enter the grace countdown — it stays alive
// well past any realistic reconnectGraceMs.
await new Promise(resolve => setTimeout(resolve, 300))
expect(manager.get(handle.key)).toBeDefined()
expect(manager.isParked(handle.key)).toBe(true)
} finally {
manager.disposeAll()
}
})
it('pty manager: a reconnecting view clears the parked state (switch back)', () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const handle = manager.open('s2', 't1', process.cwd(), 80, 24)
manager.park(handle.key)
expect(manager.isParked(handle.key)).toBe(true)
// open() calls cancelClose(), which clears the parked state — the
// user switched back to the session and the view reattached.
manager.open('s2', 't1', process.cwd(), 80, 24)
expect(manager.isParked(handle.key)).toBe(false)
expect(manager.get(handle.key)).toBeDefined()
} finally {
manager.disposeAll()
}
})
it('pty manager: an explicit close frame on a parked pty still kills it', async () => {
const manager = new PtyManager(defaultShell(), 3)
try {
const handle = manager.open('s2', 't1', process.cwd(), 80, 24)
manager.park(handle.key)
// The user switched back and closed the tab — scheduleClose (the
// close-frame handler) clears the parked state and kills the pty.
manager.scheduleClose(handle.key, 0)
expect(manager.isParked(handle.key)).toBe(false)
await new Promise(resolve => setTimeout(resolve, 50))
expect(manager.get(handle.key)).toBeUndefined()
} finally {
manager.disposeAll()
}
})
it('pty manager: park on an unknown key is a no-op', () => {
const manager = new PtyManager(defaultShell(), 3)
expect(() => manager.park('s2:nonexistent')).not.toThrow()
expect(manager.isParked('s2:nonexistent')).toBe(false)
})
it('pty manager: reopening with a different cwd respawns in the new directory', async () => {
const manager = new PtyManager(defaultShell(), 3)
// A real second directory: os.tmpdir() exists on every platform ('/tmp'
// does not exist on Windows).
const other = tmpdir()
try {
const first = manager.open('s4', 't1', process.cwd(), 80, 24)
// The hydrate race: the first connect fell back to the process cwd,
// the reconnect carries the session's real cwd — the shell must move.
const second = manager.open('s4', 't1', other, 80, 24)
expect(second).not.toBe(first)
expect(second.cwd).toBe(other)
expect(manager.keysOf('s4')).toHaveLength(1)
// A same-cwd reconnect reattaches without respawning.
const third = manager.open('s4', 't1', other, 80, 24)
expect(third).toBe(second)
expect(manager.keysOf('s4')).toHaveLength(1)
} finally {
manager.disposeAll()
}
})
it.skipIf(process.platform === 'win32')('spawns the shell as a login shell (loads ~/.profile)', async () => {
const home = mkdtempSync(join(tmpdir(), 'dsh-sidebar-login-'))
const previousHome = process.env.HOME
let handle: SidebarPty | undefined
try {
// A login bash reads ~/.profile (a non-login interactive bash reads
// ~/.bashrc instead), so this marker proves the spawn used a login
// argv — the terminal-emulator behavior the tab should match.
writeFileSync(join(home, '.profile'), 'export DSH_LOGIN_MARKER=loaded-from-profile\n')
process.env.HOME = home
const manager = new PtyManager('/bin/bash', 3)
try {
handle = manager.open('s5', 't1', process.cwd(), 80, 24)
handle.pty.write('echo $DSH_LOGIN_MARKER\r')
const deadline = Date.now() + 5000
while (!handle.transcript.includes('loaded-from-profile') && Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, 50))
}
expect(handle.transcript).toContain('loaded-from-profile')
} finally {
manager.disposeAll()
}
} finally {
if (previousHome === undefined) delete process.env.HOME
else process.env.HOME = previousHome
await rmTempDirAfterPtyExit(handle ?? { exited: true }, home)
}
})
it('lists the repository root level', async () => {
const listing = await listDirectory(process.cwd(), 1000)
expect(listing.entries.some(entry => entry.name === 'src' && entry.isDir)).toBe(true)
expect(listing.entries.some(entry => entry.name === 'package.json' && !entry.isDir)).toBe(true)
expect(listing.truncated).toBe(false)
})
})
/**
* Destructive git operations (discard / revert / cherry-pick) run against a
* throwaway repository under the OS temp dir — never the plugin repo. The
* fixture's commit identity comes from the GIT_AUTHOR / GIT_COMMITTER
* environment variables, confined to the fixture process: no git config is
* touched anywhere (the plugin never sets an identity, and neither does its
* test fixture).
*/
describe('git destructive operations (scratch repository)', () => {
const FIXTURE_IDENTITY = {
GIT_AUTHOR_NAME: 'dsh-better-sidebar-test',
GIT_AUTHOR_EMAIL: 'test@dsh.invalid',
GIT_COMMITTER_NAME: 'dsh-better-sidebar-test',
GIT_COMMITTER_EMAIL: 'test@dsh.invalid',
}
const gitRun = (cwd: string, args: string[]): string => {
const result = spawnSync('git', ['-C', cwd, '--no-pager', '-c', 'color.ui=false', ...args], {
encoding: 'utf8',
env: { ...process.env, ...FIXTURE_IDENTITY },
})
if (result.status !== 0) {
throw new Error(result.stderr || `git ${args[0] ?? ''} exited with ${String(result.status)}`)
}
return result.stdout
}
/** A fresh repo on branch `main` with one committed file `a.txt`. */
const makeScratchRepo = (): string => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-git-'))
gitRun(dir, ['init', '-q'])
// Pin the eol policy: Git for Windows defaults to core.autocrlf=true
// (system gitconfig on the CI runner, and many dev machines), which
// smudges LF→CRLF on every index restore and breaks the byte-exact
// assertions below. The destructive-op behavior under test is orthogonal
// to the machine's eol policy.
gitRun(dir, ['config', 'core.autocrlf', 'false'])
gitRun(dir, ['checkout', '-q', '-b', 'main'])
writeFileSync(join(dir, 'a.txt'), 'one\ntwo\nthree\n')
gitRun(dir, ['add', '-A'])
gitRun(dir, ['commit', '-q', '-m', 'base'])
return dir
}
it('discard restores the worktree file from the index (staged changes kept)', async () => {
const dir = makeScratchRepo()
try {
// Unstaged-only changes: fully reverts to the committed content.
writeFileSync(join(dir, 'a.txt'), 'one\nCHANGED\nthree\n')
await git.discard(dir, 'a.txt')
expect(readFileSync(join(dir, 'a.txt'), 'utf8')).toBe('one\ntwo\nthree\n')
// Staged changes: the worktree snaps back to the STAGED content and
// the index is untouched (`git checkout -- <path>` restores from the
// index — VSCode's "Discard Changes" semantics).
writeFileSync(join(dir, 'a.txt'), 'one\nCHANGED\nthree\n')
gitRun(dir, ['add', '-A'])
await git.discard(dir, 'a.txt')
expect(readFileSync(join(dir, 'a.txt'), 'utf8')).toBe('one\nCHANGED\nthree\n')
const staged = await git.diff(dir, 'a.txt', true)
expect(staged).toContain('-two')
expect(staged).toContain('+CHANGED')
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('revert creates a revert commit', async () => {
const dir = makeScratchRepo()
try {
writeFileSync(join(dir, 'a.txt'), 'one\nTWO\nthree\n')
gitRun(dir, ['add', '-A'])
gitRun(dir, ['commit', '-q', '-m', 'change'])
const featureHash = (await git.log(dir))[0]!.hashFull
await git.revert(dir, featureHash)
expect(readFileSync(join(dir, 'a.txt'), 'utf8')).toBe('one\ntwo\nthree\n')
expect((await git.log(dir))[0]!.subject).toBe('Revert "change"')
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('cherry-pick applies a commit from another branch', async () => {
const dir = makeScratchRepo()
try {
gitRun(dir, ['checkout', '-q', '-b', 'feature'])
writeFileSync(join(dir, 'b.txt'), 'feature work\n')
gitRun(dir, ['add', '-A'])
gitRun(dir, ['commit', '-q', '-m', 'feature work'])
const featureHash = (await git.log(dir))[0]!.hashFull
gitRun(dir, ['checkout', '-q', 'main'])
await git.cherryPick(dir, featureHash)
expect(readFileSync(join(dir, 'b.txt'), 'utf8')).toBe('feature work\n')
expect((await git.log(dir))[0]!.subject).toBe('feature work')
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
it('reports a failing destructive operation as a GitCommandError', async () => {
const dir = makeScratchRepo()
try {
// An unknown revision fails before touching anything.
await expect(git.revert(dir, 'deadbeef00000000000000000000000000000000')).rejects.toThrow()
await expect(git.cherryPick(dir, 'deadbeef00000000000000000000000000000000')).rejects.toThrow()
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
})
describe('session cwd resolution over the API route', () => {
interface CtxOverrides {
sessions?: { get: (id: string) => { header: { cwd?: string } } | undefined }
sessionPersistence?: { inspect: (id: string) => Promise<{ meta: { cwd?: string } }> }
fs?: {
resolve(path: string): Promise<{ targetKey: string; displayPath: string }>
contains(parent: { targetKey: string }, child: { targetKey: string }): boolean
lstat(path: string): Promise<{ type: 'file' | 'directory' | 'symlink' | 'other' } | undefined>
stat(target: { targetKey: string }): Promise<{ type: 'file' | 'directory' | 'other' } | undefined>
listDir(target: { targetKey: string }): Promise<Array<{
name: string
type: 'file' | 'directory' | 'other'
target: { targetKey: string; displayPath: string }
}>>
}
}
const mountAll = (overrides: CtxOverrides = {}): SidebarWebRoute[] => {
const routes: SidebarWebRoute[] = []
const localFs = {
resolve: async (path: string) => {
const absolute = resolvePath(path)
const canonical = await import('node:fs/promises').then(({ realpath }) => realpath(absolute))
return { targetKey: canonical, displayPath: absolute }
},
contains: (parent: { targetKey: string }, child: { targetKey: string }) => child.targetKey === parent.targetKey || child.targetKey.startsWith(`${parent.targetKey}${process.platform === 'win32' ? '\\' : '/'}`),
lstat: async (path: string) => {
const info = await import('node:fs/promises').then(fs => fs.lstat(path)).catch(() => undefined)
return info === undefined ? undefined : { type: info.isSymbolicLink() ? 'symlink' as const : info.isDirectory() ? 'directory' as const : info.isFile() ? 'file' as const : 'other' as const }
},
stat: async (target: { targetKey: string }) => {
const info = await import('node:fs/promises').then(fs => fs.stat(target.targetKey)).catch(() => undefined)
return info === undefined ? undefined : { type: info.isDirectory() ? 'directory' as const : info.isFile() ? 'file' as const : 'other' as const }
},
listDir: async (target: { targetKey: string; displayPath: string }) => {
const entries = await import('node:fs/promises').then(fs => fs.readdir(target.targetKey, { withFileTypes: true }))
return Promise.all(entries.map(async entry => ({
name: entry.name,
type: entry.isDirectory() ? 'directory' as const : entry.isFile() ? 'file' as const : 'other' as const,
target: await localFs.resolve(join(target.displayPath, entry.name)),
})))
},
}
const ctx = {
webRuntime: { trustedHosts: [] },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
},
sessions: overrides.sessions ?? { get: () => undefined },
fs: overrides.fs ?? localFs,
tools: { register: () => () => {} },
// The vendored cordis runs registration effects immediately.
effect: (fn: () => void | (() => void)) => { fn() },
// No settings service: the namespace registration never runs.
inject: () => () => {},
// No jobs/agents services in the smoke context: the routes degrade.
get: (key: string) => key === 'sessionPersistence' ? overrides.sessionPersistence : undefined,
}
apply(ctx as never)
return routes
}
const mount = (overrides: CtxOverrides = {}): SidebarWebRoute => mountAll(overrides).find(route => route.path === '/sidebar/api')!
const invoke = async (
route: SidebarWebRoute,
method: string,
payload: unknown,
): Promise<{ ok: boolean; status: number; value?: { cwd: string }; error?: { code?: string; message: string } }> => {
const body = Buffer.from(JSON.stringify(payload))
const req = {
method: 'POST',
url: `/sidebar/api/${method}`,
headers: { host: '127.0.0.1:3080' },
[Symbol.asyncIterator]: async function* () { yield body },
} as never
const out: { status: number; body: string } = { status: 200, body: '' }
const res = {
writeHead: (status: number) => { out.status = status },
end: (chunk: unknown) => { out.body += String(chunk ?? '') },
} as never
await route.handler(req, res)
return { ...JSON.parse(out.body) as { ok: boolean; value?: { cwd: string }; error?: { code?: string; message: string } }, status: out.status }
}
const invokeGet = async (route: SidebarWebRoute, url: string): Promise<{ status: number; body: string }> => {
const out: { status: number; body: string } = { status: 200, body: '' }
const req = { method: 'GET', url, headers: { host: '127.0.0.1:3080' } } as never
const res = {
writeHead: (status: number) => { out.status = status },
end: (chunk: unknown) => { out.body += String(chunk ?? '') },
} as never
await route.handler(req, res)
return out
}
it('uses the client summary cwd while the session is detached', async () => {
const route = mount()
const result = await invoke(route, 'session.cwd', { sessionId: 's-detached', cwd: '/tmp/summary-cwd' })
expect(result.ok).toBe(true)
// The summary cwd passes through requireAbsolute (platform resolve), so
// the expectation follows the platform's own normalization.
expect(result.value?.cwd).toBe(resolvePath('/tmp/summary-cwd'))
})
it('falls back to the process cwd with no summary cwd', async () => {
const route = mount()
const result = await invoke(route, 'session.cwd', { sessionId: 's-unknown' })
expect(result.ok).toBe(true)
expect(result.value?.cwd).toBe(process.cwd())
})
it('resolves a cold (detached) session cwd through the persistence index', async () => {
// Regression: a detached first request (session not yet attached, no
// client cwd) must resolve the cwd from the session-persistence index
// instead of the host process cwd. On Windows the host process cwd is
// the DSH source root (dsh.cmd's `pushd`), so every user-project path
// was misclassified as "outside workspace" by the realpath guard.
const coldCwd = resolvePath('/cold-project-cwd')
const route = mount({
sessionPersistence: {
inspect: async (id) => ({
meta: id === 's-cold' ? { cwd: coldCwd } : {},
}),
},
})
const result = await invoke(route, 'session.cwd', { sessionId: 's-cold' })
expect(result.ok).toBe(true)
expect(result.value?.cwd).toBe(coldCwd)
})
it('rejects a relative cwd from the persistence index', async () => {
// A buggy / corrupt persistence layer that stored a relative cwd must
// be rejected by requireAbsolute instead of flowing into the workspace
// guard, where it would be resolved against the host process cwd and
// potentially recreate the original "outside workspace" misclassification.
const route = mount({
sessionPersistence: {
inspect: async () => ({ meta: { cwd: 'relative/path' } }),
},
})
const result = await invoke(route, 'session.cwd', { sessionId: 's-bad' })
expect(result.ok).toBe(false)
expect(result.error?.message).toMatch(/invalid working directory/)
})
it('falls back to the process cwd when persistence has no cwd for the session', async () => {
const route = mount({
sessionPersistence: {
inspect: async () => ({ meta: {} }),
},
})
const result = await invoke(route, 'session.cwd', { sessionId: 's-blank' })
expect(result.ok).toBe(true)
expect(result.value?.cwd).toBe(process.cwd())
})
it('prefers the attached session header over the client summary', async () => {
const route = mount({
sessions: {
get: (id) => id === 's-attached' ? { header: { cwd: '/attached-cwd' } } : undefined,
},
})
const result = await invoke(route, 'session.cwd', { sessionId: 's-attached', cwd: '/tmp/summary-cwd' })
expect(result.ok).toBe(true)
expect(result.value?.cwd).toBe('/attached-cwd')
})
it('rejects a non-absolute client cwd', async () => {
const route = mount()
const result = await invoke(route, 'session.cwd', { sessionId: 's-detached', cwd: 'relative/path' })
expect(result.ok).toBe(false)
expect(result.error?.message).toMatch(/invalid working directory/)
})
it('pty.close releases a terminal key (and rejects a missing tab)', async () => {
const route = mount()
const result = await invoke(route, 'pty.close', { sessionId: 's-pty', tab: 't1' })
expect(result.ok).toBe(true)
const missing = await invoke(route, 'pty.close', { sessionId: 's-pty' })
expect(missing.ok).toBe(false)
})
it('git.diff resolves repo-relative paths (session in a subdirectory)', async () => {
// The plugin repo's status paths are relative to the repo top level
// (e.g. `src/git.ts`); a session whose cwd sits inside the repo must
// still load per-file diffs instead of failing with "not an absolute
// path". The session header points INTO the repository.
const route = mount({
sessions: {
get: () => ({ header: { cwd: join(process.cwd(), 'src') } }),
},
})
const result = await invoke(route, 'git.diff', { sessionId: 's-sub', path: 'src/git.ts', staged: false })
expect(result.ok).toBe(true)
const value = result as unknown as { ok: boolean; value?: { diff: string } }
expect(typeof value.value?.diff).toBe('string')
})
it('fs.read resolves repo-relative paths (untracked diff fallback)', async () => {
const route = mount({
sessions: {
get: () => ({ header: { cwd: join(process.cwd(), 'src') } }),
},
})
const result = await invoke(route, 'fs.read', { sessionId: 's-sub', path: 'src/git.ts' })
expect(result.ok).toBe(true)
const value = result as unknown as { ok: boolean; value?: { kind: string; content: string } }
expect(value.value?.kind).toBe('text')
expect(value.value?.content).toContain('runGit')
})
it('rejects repo-root-relative fs.read paths outside a nested session workspace', async () => {
const route = mount({
sessions: {
get: () => ({ header: { cwd: join(process.cwd(), 'src') } }),
},
})
const result = await invoke(route, 'fs.read', { sessionId: 's-sub', path: 'package.json' })
expect(result).toMatchObject({ ok: false, status: 403, error: { code: 'forbidden' } })
})
it('lists a routed SSH workspace instead of the empty local anchor', async () => {
const anchor = resolvePath('/home/me/.dsh/ssh-workspace-anchors/project')
const remoteRoot = 'ssh://gpu/work/project'
const fs = {
resolve: vi.fn(async (path: string) => ({
targetKey: path === anchor ? remoteRoot : `${remoteRoot}/${path.slice(anchor.length + 1)}`,
displayPath: path === anchor ? 'gpu:/work/project' : `gpu:/work/project/${path.slice(anchor.length + 1)}`,
})),
contains: vi.fn((parent: { targetKey: string }, child: { targetKey: string }) => child.targetKey === parent.targetKey || child.targetKey.startsWith(`${parent.targetKey}/`)),
lstat: vi.fn(async () => ({ type: 'directory' as const })),
stat: vi.fn(async () => ({ type: 'directory' as const })),
listDir: vi.fn(async () => [{
name: 'docs',
type: 'directory' as const,
target: { targetKey: `${remoteRoot}/docs`, displayPath: 'gpu:/work/project/docs' },
}]),
}
const route = mount({
sessions: { get: () => ({ header: { cwd: anchor } }) },
fs,
})
const tree = await invoke(route, 'fs.tree', { sessionId: 'ssh' }) as unknown as {
ok: boolean
value?: { entries: Array<{ name: string; path: string }> }
}
expect(tree.ok).toBe(true)
expect(tree.value?.entries).toEqual([expect.objectContaining({ name: 'docs', path: join(anchor, 'docs') })])
expect(fs.listDir).toHaveBeenCalledWith(expect.objectContaining({ targetKey: remoteRoot }))
})
it('rejects fs.tree paths outside the session workspace', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-security-'))
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
const outsideFile = join(outside, 'secret.txt')
writeFileSync(outsideFile, 'secret')
try {
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const tree = await invoke(route, 'fs.tree', { sessionId: 'security', path: outside })
expect(tree).toMatchObject({ ok: false, status: 403, error: { code: 'forbidden' } })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('rejects fs.read paths outside the session workspace', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-security-'))
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
const outsideFile = join(outside, 'secret.txt')
writeFileSync(outsideFile, 'secret')
try {
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const read = await invoke(route, 'fs.read', { sessionId: 'security', path: outsideFile })
expect(read).toMatchObject({ ok: false, status: 403, error: { code: 'forbidden' } })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('rejects fs.write paths outside the session workspace', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-security-'))
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
try {
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const write = await invoke(route, 'fs.write', { sessionId: 'security', path: join(outside, 'written.txt'), content: 'hack' })
expect(write).toMatchObject({ ok: false, status: 403, error: { code: 'forbidden' } })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('rejects media and HTML reads through a workspace symlink', async () => {
if (!canCreateSymlink) return
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-route-symlink-security-'))
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
const mediaPath = join(outside, 'secret.png')
const htmlPath = join(outside, 'secret.html')
writeFileSync(mediaPath, 'not an image')
writeFileSync(htmlPath, '<p>secret</p>')
try {
symlinkSync(outside, join(workspace, 'link'))
const routes = mountAll({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const media = routes.find(route => route.path === '/sidebar/file')!
const html = routes.find(route => route.path === '/sidebar/html')!
const mediaResult = await invokeGet(media, `/sidebar/file?sessionId=security&path=${encodeURIComponent(join(workspace, 'link', 'secret.png'))}`)
// Use the production encoder so the URL is well-formed on every
// platform (a Windows drive path needs the leading slash separator
// that a naive join-without-separator drops).
const htmlResult = await invokeGet(html, encodeHtmlUrl('security', join(workspace, 'link', 'secret.html')))
expect(mediaResult).toMatchObject({ status: 403 })
expect(JSON.parse(mediaResult.body)).toMatchObject({ ok: false, error: { code: 'forbidden' } })
expect(htmlResult).toMatchObject({ status: 403 })
expect(JSON.parse(htmlResult.body)).toMatchObject({ ok: false, error: { code: 'forbidden' } })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('keeps fs.tree missing-path failures as fs errors', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-security-'))
const workspace = join(root, 'workspace')
mkdirSync(workspace)
try {
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const tree = await invoke(route, 'fs.tree', { sessionId: 'security', path: join(workspace, 'missing') })
expect(tree).toMatchObject({ ok: false, status: 400, error: { code: 'fs-error' } })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it.skipIf(!canCreateSymlink)('rejects workspace symlinks that resolve outside the workspace', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-symlink-security-'))
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
writeFileSync(join(outside, 'secret.txt'), 'secret')
try {
symlinkSync(outside, join(workspace, 'link'))
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const tree = await invoke(route, 'fs.tree', { sessionId: 'security', path: join(workspace, 'link') })
expect(tree).toMatchObject({ ok: false, status: 403, error: { code: 'forbidden' } })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it.skipIf(!canCreateSymlink)('rejects fs.read through a workspace symlink', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-symlink-security-'))
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
writeFileSync(join(outside, 'secret.txt'), 'secret')
try {
symlinkSync(outside, join(workspace, 'link'))
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const read = await invoke(route, 'fs.read', { sessionId: 'security', path: join(workspace, 'link', 'secret.txt') })
expect(read).toMatchObject({ ok: false, status: 403, error: { code: 'forbidden' } })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it.skipIf(!canCreateSymlink)('rejects fs.write through a workspace symlink', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-symlink-security-'))
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
try {
symlinkSync(outside, join(workspace, 'link'))
const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
const write = await invoke(route, 'fs.write', { sessionId: 'security', path: join(workspace, 'link', 'new.txt'), content: 'hack' })
expect(write).toMatchObject({ ok: false, status: 403, error: { code: 'forbidden' } })
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})
describe('side card settings routes', () => {
/** A minimal settings seam: register/describe/update with the revision guard. */
const createFakeSettings = (pre?: Record<string, Record<string, unknown>>) => {
const namespaces = new Map<string, {
schema: unknown
value: Record<string, unknown> | undefined
revision: number
}>()
for (const [ns, value] of Object.entries(pre ?? {})) {
namespaces.set(ns, { schema: (input: unknown) => input, value, revision: 0 })
}
const resolve = (entry: { schema: unknown; value: Record<string, unknown> | undefined }): unknown => {
const schema = entry.schema as (input: unknown) => unknown
return entry.value === undefined ? schema(undefined) : schema(entry.value)
}
return {
register(ns: string, schema: unknown) {
namespaces.set(ns, { schema, value: undefined, revision: 0 })
return { get: () => ({}), watch: () => () => {}, update: async () => {}, replace: async () => {} }
},
describe() {
return [...namespaces.entries()].map(([ns, entry]) => ({
ns,
value: resolve(entry),
applies: 'live' as const,
revision: entry.revision,
}))
},
async update(ns: string, patch: Record<string, unknown>, expectedRevision?: number) {
const entry = namespaces.get(ns)
if (entry === undefined) throw new Error(`settings namespace "${ns}" is not registered`)
if (expectedRevision !== undefined && expectedRevision !== entry.revision) {
throw new SettingsConflictError(ns as SettingsNamespace, expectedRevision, entry.revision)
}
entry.value = { ...entry.value, ...patch }
entry.revision += 1
},
}
}
const mountWithSettings = (settings?: unknown): SidebarWebRoute => {
const routes: SidebarWebRoute[] = []
const fs = {
resolve: async (path: string) => {
const absolute = resolvePath(path)
const canonical = await import('node:fs/promises').then(({ realpath }) => realpath(absolute))
return { targetKey: canonical, displayPath: absolute }
},
contains: (parent: { targetKey: string }, child: { targetKey: string }) => child.targetKey === parent.targetKey || child.targetKey.startsWith(`${parent.targetKey}${process.platform === 'win32' ? '\\' : '/'}`),
lstat: async (path: string) => {
const info = await import('node:fs/promises').then(module => module.lstat(path)).catch(() => undefined)
return info === undefined ? undefined : { type: info.isSymbolicLink() ? 'symlink' as const : info.isDirectory() ? 'directory' as const : info.isFile() ? 'file' as const : 'other' as const }
},
stat: async (target: { targetKey: string }) => {
const info = await import('node:fs/promises').then(module => module.stat(target.targetKey)).catch(() => undefined)
return info === undefined ? undefined : { type: info.isDirectory() ? 'directory' as const : info.isFile() ? 'file' as const : 'other' as const }
},
listDir: async (target: { targetKey: string; displayPath: string }) => {
const entries = await import('node:fs/promises').then(module => module.readdir(target.targetKey, { withFileTypes: true }))
return Promise.all(entries.map(async entry => ({
name: entry.name,
type: entry.isDirectory() ? 'directory' as const : entry.isFile() ? 'file' as const : 'other' as const,
target: await fs.resolve(join(target.displayPath, entry.name)),
})))
},
}
const ctx = {
webRuntime: { trustedHosts: [] },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
},
sessions: { get: () => undefined },
fs,
tools: { register: () => () => {} },
effect: (fn: () => void | (() => void)) => { fn() },
inject: (deps: string[], callback: (sctx: { settings: unknown }) => void) => {
if (deps.includes('settings') && settings !== undefined) callback({ settings })
return () => {}
},
// No jobs/agents services: the jobs routes degrade to a 503.
get: () => undefined,
}
apply(ctx as never)
return routes.find(route => route.path === '/sidebar/api')!
}
const invoke = async (route: SidebarWebRoute, method: string, payload: unknown): Promise<{
ok: boolean
value?: unknown
error?: { code?: string; message: string }
}> => {
const body = Buffer.from(JSON.stringify(payload))
const req = {
method: 'POST',
url: `/sidebar/api/${method}`,
headers: { host: '127.0.0.1:3080' },
[Symbol.asyncIterator]: async function* () { yield body },
} as never
const out: { status: number; body: string } = { status: 200, body: '' }
const res = {
writeHead: (status: number) => { out.status = status },
end: (chunk: unknown) => { out.body += String(chunk ?? '') },
} as never
await route.handler(req, res)
return JSON.parse(out.body) as { ok: boolean; value?: unknown; error?: { code?: string; message: string } }
}
it('serves the schema defaults when the settings service is absent', async () => {
const route = mountWithSettings(undefined)
const result = await invoke(route, 'settings.get', {})
expect(result.ok).toBe(true)