mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-03 09:09:33 +01:00
Merge pull request #604: feat(preview): open ~/, relative and hard-wrapped paths; folder grid
This commit is contained in:
commit
90034d07d7
25 files changed
+2949
-87
No files matched your search
@@ -0,0 +1,322 @@
|
||||
/**
|
||||
* @fileoverview Clickable file paths beyond the rooted absolute form: `~/…`,
|
||||
* relative paths, and paths a program broke over lines itself.
|
||||
*
|
||||
* - `findFilePathLinks` / `resolveLinkedFilePath` / `terminalPathLine`
|
||||
* (constants.js) on the shapes real agent output has: Claude Code echoes an
|
||||
* attached image as `› [image] ~/…/garage.png`, scripts print
|
||||
* `builds/captures/…png`, and Claude Code wraps tool output a few columns
|
||||
* short of the edge, so a long path arrives as `…/captures/2` + `026-10-10/x.png`.
|
||||
* - The terminal link provider turns those into ONE link and opens the resolved
|
||||
* path (relative against the session's working directory, `~/` as is).
|
||||
* - The server expands `~/` (local: this host's home; remote: the probe on the
|
||||
* remote host), so the attachment route can serve it.
|
||||
*
|
||||
* Real code under test: constants.js + terminal-ui.js in a `vm` context, and
|
||||
* the shipped attachment registry / probe script.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { afterAll, describe, expect, it, vi } from 'vitest';
|
||||
import { registerExternalAttachment } from '../src/attachment-registry.js';
|
||||
import { buildRemoteProbeCommand, parseRemoteProbeOutput } from '../src/remote-files.js';
|
||||
|
||||
type Line = {
|
||||
startRow: number;
|
||||
endRow: number;
|
||||
text: string;
|
||||
offsetToCell: (o: number) => { row: number; col: number };
|
||||
};
|
||||
type Helpers = {
|
||||
findFilePathLinks: (text: string) => Array<{ path: string; index: number }>;
|
||||
resolveLinkedFilePath: (path: string, workingDir?: string) => string;
|
||||
terminalPathLine: (buffer: unknown, row: number, cols: number, maxRows?: number) => Line | null;
|
||||
};
|
||||
|
||||
const read = (f: string) => readFileSync(resolve(import.meta.dirname, `../src/web/public/${f}`), 'utf8');
|
||||
|
||||
function loadHelpers(): Helpers {
|
||||
const context = vm.createContext({});
|
||||
vm.runInContext(
|
||||
`${read('constants.js')}\nglobalThis.__h = { findFilePathLinks, resolveLinkedFilePath, terminalPathLine };`,
|
||||
context,
|
||||
{ filename: 'constants.js' }
|
||||
);
|
||||
return (context as { __h: Helpers }).__h;
|
||||
}
|
||||
|
||||
const { findFilePathLinks, resolveLinkedFilePath, terminalPathLine } = loadHelpers();
|
||||
const paths = (text: string) => findFilePathLinks(text).map((f) => f.path);
|
||||
|
||||
/** An xterm buffer stand-in: hard-broken rows (no `isWrapped`), as Claude Code emits them. */
|
||||
function buffer(lines: string[], cols = 80) {
|
||||
return {
|
||||
length: lines.length,
|
||||
getLine: (row: number) =>
|
||||
row >= 0 && row < lines.length
|
||||
? {
|
||||
isWrapped: false,
|
||||
translateToString: (trim?: boolean) => (trim ? lines[row].replace(/\s+$/, '') : lines[row].padEnd(cols)),
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// Verbatim from a live pane (2026-10-10): the tool output wrapped at ~64 columns.
|
||||
const BROKEN = [
|
||||
' ⎿ BILD /mnt/build/neon_getaway-mgr-hebel/builds/captures/2',
|
||||
' 026-10-10/ghost1b_gameplay.png err=0 kamera=(1108,13,811',
|
||||
' ) blick=',
|
||||
];
|
||||
const BROKEN_PATH = '/mnt/build/neon_getaway-mgr-hebel/builds/captures/2026-10-10/ghost1b_gameplay.png';
|
||||
|
||||
describe('findFilePathLinks', () => {
|
||||
it('links home-relative and relative paths', () => {
|
||||
expect(paths(' › [image] ~/repos/neon-menu/assets/ui/backgrounds/garage_plate.png (1.1MB)')).toEqual([
|
||||
'~/repos/neon-menu/assets/ui/backgrounds/garage_plate.png',
|
||||
]);
|
||||
expect(paths('2 Bericht: refs/shaderpatch_pixel_1010/BERICHT.md. Alle 12')).toEqual([
|
||||
'refs/shaderpatch_pixel_1010/BERICHT.md',
|
||||
]);
|
||||
expect(paths('./a.md ../b.json look_montage.png')).toEqual(['./a.md', '../b.json', 'look_montage.png']);
|
||||
});
|
||||
|
||||
it('keeps brackets, `=` and trailing punctuation out of a relative path', () => {
|
||||
expect(paths('1. Garage-BG (garage_plate.png) — Bühne')).toEqual(['garage_plate.png']);
|
||||
expect(paths('OUT=builds/captures/x.png, "shots/b.webp"')).toEqual(['builds/captures/x.png', 'shots/b.webp']);
|
||||
expect(paths('see src/a.ts:120.')).toEqual(['src/a.ts']);
|
||||
});
|
||||
|
||||
it('still finds rooted absolute paths, and never a relative path inside one', () => {
|
||||
expect(paths('sign-off from /mnt/raid1/x/refs/look_montage.png.')).toEqual(['/mnt/raid1/x/refs/look_montage.png']);
|
||||
// Unknown root: not linked at all (no `nix/store/…` cut out of it).
|
||||
expect(paths('/nix/store/abc-x/share/icon.png')).toEqual([]);
|
||||
// `/etc` stays out on purpose (the server refuses that tree).
|
||||
expect(paths('/etc/app/config.json')).toEqual([]);
|
||||
});
|
||||
|
||||
it('never cuts a path out of a web URL, but keeps file:// paths', () => {
|
||||
expect(paths('https://x.io/a/home/b.png?img=c.png')).toEqual([]);
|
||||
expect(paths('file:///home/joe/x.png')).toEqual(['/home/joe/x.png']);
|
||||
});
|
||||
|
||||
it('reports where each path starts', () => {
|
||||
const text = 'a ~/x.png b /tmp/y.pdf c z.md';
|
||||
for (const { path, index } of findFilePathLinks(text)) expect(text.slice(index, index + path.length)).toBe(path);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveLinkedFilePath', () => {
|
||||
it('resolves relative paths against the working directory, collapsing . and ..', () => {
|
||||
expect(resolveLinkedFilePath('builds/x.png', '/mnt/ws')).toBe('/mnt/ws/builds/x.png');
|
||||
expect(resolveLinkedFilePath('./a/./b.md', '/mnt/ws/')).toBe('/mnt/ws/a/b.md');
|
||||
expect(resolveLinkedFilePath('../other/x.png', '/mnt/ws')).toBe('/mnt/other/x.png');
|
||||
});
|
||||
|
||||
it('leaves absolute and ~/ paths alone, and relative ones without a working directory', () => {
|
||||
expect(resolveLinkedFilePath('/tmp/a.png', '/mnt/ws')).toBe('/tmp/a.png');
|
||||
expect(resolveLinkedFilePath('~/a.png', '/mnt/ws')).toBe('~/a.png');
|
||||
expect(resolveLinkedFilePath('a.png', undefined)).toBe('a.png');
|
||||
});
|
||||
});
|
||||
|
||||
describe('terminalPathLine', () => {
|
||||
it('glues a path broken short of the edge back together, from either row', () => {
|
||||
for (const row of [0, 1]) {
|
||||
const line = terminalPathLine(buffer(BROKEN), row, 80)!;
|
||||
expect([line.startRow, line.endRow]).toEqual([0, 1]);
|
||||
const [found] = findFilePathLinks(line.text);
|
||||
expect(found.path).toBe(BROKEN_PATH);
|
||||
// The cells are exact on both rows: after ` ⎿ BILD ` and after the 5-column indent.
|
||||
expect(line.offsetToCell(found.index)).toEqual({ row: 0, col: 10 });
|
||||
expect(line.offsetToCell(found.index + found.path.length - 1)).toEqual({ row: 1, col: 34 });
|
||||
}
|
||||
expect(terminalPathLine(buffer(BROKEN), 2, 80)).toMatchObject({ startRow: 2, endRow: 2 });
|
||||
});
|
||||
|
||||
it('follows a path over three rows', () => {
|
||||
const rows = ['x /tmp/claude-1001/-home-joe-cases', ' -neon/de4576ce-aaaaaaaaaaaaa', ' -56b4/shot.png'];
|
||||
const line = terminalPathLine(buffer(rows), 1, 80)!;
|
||||
expect(paths(line.text)).toEqual(['/tmp/claude-1001/-home-joe-cases-neon/de4576ce-aaaaaaaaaaaaa-56b4/shot.png']);
|
||||
});
|
||||
|
||||
it('does not glue lines that are not a broken path', () => {
|
||||
// A shorter line ending on a directory, then a longer one: not a wrap.
|
||||
expect(terminalPathLine(buffer(['cd /mnt/raid1/foo', ' file.png erstellt']), 0, 80)).toMatchObject({ endRow: 0 });
|
||||
// A chain that never reaches a file is dropped.
|
||||
const listing = terminalPathLine(buffer(['cd ~/repos/neon', 'ls', 'a.png']), 2, 80)!;
|
||||
expect(paths(listing.text)).toEqual(['a.png']);
|
||||
// A path that already ended, and a next line opening a new rooted path.
|
||||
expect(terminalPathLine(buffer(['see /tmp/a/b.png', 'c/d.png']), 0, 80)).toMatchObject({ endRow: 0 });
|
||||
expect(terminalPathLine(buffer(['/home/joe/dir/', '/home/x.png']), 0, 80)).toMatchObject({ endRow: 0 });
|
||||
});
|
||||
|
||||
// `git ls-files`, `find` and `ls -R` print one path per row. An extensionless
|
||||
// entry (a directory, `Dockerfile`, `.gitignore`) followed by an entry that is
|
||||
// equal or shorter looked exactly like a path broken short of the edge, and the
|
||||
// two were glued: `src/components` + `src/index.ts` linked `src/componentssrc/index.ts`
|
||||
// and the real `src/index.ts` link was gone (Ark0N, PR #604, round 2).
|
||||
describe('a listing is never glued into one path', () => {
|
||||
const LISTING = [
|
||||
'src/components',
|
||||
'src/index.ts',
|
||||
'src/lib',
|
||||
'./index.ts',
|
||||
'../docs/README.md',
|
||||
'packages/gesture-control/.gitignore',
|
||||
'packages/gesture-control/README.md',
|
||||
'packages/gesture-control/package.json',
|
||||
'data/runs/a.jsonl',
|
||||
'data/runs/b.jsonl',
|
||||
'data/runs/c.jsonl',
|
||||
'data/runs/d.json',
|
||||
];
|
||||
|
||||
it('keeps every row its own line', () => {
|
||||
const buf = buffer(LISTING, 120);
|
||||
LISTING.forEach((entry, row) => {
|
||||
const line = terminalPathLine(buf, row, 120)!;
|
||||
expect([line.startRow, line.endRow], entry).toEqual([row, row]);
|
||||
expect(line.text, entry).toBe(entry);
|
||||
});
|
||||
});
|
||||
|
||||
it('links the entry that used to be swallowed', () => {
|
||||
const buf = buffer(LISTING, 120);
|
||||
expect(paths(terminalPathLine(buf, 1, 120)!.text)).toEqual(['src/index.ts']);
|
||||
});
|
||||
|
||||
it('still glues a path whose next row opens on a different directory (a real wrap)', () => {
|
||||
// The control: `…/captures/2` + `026-10-10/…` has a `/` in its head too.
|
||||
const line = terminalPathLine(buffer(BROKEN), 0, 80)!;
|
||||
expect([line.startRow, line.endRow]).toEqual([0, 1]);
|
||||
expect(paths(line.text)).toEqual([BROKEN_PATH]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
type Link = {
|
||||
text: string;
|
||||
range: { start: { x: number; y: number }; end: { x: number; y: number } };
|
||||
activate: (ev: unknown, text: string) => void;
|
||||
};
|
||||
type Provider = { provideLinks: (line: number, cb: (links: Link[] | undefined) => void) => void };
|
||||
|
||||
function loadApp() {
|
||||
const CodemanApp = function CodemanApp(this: unknown) {};
|
||||
const context = vm.createContext({
|
||||
window: {},
|
||||
document: {
|
||||
body: { classList: { contains: () => false } },
|
||||
activeElement: null,
|
||||
addEventListener: vi.fn(),
|
||||
getElementById: () => null,
|
||||
},
|
||||
CodemanApp,
|
||||
console: { warn: vi.fn(), log: vi.fn(), debug: vi.fn() },
|
||||
_crashDiag: { log: vi.fn() },
|
||||
performance: { now: () => 0 },
|
||||
requestAnimationFrame: () => 1,
|
||||
setTimeout: () => 1,
|
||||
MobileDetection: { isTouchDevice: () => false },
|
||||
DEC_SYNC_STRIP_RE: /\x1b\[\?2026[hl]/g,
|
||||
TERMINAL_CHUNK_SIZE: 32 * 1024,
|
||||
});
|
||||
vm.runInContext(read('constants.js'), context, { filename: 'constants.js' });
|
||||
vm.runInContext(read('terminal-ui.js'), context, { filename: 'terminal-ui.js' });
|
||||
const app = new (CodemanApp as unknown as new () => Record<string, any>)();
|
||||
app.activeSessionId = 's1';
|
||||
app.sessions = new Map([['s1', { workingDir: '/mnt/build/neon_getaway-mgr-hebel' }]]);
|
||||
app.openFilePreview = vi.fn();
|
||||
app.openLogViewerWindow = vi.fn();
|
||||
app._isExternalPreviewPath = (p: string) => p.startsWith('~/');
|
||||
return app;
|
||||
}
|
||||
|
||||
function linksOn(lines: string[], row: number) {
|
||||
const app = loadApp();
|
||||
app.terminal = { cols: 80, registerLinkProvider: vi.fn(), buffer: { active: buffer(lines) } };
|
||||
const provider = app.registerFilePathLinkProvider() as Provider;
|
||||
let out: Link[] = [];
|
||||
provider.provideLinks(row, (links) => {
|
||||
out = links || [];
|
||||
});
|
||||
return { app, links: out };
|
||||
}
|
||||
|
||||
describe('terminal link provider', () => {
|
||||
it('links a broken path once, across both rows, and opens the whole path', () => {
|
||||
const { app, links } = linksOn(BROKEN, 2);
|
||||
expect(links.map((l) => l.text)).toEqual([BROKEN_PATH]);
|
||||
expect(links[0].range.start).toEqual({ x: 11, y: 1 });
|
||||
expect(links[0].range.end.y).toBe(2);
|
||||
links[0].activate({}, links[0].text);
|
||||
expect(app.openFilePreview).toHaveBeenCalledWith(BROKEN_PATH, 's1');
|
||||
});
|
||||
|
||||
it('opens a relative path resolved against the working directory', () => {
|
||||
const { app, links } = linksOn([' ⎿ wrote builds/captures/2026-10-10/a.png'], 1);
|
||||
links[0].activate({}, links[0].text);
|
||||
expect(app.openFilePreview).toHaveBeenCalledWith(
|
||||
'/mnt/build/neon_getaway-mgr-hebel/builds/captures/2026-10-10/a.png',
|
||||
's1'
|
||||
);
|
||||
});
|
||||
|
||||
it('opens a ~/ path as is, in the preview (the server expands it), even for text', () => {
|
||||
const { app, links } = linksOn([' › [image] ~/repos/x/garage.png', 'notes ~/logs/run.log'], 2);
|
||||
links[0].activate({}, links[0].text);
|
||||
expect(app.openFilePreview).toHaveBeenCalledWith('~/logs/run.log', 's1');
|
||||
expect(app.openLogViewerWindow).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens a relative text file in the log viewer by its resolved path', () => {
|
||||
const { app, links } = linksOn(['tail logs/run.log'], 1);
|
||||
links[0].activate({}, links[0].text);
|
||||
expect(app.openLogViewerWindow).toHaveBeenCalledWith('/mnt/build/neon_getaway-mgr-hebel/logs/run.log', 's1');
|
||||
});
|
||||
|
||||
it('never adds a path link overlapping a URL link', () => {
|
||||
const { links } = linksOn(['see https://x.io/view?img=shots/a.png now'], 1);
|
||||
expect(links.map((l) => l.text)).toEqual(['https://x.io/view?img=shots/a.png']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('server: ~/ expands on the session host', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'codeman-tilde-'));
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
||||
|
||||
it('a local session registers ~/… against this host home', async () => {
|
||||
// test/setup.ts points HOME at a temp dir, so this never touches the real home.
|
||||
const dir = join(homedir(), 'tilde-link-test');
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(join(dir, 'shot.png'), 'PNG');
|
||||
try {
|
||||
const event = await registerExternalAttachment('tilde-session', '~/tilde-link-test/shot.png', {});
|
||||
expect(event.attachmentId).toMatch(/^att_/);
|
||||
expect(event.size).toBe(3);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('a relative path is still refused', async () => {
|
||||
await expect(registerExternalAttachment('tilde-session', 'shots/a.png', {})).rejects.toThrow(/absolute/);
|
||||
});
|
||||
|
||||
it('the remote probe expands ~/ to the remote $HOME, and reports the absolute path', () => {
|
||||
writeFileSync(join(root, 'remote.png'), 'PNGPNG');
|
||||
const requested = ['~/remote.png', '~/missing.png'];
|
||||
const stdout = execFileSync('sh', ['-c', buildRemoteProbeCommand(requested)], {
|
||||
env: { ...process.env, HOME: root },
|
||||
}).toString();
|
||||
const [found, missing] = parseRemoteProbeOutput(stdout, requested);
|
||||
expect(found).toMatchObject({ kind: 'file', size: 6 });
|
||||
expect(found?.realPath.endsWith('/remote.png')).toBe(true);
|
||||
expect(found?.realPath.startsWith('/')).toBe(true);
|
||||
expect(missing).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -298,7 +298,7 @@ describe('fold reserved region: every centred overlay is covered', () => {
|
||||
it('finds the overlays it is meant to guard', () => {
|
||||
// A rename that empties this list would turn every assertion below into a
|
||||
// no-op, so the count is pinned.
|
||||
expect(CENTRED_OVERLAYS.length).toBe(7);
|
||||
expect(CENTRED_OVERLAYS.length).toBe(8);
|
||||
});
|
||||
|
||||
it.each(CENTRED_OVERLAYS.map((o) => [o.selector, o] as const))('%s keeps its dialog out of the hinge', (_, o) => {
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
/**
|
||||
* @fileoverview Folder grid, client side.
|
||||
*
|
||||
* - Folder paths are links (`findFilePathLinks` marks them `folder: true`): rooted
|
||||
* and `~/` paths whose last segment has no extension, relative ones only with a
|
||||
* trailing slash. File links win any overlap; prose and URLs stay plain text.
|
||||
* - Both consumers route a folder link to `openFolderGrid`.
|
||||
* - `openFolderGrid` grants the folder (`POST …/folders`), renders tiles from the
|
||||
* folder's by-name routes, and falls back to the file preview when the server
|
||||
* finds a file there.
|
||||
* - A tile's preview renders from the folder routes (never the attachment
|
||||
* registry), pages with ‹ › / ←/→ (wrapping), and the arrows are kept away from
|
||||
* the terminal; "Show folder" opens the grid of a previewed file's folder.
|
||||
*
|
||||
* Real code under test: constants.js + panels-ui.js in a `vm` context against a
|
||||
* stub app and a minimal fake DOM (no jsdom), as in file-preview-detach.test.ts.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
const read = (f: string) => readFileSync(resolve(PUBLIC, f), 'utf8');
|
||||
|
||||
type Found = { path: string; index: number; folder?: true };
|
||||
const constants = vm.createContext({});
|
||||
vm.runInContext(`${read('constants.js')}\nglobalThis.__h = { findFilePathLinks, resolveLinkedFilePath };`, constants, {
|
||||
filename: 'constants.js',
|
||||
});
|
||||
const { findFilePathLinks, resolveLinkedFilePath } = (
|
||||
constants as unknown as {
|
||||
__h: { findFilePathLinks: (t: string) => Found[]; resolveLinkedFilePath: (p: string, w?: string) => string };
|
||||
}
|
||||
).__h;
|
||||
const folders = (text: string) =>
|
||||
findFilePathLinks(text)
|
||||
.filter((f) => f.folder)
|
||||
.map((f) => f.path);
|
||||
|
||||
describe('folder links (findFilePathLinks)', () => {
|
||||
it('links rooted, ~/ and slash-terminated relative folders', () => {
|
||||
expect(folders('post mal /mnt/raid1/neon_getaway/styleframes')).toEqual(['/mnt/raid1/neon_getaway/styleframes']);
|
||||
expect(folders('ls ~/repos/neon-menu/assets/')).toEqual(['~/repos/neon-menu/assets/']);
|
||||
expect(folders('see builds/captures/ next')).toEqual(['builds/captures/']);
|
||||
expect(folders('cd /home/joe/.codeman/app.')).toEqual(['/home/joe/.codeman/app']);
|
||||
expect(folders('in (/mnt/raid1/foo), ok')).toEqual(['/mnt/raid1/foo']);
|
||||
});
|
||||
|
||||
it('leaves files, prose, bare roots and URLs alone', () => {
|
||||
expect(folders('/home/joe/a.png and /home/joe/a.rs')).toEqual([]);
|
||||
expect(folders('Node.js and/or foo')).toEqual([]);
|
||||
expect(folders('/home/ alone, ~/ alone')).toEqual([]);
|
||||
expect(folders('https://x.io/home/joe/dir and http://host/a/')).toEqual([]);
|
||||
expect(folders('/etc/nginx is not a link root')).toEqual([]);
|
||||
});
|
||||
|
||||
it('ends a folder path at a colon (PATH lists), and stays linear on colon runs', () => {
|
||||
expect(folders('export PATH=/home/u/bin:/usr/bin')).toEqual(['/home/u/bin']);
|
||||
expect(folders('dirs /mnt/a/frames:/mnt/b/frames')).toEqual(['/mnt/a/frames', '/mnt/b/frames']);
|
||||
const start = Date.now();
|
||||
findFilePathLinks('a:'.repeat(16000) + '//');
|
||||
expect(Date.now() - start).toBeLessThan(100);
|
||||
});
|
||||
|
||||
it('keeps the file link where both could match, and orders by position', () => {
|
||||
const found = findFilePathLinks('dir /mnt/a/frames then /mnt/a/frames/x.png');
|
||||
expect(found.map((f) => [f.path, !!f.folder])).toEqual([
|
||||
['/mnt/a/frames', true],
|
||||
['/mnt/a/frames/x.png', false],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('folder links are routed to the grid', () => {
|
||||
it('terminal provider opens folder links in the grid', () => {
|
||||
const src = read('terminal-ui.js');
|
||||
expect(src).toMatch(/addLink\(found\.path, found\.index, !!found\.folder\)/);
|
||||
expect(src).toMatch(/if \(folder\) \{\s*self\.openFolderGrid\(target, sessionId\);/);
|
||||
});
|
||||
|
||||
it('response viewer marks folder links and opens them in the grid', () => {
|
||||
const src = read('app.js');
|
||||
expect(src).toMatch(/if \(folder\) link\.dataset\.folder = '1';/);
|
||||
expect(src).toMatch(/pathLink\.dataset\.folder\) this\.openFolderGrid\(/);
|
||||
});
|
||||
|
||||
it('ships the grid overlay and the preview buttons', () => {
|
||||
const html = read('index.html');
|
||||
for (const id of [
|
||||
'folderGridOverlay',
|
||||
'folderGridTitle',
|
||||
'folderGridFolders',
|
||||
'folderGridBody',
|
||||
'folderGridFooter',
|
||||
'folderGridUpBtn',
|
||||
'filePreviewPrevBtn',
|
||||
'filePreviewNextBtn',
|
||||
'filePreviewFolderBtn',
|
||||
]) {
|
||||
expect(html, id).toContain(`id="${id}"`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------- panels-ui.js against a stub app ----------
|
||||
|
||||
type FakeEl = {
|
||||
tagName: string;
|
||||
children: FakeEl[];
|
||||
textContent: string;
|
||||
innerHTML: string;
|
||||
className: string;
|
||||
dataset: Record<string, string>;
|
||||
hidden?: boolean;
|
||||
disabled?: boolean;
|
||||
title?: string;
|
||||
src?: string;
|
||||
onclick?: () => void;
|
||||
onerror?: () => void;
|
||||
classList: { add: (c: string) => void; remove: (c: string) => void; contains: (c: string) => boolean };
|
||||
appendChild: (c: FakeEl) => void;
|
||||
append: (...c: FakeEl[]) => void;
|
||||
querySelector: (sel: string) => FakeEl | null;
|
||||
querySelectorAll: (sel: string) => FakeEl[];
|
||||
scrollIntoView: () => void;
|
||||
};
|
||||
|
||||
function el(tagName = 'div'): FakeEl {
|
||||
const classes = new Set<string>();
|
||||
const node: FakeEl = {
|
||||
tagName: tagName.toUpperCase(),
|
||||
children: [],
|
||||
textContent: '',
|
||||
className: '',
|
||||
dataset: {},
|
||||
get innerHTML() {
|
||||
return '';
|
||||
},
|
||||
set innerHTML(_v: string) {
|
||||
node.children = [];
|
||||
},
|
||||
classList: {
|
||||
add: (c) => classes.add(c),
|
||||
remove: (c) => classes.delete(c),
|
||||
contains: (c) => classes.has(c) || node.className.split(' ').includes(c),
|
||||
},
|
||||
appendChild: (c) => void node.children.push(c),
|
||||
append: (...c) => void node.children.push(...c),
|
||||
querySelector: () => null,
|
||||
querySelectorAll: () => [],
|
||||
scrollIntoView: () => {},
|
||||
} as FakeEl;
|
||||
return node;
|
||||
}
|
||||
|
||||
function loadApp(fetchImpl: (url: string, init?: { body?: string }) => unknown) {
|
||||
const CodemanApp = function CodemanApp(this: unknown) {} as unknown as new () => Record<string, unknown>;
|
||||
const keyHandlers: Array<(ev: unknown) => void> = [];
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
console: { ...console, warn: vi.fn(), error: vi.fn() },
|
||||
localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
|
||||
escapeHtml: (s: string) => String(s),
|
||||
CodemanBase: { base: '', url: (p: string) => p },
|
||||
resolveLinkedFilePath,
|
||||
document: {
|
||||
getElementById: () => null,
|
||||
createElement: (t: string) => el(t),
|
||||
addEventListener: (type: string, fn: (ev: unknown) => void) => {
|
||||
if (type === 'keydown') keyHandlers.push(fn);
|
||||
},
|
||||
},
|
||||
window: { addEventListener: vi.fn(), open: vi.fn() },
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
confirm: () => true,
|
||||
fetch: vi.fn(async (url: string, init?: { body?: string }) => fetchImpl(url, init)),
|
||||
});
|
||||
vm.runInContext(read('panels-ui.js'), context, { filename: 'panels-ui.js' });
|
||||
|
||||
const previewOverlay = el();
|
||||
const gridOverlay = el();
|
||||
const previewBody = el();
|
||||
const gridBody = el();
|
||||
const elements: Record<string, FakeEl> = {
|
||||
filePreviewOverlay: previewOverlay,
|
||||
filePreviewBody: previewBody,
|
||||
filePreviewTitle: el(),
|
||||
filePreviewFooter: el(),
|
||||
filePreviewDetachBtn: el(),
|
||||
filePreviewPrevBtn: Object.assign(el(), { hidden: true }),
|
||||
filePreviewNextBtn: Object.assign(el(), { hidden: true }),
|
||||
filePreviewFolderBtn: Object.assign(el(), { hidden: true }),
|
||||
folderGridOverlay: gridOverlay,
|
||||
folderGridTitle: el(),
|
||||
folderGridFolders: el(),
|
||||
folderGridBody: gridBody,
|
||||
folderGridFooter: el(),
|
||||
folderGridUpBtn: el(),
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const app = new CodemanApp() as Record<string, any>;
|
||||
app.$ = (id: string) => elements[id] ?? null;
|
||||
app._resetFilePreviewEdit = () => {};
|
||||
app.showToast = vi.fn();
|
||||
app.formatFileSize = (n: number) => `${n} B`;
|
||||
app.sessions = new Map([['s1', { workingDir: '/home/joe/wiki' }]]);
|
||||
app._registerExternalPreview = vi.fn(async () => ({ attachmentId: 'att-x' }));
|
||||
return { app, elements, keyHandlers, fetch: context.fetch as ReturnType<typeof vi.fn> };
|
||||
}
|
||||
|
||||
const LISTING = {
|
||||
folderId: 'fld_1',
|
||||
path: '/mnt/raid1/styleframes',
|
||||
files: [
|
||||
{ name: 'b.png', extension: 'png', attachmentType: 'image', size: 10, mtimeMs: 2 },
|
||||
{ name: 'deck.pdf', extension: 'pdf', attachmentType: 'pdf', size: 20, mtimeMs: 1 },
|
||||
{ name: 'clip.mp4', extension: 'mp4', attachmentType: 'video', size: 30, mtimeMs: 0 },
|
||||
],
|
||||
folders: ['old'],
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
function ok(data: unknown) {
|
||||
return { ok: true, status: 200, json: async () => ({ success: true, data }) };
|
||||
}
|
||||
|
||||
describe('openFolderGrid', () => {
|
||||
it('grants the folder and renders a tile per file from the folder routes', async () => {
|
||||
const { app, elements, fetch } = loadApp(() => ok(LISTING));
|
||||
await app.openFolderGrid('~/styleframes', 's1');
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('/api/sessions/s1/folders', expect.objectContaining({ method: 'POST' }));
|
||||
expect(JSON.parse(fetch.mock.calls[0][1].body)).toEqual({ path: '~/styleframes' });
|
||||
expect(elements.folderGridOverlay.classList.contains('visible')).toBe(true);
|
||||
expect(elements.folderGridTitle.textContent).toBe('/mnt/raid1/styleframes');
|
||||
|
||||
const tiles = elements.folderGridBody.children;
|
||||
expect(tiles).toHaveLength(3);
|
||||
const thumb = (i: number) => tiles[i].children[0];
|
||||
expect(thumb(0).children[0].src).toBe('/api/sessions/s1/folders/fld_1/files/b.png/raw');
|
||||
expect(thumb(1).children[0].src).toBe('/api/sessions/s1/folders/fld_1/files/deck.pdf/thumbnail');
|
||||
expect(thumb(2).children).toHaveLength(0);
|
||||
expect(thumb(2).textContent).toBe('MP4');
|
||||
expect(elements.folderGridFolders.children.map((c) => c.textContent)).toEqual(['old/']);
|
||||
expect(elements.folderGridFooter.textContent).toBe('3 files • 1 folder');
|
||||
});
|
||||
|
||||
it('falls back to the file preview when the path is a file', async () => {
|
||||
const { app } = loadApp(() => ({ ok: false, status: 400, json: async () => ({ error: 'Not a folder' }) }));
|
||||
app.openFilePreview = vi.fn();
|
||||
await app.openFolderGrid('/mnt/raid1/notes', 's1');
|
||||
expect(app.openFilePreview).toHaveBeenCalledWith('/mnt/raid1/notes', 's1');
|
||||
});
|
||||
|
||||
it('toasts a missing or blocked folder', async () => {
|
||||
const { app, elements } = loadApp(() => ({
|
||||
ok: false,
|
||||
status: 404,
|
||||
json: async () => ({ error: 'Folder not found' }),
|
||||
}));
|
||||
await app.openFolderGrid('/mnt/raid1/gone', 's1');
|
||||
expect(app.showToast).toHaveBeenCalledWith(expect.stringContaining('Folder not found'), 'error');
|
||||
expect(elements.folderGridOverlay.classList.contains('visible')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('folder preview paging', () => {
|
||||
async function openGrid() {
|
||||
const ctx = loadApp(() => ok(LISTING));
|
||||
await ctx.app.openFolderGrid('/mnt/raid1/styleframes', 's1');
|
||||
return ctx;
|
||||
}
|
||||
|
||||
it('previews a tile from the folder routes, never registering an attachment', async () => {
|
||||
const { app, elements } = await openGrid();
|
||||
elements.folderGridBody.children[0].onclick?.();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(app._registerExternalPreview).not.toHaveBeenCalled();
|
||||
expect(app.filePreviewDetachUrl).toBe('/api/sessions/s1/folders/fld_1/files/b.png/raw');
|
||||
expect(elements.filePreviewTitle.textContent).toBe('/mnt/raid1/styleframes/b.png');
|
||||
expect(elements.filePreviewPrevBtn.hidden).toBe(false);
|
||||
expect(elements.filePreviewNextBtn.hidden).toBe(false);
|
||||
expect(elements.filePreviewFolderBtn.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it('pages with wrap-around and keeps arrow keys away from the terminal', async () => {
|
||||
const { app, elements, keyHandlers } = await openGrid();
|
||||
elements.folderGridBody.children[0].onclick?.();
|
||||
elements.filePreviewOverlay.classList.add('visible');
|
||||
|
||||
app.stepFolderPreview(-1);
|
||||
expect(app.folderGrid.index).toBe(2);
|
||||
expect(app.filePreviewDetachUrl).toBe('/api/sessions/s1/folders/fld_1/files/clip.mp4/raw');
|
||||
|
||||
const ev = {
|
||||
key: 'ArrowRight',
|
||||
target: { tagName: 'TEXTAREA', classList: { contains: (c: string) => c === 'xterm-helper-textarea' } },
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
};
|
||||
keyHandlers.forEach((h) => h(ev));
|
||||
expect(app.folderGrid.index).toBe(0);
|
||||
expect(ev.stopPropagation).toHaveBeenCalled();
|
||||
|
||||
const typing = {
|
||||
...ev,
|
||||
target: { tagName: 'INPUT', classList: { contains: () => false } },
|
||||
stopPropagation: vi.fn(),
|
||||
};
|
||||
keyHandlers.forEach((h) => h(typing));
|
||||
expect(app.folderGrid.index).toBe(0);
|
||||
expect(typing.stopPropagation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('Escape closes the preview first, then the grid', async () => {
|
||||
const { app, elements, keyHandlers } = await openGrid();
|
||||
elements.folderGridBody.children[1].onclick?.();
|
||||
elements.filePreviewOverlay.classList.add('visible');
|
||||
const esc = () => ({ key: 'Escape', target: null, preventDefault: vi.fn(), stopPropagation: vi.fn() });
|
||||
|
||||
keyHandlers.forEach((h) => h(esc()));
|
||||
expect(elements.filePreviewOverlay.classList.contains('visible')).toBe(false);
|
||||
expect(elements.folderGridOverlay.classList.contains('visible')).toBe(true);
|
||||
expect(app.folderGrid.index).toBeNull();
|
||||
|
||||
keyHandlers.forEach((h) => h(esc()));
|
||||
expect(elements.folderGridOverlay.classList.contains('visible')).toBe(false);
|
||||
expect(app.folderGrid).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('stale loads', () => {
|
||||
const TEXT_LISTING = {
|
||||
...LISTING,
|
||||
path: '/mnt/raid1/logs',
|
||||
files: [
|
||||
{ name: 'a.log', extension: 'log', attachmentType: 'text', size: 1, mtimeMs: 2 },
|
||||
{ name: 'b.log', extension: 'log', attachmentType: 'text', size: 1, mtimeMs: 1 },
|
||||
],
|
||||
};
|
||||
const text = (body: string) => ({ ok: true, status: 200, text: async () => body });
|
||||
const flush = () => new Promise((r) => setTimeout(r, 0));
|
||||
|
||||
it("paging past a text file that is still loading never shows its text under the next file's title", async () => {
|
||||
const pending: Record<string, (v: unknown) => void> = {};
|
||||
const { app, elements } = loadApp((url) =>
|
||||
url.endsWith('/folders') ? ok(TEXT_LISTING) : new Promise((r) => (pending[url] = r))
|
||||
);
|
||||
await app.openFolderGrid('/mnt/raid1/logs', 's1');
|
||||
app._renderFilePreviewText = vi.fn();
|
||||
elements.folderGridBody.children[0].onclick?.();
|
||||
elements.filePreviewOverlay.classList.add('visible');
|
||||
app.stepFolderPreview(1);
|
||||
await flush();
|
||||
|
||||
pending['/api/sessions/s1/folders/fld_1/files/b.log/raw'](text('B'));
|
||||
await flush();
|
||||
pending['/api/sessions/s1/folders/fld_1/files/a.log/raw'](text('A'));
|
||||
await flush();
|
||||
|
||||
expect(elements.filePreviewTitle.textContent).toBe('/mnt/raid1/logs/b.log');
|
||||
expect(app.filePreviewContent).toBe('B');
|
||||
expect(app.filePreviewText.filePath).toBe('/mnt/raid1/logs/b.log');
|
||||
expect(app._renderFilePreviewText).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('two quick folder opens render only the newer one, and a closed grid stays closed', async () => {
|
||||
const pending: Record<string, (v: unknown) => void> = {};
|
||||
const { app, elements } = loadApp((_url, init) => {
|
||||
const path = JSON.parse(init?.body || '{}').path;
|
||||
return new Promise((r) => (pending[path] = r));
|
||||
});
|
||||
const first = app.openFolderGrid('/mnt/raid1/styleframes', 's1');
|
||||
const second = app.openFolderGrid('/mnt/raid1/logs', 's1');
|
||||
pending['/mnt/raid1/logs'](ok(TEXT_LISTING));
|
||||
await second;
|
||||
pending['/mnt/raid1/styleframes'](ok(LISTING));
|
||||
await first;
|
||||
expect(app.folderGrid.path).toBe('/mnt/raid1/logs');
|
||||
expect(elements.folderGridTitle.textContent).toBe('/mnt/raid1/logs');
|
||||
|
||||
const late = app.openFolderGrid('/mnt/raid1/styleframes', 's1');
|
||||
app.closeFolderGrid();
|
||||
pending['/mnt/raid1/styleframes'](ok(LISTING));
|
||||
await late;
|
||||
expect(app.folderGrid).toBeNull();
|
||||
expect(elements.folderGridOverlay.classList.contains('visible')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('"Show folder" in the preview', () => {
|
||||
it('knows the folder of absolute, relative and ~/ paths, not of a bare attachment card', () => {
|
||||
const { app } = loadApp(() => ok(LISTING));
|
||||
expect(app._previewFolderPath('/mnt/raid1/x/a.png', 's1', null)).toEqual({ dir: '/mnt/raid1/x', sessionId: 's1' });
|
||||
expect(app._previewFolderPath('builds/a.png', 's1', null)).toEqual({
|
||||
dir: '/home/joe/wiki/builds',
|
||||
sessionId: 's1',
|
||||
});
|
||||
expect(app._previewFolderPath('~/r/a.png', 's1', null)).toEqual({ dir: '~/r', sessionId: 's1' });
|
||||
expect(app._previewFolderPath('a.png', 's1', 'att-1')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows the button for a previewed file and opens its folder', async () => {
|
||||
const { app, elements, fetch } = loadApp(() => ok(LISTING));
|
||||
await app.openFilePreview('/mnt/raid1/styleframes/b.png', 's1');
|
||||
expect(elements.filePreviewFolderBtn.hidden).toBe(false);
|
||||
expect(elements.filePreviewPrevBtn.hidden).toBe(true);
|
||||
|
||||
app.openFolderOfPreview();
|
||||
await vi.waitFor(() => expect(elements.folderGridOverlay.classList.contains('visible')).toBe(true));
|
||||
expect(JSON.parse(fetch.mock.calls.at(-1)[1].body)).toEqual({ path: '/mnt/raid1/styleframes' });
|
||||
});
|
||||
});
|
||||
@@ -36,7 +36,14 @@ function shippedPattern(name: string): RegExp {
|
||||
return new RegExp(lit.slice(1, lastSlash), lit.slice(lastSlash + 1));
|
||||
}
|
||||
|
||||
const PATTERN_NAMES = ['urlPattern', 'cmdPattern', 'FILE_PATH_LINK_PATTERN', 'bashPattern'];
|
||||
const PATTERN_NAMES = [
|
||||
'urlPattern',
|
||||
'cmdPattern',
|
||||
'FILE_PATH_LINK_PATTERN',
|
||||
'RELATIVE_FILE_PATH_LINK_PATTERN',
|
||||
'FOLDER_PATH_LINK_PATTERN',
|
||||
'bashPattern',
|
||||
];
|
||||
|
||||
/** Lines that made 0.9.10's cmdPattern backtrack exponentially (>2s each). */
|
||||
const KILLER_LINES = [
|
||||
@@ -49,6 +56,8 @@ const KILLER_LINES = [
|
||||
// long URL-ish and path-ish soup for the other patterns
|
||||
'https://example.com/' + 'a/'.repeat(1500) + ' ' + '/home/x/'.repeat(400) + '.'.repeat(2000),
|
||||
'Bash(' + 'x'.repeat(4000),
|
||||
// a colon run ending in `//`: a folder body that kept `:` rescanned it for `://` from every colon
|
||||
'a:'.repeat(16000) + '//',
|
||||
];
|
||||
|
||||
describe('terminal link-provider regexes (shipped source)', () => {
|
||||
@@ -167,13 +176,19 @@ describe('terminal link-provider regexes (shipped source)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('terminal-ui builds its path pattern from the shared factory', () => {
|
||||
it('terminal-ui finds its paths through the shared helper', () => {
|
||||
// Structural guard: a local literal here would drift from the response
|
||||
// viewer's linkifier, which is the divergence the move exists to prevent.
|
||||
expect(SOURCE).toContain('absoluteFilePathPattern()');
|
||||
expect(SOURCE).toContain('findFilePathLinks(lineText)');
|
||||
expect(SOURCE).not.toMatch(/const extPattern =\s*\n?\s*\//);
|
||||
});
|
||||
|
||||
it('the rooted and the relative path pattern link the same extensions', () => {
|
||||
const extensions = (name: string) => /\\\.\(\?:([^()]*)\)\)\\b$/.exec(shippedPattern(name).source)?.[1];
|
||||
expect(extensions('FILE_PATH_LINK_PATTERN')).toBeTruthy();
|
||||
expect(extensions('RELATIVE_FILE_PATH_LINK_PATTERN')).toBe(extensions('FILE_PATH_LINK_PATTERN'));
|
||||
});
|
||||
|
||||
it('cmdPattern arg group cannot match empty tokens (the exponential trigger)', () => {
|
||||
// structural guard: the dangerous construct is an empty-matchable token
|
||||
// inside a repeated group — `[^\s\/]*\s+` repeated. Check the pattern
|
||||
|
||||
@@ -111,10 +111,24 @@ describe('response viewer file-path linkifier', () => {
|
||||
});
|
||||
|
||||
it('leaves text with no path untouched', () => {
|
||||
const root = linkify('<p>Ratio 3/4 on 2026/08/16, see src/app.ts</p>');
|
||||
const root = linkify('<p>Ratio 3/4 on 2026/08/16, see the app</p>');
|
||||
|
||||
expect(paths(root)).toHaveLength(0);
|
||||
expect(root.textContent).toBe('Ratio 3/4 on 2026/08/16, see src/app.ts');
|
||||
expect(root.textContent).toBe('Ratio 3/4 on 2026/08/16, see the app');
|
||||
});
|
||||
|
||||
it('links ~/ and relative paths too, the same forms the terminal links', () => {
|
||||
const root = linkify(
|
||||
'<p>Attached <code>~/repos/x/garage.png</code>, wrote builds/captures/a.png (see src/app.ts)</p>'
|
||||
);
|
||||
|
||||
expect(paths(root).map((a) => a.getAttribute('data-path'))).toEqual([
|
||||
'~/repos/x/garage.png',
|
||||
'builds/captures/a.png',
|
||||
'src/app.ts',
|
||||
]);
|
||||
expect(root.textContent).toBe('Attached ~/repos/x/garage.png, wrote builds/captures/a.png (see src/app.ts)');
|
||||
expect(paths(root).every((a) => a.getAttribute('data-linkified') === '1')).toBe(true);
|
||||
});
|
||||
|
||||
it('never linkifies /etc paths — the server blocks the whole tree, so the link could only 403', () => {
|
||||
@@ -145,6 +159,12 @@ describe('response viewer file-path linkifier', () => {
|
||||
// either leaves inert paths (no linkify) or dead links (no handler).
|
||||
expect(APP_SOURCE).toContain('this._linkifyFilePaths(renderedText)');
|
||||
expect(APP_SOURCE).toMatch(/closest\('a\.rv-path'\)/);
|
||||
expect(APP_SOURCE).toMatch(/openFilePreview\(filePath, pathLink\.dataset\.sessionId \|\| this\.activeSessionId\)/);
|
||||
expect(APP_SOURCE).toMatch(/const sessionId = pathLink\.dataset\.sessionId \|\| this\.activeSessionId;/);
|
||||
// Only the linkifier's own links are resolved; a markdown document's rebased
|
||||
// links keep the path the rebase computed.
|
||||
expect(APP_SOURCE).toMatch(
|
||||
/pathLink\.dataset\.linkified \? this\._resolveLinkedFilePath\?\.\(filePath, sessionId\) : filePath/
|
||||
);
|
||||
expect(APP_SOURCE).toMatch(/openFilePreview\(target \|\| filePath, sessionId\)/);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { MAX_ROUTE_PARAM_LENGTH } from '../../src/web/route-helpers.js';
|
||||
|
||||
export interface RouteTestHarness {
|
||||
app: FastifyInstance;
|
||||
@@ -30,7 +31,7 @@ export async function createRouteTestHarness(
|
||||
registerFn: (app: FastifyInstance, ctx: any) => void,
|
||||
ctxOptions?: { sessionId?: string; authUser?: { username: string; role: 'admin' | 'user' } }
|
||||
): Promise<RouteTestHarness> {
|
||||
const app = Fastify({ logger: false });
|
||||
const app = Fastify({ logger: false, routerOptions: { maxParamLength: MAX_ROUTE_PARAM_LENGTH } });
|
||||
|
||||
// Register cookie plugin — some routes access req.cookies
|
||||
await app.register(fastifyCookie);
|
||||
|
||||
@@ -18,6 +18,7 @@ vi.mock('node:fs/promises', () => ({
|
||||
readdir: vi.fn(async () => []),
|
||||
readFile: vi.fn(async () => 'file content'),
|
||||
stat: vi.fn(async () => ({ size: 100, isFile: () => true, isDirectory: () => true })),
|
||||
realpath: vi.fn(async (p: string) => p),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -442,6 +443,86 @@ describe('file-routes', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// The folder grid is a third file-serving surface (folder-listing.ts): the
|
||||
// same rule as the picker, on the resolved folder AND on each served file.
|
||||
describe('folder grid', () => {
|
||||
const ALICE = `${SPACES}/alice/cases`;
|
||||
const BOB = `${SPACES}/bob/renders`;
|
||||
|
||||
const owned = async (role: 'admin' | 'user', username: string) => {
|
||||
const scoped = await harnessAs(role, username);
|
||||
scoped.ctx._session.owner = username;
|
||||
return scoped;
|
||||
};
|
||||
const grant = (scoped: RouteTestHarness, path: string) =>
|
||||
scoped.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${scoped.ctx._sessionId}/folders`,
|
||||
payload: { path },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mockedStat.mockImplementation(async (p) => {
|
||||
const file = /\.\w+$/.test(String(p));
|
||||
return { size: 100, mtimeMs: 1, isFile: () => file, isDirectory: () => !file } as never;
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses another user's space and never reads it", async () => {
|
||||
const scoped = await owned('user', 'bob');
|
||||
try {
|
||||
mockedReaddir.mockClear();
|
||||
const res = await grant(scoped, ALICE);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(JSON.parse(res.body).error).toBe('Folder is outside your space');
|
||||
expect(mockedReaddir).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await scoped.app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('lists a folder in their own space', async () => {
|
||||
const scoped = await owned('user', 'bob');
|
||||
try {
|
||||
mockedReaddir.mockResolvedValueOnce([] as never);
|
||||
const res = await grant(scoped, BOB);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).data.path).toBe(BOB);
|
||||
} finally {
|
||||
await scoped.app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a file of their own folder that resolves into another user's space", async () => {
|
||||
const scoped = await owned('user', 'bob');
|
||||
try {
|
||||
mockedReaddir.mockResolvedValueOnce([] as never);
|
||||
const { folderId } = JSON.parse((await grant(scoped, BOB)).body).data;
|
||||
mockedRealpathSync.mockImplementation(((p: string) =>
|
||||
p === `${BOB}/plan.png` ? `${ALICE}/secret-project/plan.png` : p) as never);
|
||||
const res = await scoped.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${scoped.ctx._sessionId}/folders/${folderId}/files/plan.png/raw`,
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(JSON.parse(res.body).error).toBe('File is outside your space');
|
||||
expect(mockedCreateReadStream).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await scoped.app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('lets a multi-user admin list any folder', async () => {
|
||||
const scoped = await owned('admin', 'root');
|
||||
try {
|
||||
mockedReaddir.mockResolvedValueOnce([] as never);
|
||||
expect((await grant(scoped, ALICE)).statusCode).toBe(200);
|
||||
} finally {
|
||||
await scoped.app.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the host-wide roots for a multi-user admin', async () => {
|
||||
const scoped = await harnessAs('admin', 'root');
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,596 @@
|
||||
/**
|
||||
* @fileoverview Folder grid — `POST /api/sessions/:id/folders` grants + lists a
|
||||
* folder, `GET …/folders/:folderId/files/:name/(raw|preview|thumbnail)` serves one
|
||||
* of its files by name. Local folders are real temp dirs; a remote case mocks only
|
||||
* the ssh IO, and the remote listing script itself runs on a real `sh`.
|
||||
*
|
||||
* Port: N/A (app.inject doesn't open ports)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { Readable } from 'node:stream';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import {
|
||||
closeSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
utimesSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
import { folderGrants, validFolderFileName } from '../../src/folder-listing.js';
|
||||
import type { SessionRemote } from '../../src/types/session.js';
|
||||
|
||||
vi.mock('../../src/remote-files.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/remote-files.js')>();
|
||||
return {
|
||||
...actual,
|
||||
remoteListFolder: vi.fn(),
|
||||
remoteProbePaths: vi.fn(),
|
||||
remoteCreateReadStream: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../src/utils/bounded-path-probe.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/utils/bounded-path-probe.js')>();
|
||||
return { ...actual, probePathKind: vi.fn(actual.probePathKind) };
|
||||
});
|
||||
|
||||
import { probePathKind } from '../../src/utils/bounded-path-probe.js';
|
||||
import {
|
||||
buildRemoteFolderListCommand,
|
||||
parseRemoteFolderListOutput,
|
||||
remoteCreateReadStream,
|
||||
remoteListFolder,
|
||||
remoteProbePaths,
|
||||
} from '../../src/remote-files.js';
|
||||
|
||||
const mockedProbePathKind = vi.mocked(probePathKind);
|
||||
const mockedListFolder = vi.mocked(remoteListFolder);
|
||||
const mockedProbePaths = vi.mocked(remoteProbePaths);
|
||||
const mockedCreateReadStream = vi.mocked(remoteCreateReadStream);
|
||||
|
||||
function touch(path: string, body: string, mtimeSec: number) {
|
||||
writeFileSync(path, body);
|
||||
utimesSync(path, mtimeSec, mtimeSec);
|
||||
}
|
||||
|
||||
describe('folder grid routes — local folder', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let sessionId: string;
|
||||
let root: string;
|
||||
let dir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerFileRoutes);
|
||||
sessionId = harness.ctx._sessionId;
|
||||
root = mkdtempSync(join(tmpdir(), 'codeman-folder-grid-'));
|
||||
dir = join(root, 'renders');
|
||||
mkdirSync(dir);
|
||||
touch(join(dir, 'old.png'), 'old-png', 1_700_000_000);
|
||||
touch(join(dir, 'new.PNG'), 'new-png', 1_700_000_500);
|
||||
touch(join(dir, 'clip.mp4'), 'mp4', 1_700_000_100);
|
||||
touch(join(dir, 'notes.xyz'), 'unsupported', 1_700_000_900);
|
||||
touch(join(dir, '.hidden.png'), 'hidden', 1_700_000_900);
|
||||
mkdirSync(join(dir, 'shots'));
|
||||
mkdirSync(join(dir, '.cache'));
|
||||
harness.ctx._session.workingDir = root;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
folderGrants.clearSession(sessionId);
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
delete process.env.CODEMAN_ATTACHMENT_CONFINE;
|
||||
delete process.env.CODEMAN_ATTACHMENT_BLOCKED_PATHS;
|
||||
});
|
||||
|
||||
async function grant(path: string) {
|
||||
return harness.app.inject({ method: 'POST', url: `/api/sessions/${sessionId}/folders`, payload: { path } });
|
||||
}
|
||||
|
||||
it('lists supported files newest first plus subfolders, skipping hidden + unsupported', async () => {
|
||||
const res = await grant(dir);
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = JSON.parse(res.body).data;
|
||||
expect(data.folderId).toMatch(/^fld_/);
|
||||
expect(data.path).toBe(dir);
|
||||
expect(data.files.map((f: { name: string }) => f.name)).toEqual(['new.PNG', 'clip.mp4', 'old.png']);
|
||||
expect(data.files[0]).toMatchObject({ extension: 'png', attachmentType: 'image', size: 7 });
|
||||
expect(data.folders).toEqual(['shots']);
|
||||
expect(data.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it('grants the same folder the same id', async () => {
|
||||
const a = JSON.parse((await grant(dir)).body).data.folderId;
|
||||
const b = JSON.parse((await grant(`${dir}/`)).body).data.folderId;
|
||||
expect(b).toBe(a);
|
||||
});
|
||||
|
||||
it('rejects a relative path, a file, and a missing folder', async () => {
|
||||
expect((await grant('renders')).statusCode).toBe(400);
|
||||
expect((await grant(join(dir, 'old.png'))).statusCode).toBe(400);
|
||||
expect((await grant(join(root, 'nope'))).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('refuses a blocked folder and a folder outside a confined workspace', async () => {
|
||||
process.env.CODEMAN_ATTACHMENT_BLOCKED_PATHS = dir;
|
||||
expect((await grant(dir)).statusCode).toBe(403);
|
||||
delete process.env.CODEMAN_ATTACHMENT_BLOCKED_PATHS;
|
||||
|
||||
process.env.CODEMAN_ATTACHMENT_CONFINE = '1';
|
||||
harness.ctx._session.workingDir = join(dir, 'shots');
|
||||
expect((await grant(dir)).statusCode).toBe(403);
|
||||
harness.ctx._session.workingDir = root;
|
||||
expect((await grant(dir)).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('never reads a refused folder: the guard runs on the resolved folder first', async () => {
|
||||
const readdir = vi.spyOn(fs, 'readdir');
|
||||
try {
|
||||
process.env.CODEMAN_ATTACHMENT_BLOCKED_PATHS = dir;
|
||||
expect((await grant(dir)).statusCode).toBe(403);
|
||||
expect(readdir).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
readdir.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('answers a folder or file that does not respond with 503, never 404, and does not read it', async () => {
|
||||
const readdir = vi.spyOn(fs, 'readdir');
|
||||
try {
|
||||
mockedProbePathKind.mockResolvedValueOnce('unknown');
|
||||
const res = await grant(dir);
|
||||
expect(res.statusCode).toBe(503);
|
||||
expect(JSON.parse(res.body).error).toContain(`Folder is not responding or not readable: ${dir}`);
|
||||
expect(readdir).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
readdir.mockRestore();
|
||||
}
|
||||
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
mockedProbePathKind.mockResolvedValueOnce('unknown');
|
||||
const file = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/old.png/raw`,
|
||||
});
|
||||
expect(file.statusCode).toBe(503);
|
||||
expect(JSON.parse(file.body).error).toContain('File is not responding or not readable');
|
||||
});
|
||||
|
||||
it('does not serve a hidden file by name, as the listing hides it', async () => {
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/.hidden.png/raw`,
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('serves a granted file by name, with ranges', async () => {
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/old.png/raw`,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['content-type']).toBe('image/png');
|
||||
expect(res.body).toBe('old-png');
|
||||
|
||||
const ranged = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/old.png/raw`,
|
||||
headers: { range: 'bytes=0-2' },
|
||||
});
|
||||
expect(ranged.statusCode).toBe(206);
|
||||
expect(ranged.body).toBe('old');
|
||||
});
|
||||
|
||||
it('redirects a non-office preview to raw', async () => {
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/clip.mp4/preview`,
|
||||
});
|
||||
expect(res.statusCode).toBe(302);
|
||||
expect(res.headers.location).toBe(`/api/sessions/${sessionId}/folders/${folderId}/files/clip.mp4/raw`);
|
||||
});
|
||||
|
||||
it('never serves a name that leaves the folder or has an unsupported type', async () => {
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
writeFileSync(join(root, 'outside.png'), 'outside');
|
||||
for (const name of ['..%2Foutside.png', '..', '.', 'notes.xyz', 'shots%2Fx.png']) {
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/${name}/raw`,
|
||||
});
|
||||
expect(res.statusCode, name).not.toBe(200);
|
||||
}
|
||||
const missing = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/gone.png/raw`,
|
||||
});
|
||||
expect(missing.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('refuses a file in the folder that symlinks to a blocked target', async () => {
|
||||
const secret = join(root, 'secret');
|
||||
mkdirSync(secret);
|
||||
writeFileSync(join(secret, 'key.png'), 'secret');
|
||||
symlinkSync(join(secret, 'key.png'), join(dir, 'innocent.png'));
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
process.env.CODEMAN_ATTACHMENT_BLOCKED_PATHS = secret;
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/innocent.png/raw`,
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
// The attachment gate (`registerExternalAttachment`) judges the file a symlink
|
||||
// RESOLVES to: its extension must be a supported one and it must be a regular
|
||||
// file. The folder routes only looked at the requested name, so a name that
|
||||
// passed (`shot.png`) could serve anything it pointed at.
|
||||
describe('the resolved target is held to the attachment gate', () => {
|
||||
const files = (folderId: string, name: string, leaf: 'raw' | 'preview' | 'thumbnail' = 'raw') =>
|
||||
harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/${encodeURIComponent(name)}/${leaf}`,
|
||||
});
|
||||
|
||||
it('refuses a supported-looking name whose target has an unsupported extension', async () => {
|
||||
writeFileSync(join(root, 'secret.bin'), 'secret');
|
||||
symlinkSync(join(root, 'secret.bin'), join(dir, 'shot.png'));
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
for (const leaf of ['raw', 'preview', 'thumbnail'] as const) {
|
||||
const res = await files(folderId, 'shot.png', leaf);
|
||||
expect(res.statusCode, leaf).toBe(400);
|
||||
expect(res.body, leaf).not.toContain('secret');
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a name whose target has no extension at all', async () => {
|
||||
writeFileSync(join(root, 'history'), 'private history');
|
||||
symlinkSync(join(root, 'history'), join(dir, 'notes.txt'));
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
const res = await files(folderId, 'notes.txt');
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body).not.toContain('private history');
|
||||
});
|
||||
|
||||
it('refuses a device node behind a supported name', async () => {
|
||||
// /dev/null, not /dev/zero: the same class (character device, no
|
||||
// extension), but it ends the stream instead of filling the test's memory
|
||||
// should the guard ever be missing.
|
||||
symlinkSync('/dev/null', join(dir, 'zero.txt'));
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
const res = await files(folderId, 'zero.txt');
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('refuses a FIFO without opening it', async () => {
|
||||
const fifo = join(dir, 'pipe.txt');
|
||||
execFileSync('mkfifo', [fifo]);
|
||||
// Hold both ends open from here: if the route ever did open it, the open
|
||||
// returns at once and the read blocks, which the race below reports as a
|
||||
// hang instead of leaving a libuv worker parked on a writer that never comes.
|
||||
const fd = openSync(fifo, 'r+');
|
||||
try {
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
const outcome = await Promise.race([
|
||||
files(folderId, 'pipe.txt').then((res) => res.statusCode),
|
||||
new Promise<string>((resolve) => setTimeout(() => resolve('hung'), 2000)),
|
||||
]);
|
||||
expect(outcome).toBe(400);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
});
|
||||
|
||||
it('still serves a symlink whose target is a supported regular file', async () => {
|
||||
writeFileSync(join(root, 'real.png'), 'real-png');
|
||||
symlinkSync(join(root, 'real.png'), join(dir, 'alias.png'));
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
const res = await files(folderId, 'alias.png');
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toBe('real-png');
|
||||
});
|
||||
});
|
||||
|
||||
it('serves a file whose name is longer than the 100-character default of a route parameter', async () => {
|
||||
// The listing shows it (names go up to 255), so the raw/preview/thumbnail
|
||||
// routes have to be able to take it back.
|
||||
const longName = `${'n'.repeat(146)}.png`;
|
||||
expect(longName.length).toBe(150);
|
||||
touch(join(dir, longName), 'long-png', 1_700_000_300);
|
||||
const { folderId } = JSON.parse((await grant(dir)).body).data;
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/${longName}/raw`,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toBe('long-png');
|
||||
});
|
||||
|
||||
// A Docker case is a LOCAL session for the file routes, but its `~` is the
|
||||
// container's home: a separate, seeded directory. `~/x.png` printed inside the
|
||||
// container used to open the HOST's `~/x.png`.
|
||||
describe('~/ in a Docker case', () => {
|
||||
beforeEach(() => {
|
||||
(harness.ctx._session as { docker?: unknown }).docker = {
|
||||
hostId: 'local',
|
||||
label: 'local',
|
||||
engine: 'docker',
|
||||
image: 'codeman-sandbox',
|
||||
containerName: 'codeman-case-test',
|
||||
hostWorkspacePath: root,
|
||||
containerWorkdir: root,
|
||||
network: 'bridge',
|
||||
};
|
||||
});
|
||||
|
||||
it('refuses a ~/ folder, and still lists an absolute one', async () => {
|
||||
const home = await grant('~/renders');
|
||||
expect(home.statusCode).toBe(400);
|
||||
expect(JSON.parse(home.body).error).toMatch(/docker/i);
|
||||
expect((await grant(dir)).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it('refuses a ~/ attachment, and still registers an absolute one', async () => {
|
||||
const post = (path: string) =>
|
||||
harness.app.inject({ method: 'POST', url: `/api/sessions/${sessionId}/attachments`, payload: { path } });
|
||||
const home = await post('~/renders/old.png');
|
||||
expect(home.statusCode).toBe(400);
|
||||
expect(JSON.parse(home.body).error).toMatch(/docker/i);
|
||||
expect((await post(join(dir, 'old.png'))).statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps resolving ~/ for a session that is not in a Docker case', async () => {
|
||||
// The contrast: only the Docker case is turned away, `~/` itself still works.
|
||||
const res = await grant('~/this-folder-does-not-exist-codeman-test');
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('404s an unknown folder id and another session’s grant', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/fld_nope/files/old.png/raw`,
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
const foreign = folderGrants.grant('another-session', dir);
|
||||
const res2 = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${foreign}/files/old.png/raw`,
|
||||
});
|
||||
expect(res2.statusCode).toBe(404);
|
||||
folderGrants.clearSession('another-session');
|
||||
});
|
||||
});
|
||||
|
||||
describe('folder grid routes — remote (SSH) case', () => {
|
||||
const REMOTE_DIR = '/srv/remote/case';
|
||||
const remote: SessionRemote = {
|
||||
hostId: 'host-1',
|
||||
label: 'testhost',
|
||||
host: '192.0.2.10',
|
||||
username: 'j',
|
||||
remotePath: REMOTE_DIR,
|
||||
};
|
||||
let harness: RouteTestHarness;
|
||||
let sessionId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerFileRoutes);
|
||||
sessionId = harness.ctx._sessionId;
|
||||
harness.ctx._session.workingDir = REMOTE_DIR;
|
||||
harness.ctx._session.remote = { ...remote };
|
||||
mockedListFolder.mockResolvedValue({
|
||||
dir: '/mnt/raid/styleframes',
|
||||
entries: [
|
||||
{ kind: 'file', name: 'a.png', size: 3, mtimeMs: 1000 },
|
||||
{ kind: 'file', name: 'b.jpg', size: 4, mtimeMs: 2000 },
|
||||
{ kind: 'directory', name: 'old', size: 0, mtimeMs: 0 },
|
||||
],
|
||||
truncated: true,
|
||||
});
|
||||
mockedProbePaths.mockResolvedValue([
|
||||
{ realPath: '/mnt/raid/styleframes/a.png', kind: 'file', size: 3, mtimeMs: 1000 },
|
||||
{ realPath: REMOTE_DIR, kind: 'directory', size: 0, mtimeMs: 0 },
|
||||
]);
|
||||
mockedCreateReadStream.mockReturnValue({ stream: Readable.from([Buffer.from('abc')]), close: vi.fn() } as never);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
folderGrants.clearSession(sessionId);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('lists the folder on the remote host and serves its files over ssh', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${sessionId}/folders`,
|
||||
payload: { path: '~/styleframes' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = JSON.parse(res.body).data;
|
||||
expect(mockedListFolder).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ host: '192.0.2.10' }),
|
||||
'~/styleframes',
|
||||
expect.arrayContaining(['png', 'pdf']),
|
||||
expect.any(Number)
|
||||
);
|
||||
expect(data.path).toBe('/mnt/raid/styleframes');
|
||||
expect(data.files.map((f: { name: string }) => f.name)).toEqual(['b.jpg', 'a.png']);
|
||||
expect(data.folders).toEqual(['old']);
|
||||
expect(data.truncated).toBe(true);
|
||||
|
||||
const raw = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${data.folderId}/files/a.png/raw`,
|
||||
});
|
||||
expect(raw.statusCode).toBe(200);
|
||||
expect(raw.body).toBe('abc');
|
||||
expect(mockedProbePaths).toHaveBeenCalledWith(expect.anything(), ['/mnt/raid/styleframes/a.png', REMOTE_DIR]);
|
||||
|
||||
const thumb = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${data.folderId}/files/a.png/thumbnail`,
|
||||
});
|
||||
expect(thumb.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
describe('the resolved remote target is held to the attachment gate', () => {
|
||||
async function rawOf(name: string) {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${sessionId}/folders`,
|
||||
payload: { path: '~/styleframes' },
|
||||
});
|
||||
const { folderId } = JSON.parse(res.body).data;
|
||||
return harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/folders/${folderId}/files/${name}/raw`,
|
||||
});
|
||||
}
|
||||
|
||||
it('refuses a name whose remote symlink resolves to an unsupported extension', async () => {
|
||||
mockedProbePaths.mockResolvedValue([
|
||||
{ realPath: '/mnt/raid/secret.bin', kind: 'file', size: 6, mtimeMs: 1000 },
|
||||
{ realPath: REMOTE_DIR, kind: 'directory', size: 0, mtimeMs: 0 },
|
||||
]);
|
||||
const res = await rawOf('a.png');
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(mockedCreateReadStream).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a name that resolves to something that is not a regular file', async () => {
|
||||
mockedProbePaths.mockResolvedValue([
|
||||
{ realPath: '/mnt/raid/styleframes/a.png', kind: 'other', size: 0, mtimeMs: 0 },
|
||||
{ realPath: REMOTE_DIR, kind: 'directory', size: 0, mtimeMs: 0 },
|
||||
]);
|
||||
const res = await rawOf('a.png');
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(mockedCreateReadStream).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('answers 400 "Not a folder" for a remote file, so the client falls back to the preview', async () => {
|
||||
mockedListFolder.mockResolvedValue('not-a-folder');
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${sessionId}/folders`,
|
||||
payload: { path: '/srv/remote/case/Makefile' },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).error).toMatch(/not a folder/i);
|
||||
});
|
||||
|
||||
it('answers 404 for a missing remote folder', async () => {
|
||||
mockedListFolder.mockResolvedValue(null);
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${sessionId}/folders`,
|
||||
payload: { path: '/nope' },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('remote folder listing script (real sh)', () => {
|
||||
let root: string;
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'codeman-folder-sh-'));
|
||||
});
|
||||
afterEach(() => rmSync(root, { recursive: true, force: true }));
|
||||
|
||||
function run(dir: string, max = 100, home = root) {
|
||||
const stdout = execFileSync('sh', ['-c', buildRemoteFolderListCommand(dir, ['png', 'pdf'], max)], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, HOME: home },
|
||||
});
|
||||
return parseRemoteFolderListOutput(stdout);
|
||||
}
|
||||
|
||||
it('lists supported files with size/mtime, subfolders, odd names; resolves ~ and symlinks', () => {
|
||||
const dir = join(root, 'frames');
|
||||
mkdirSync(dir);
|
||||
touch(join(dir, "it's a | frame.PNG"), '12345', 1_700_000_000);
|
||||
touch(join(dir, 'doc.pdf'), 'pdf', 1_700_000_100);
|
||||
touch(join(dir, 'shot.Png'), 'x', 1_700_000_100);
|
||||
touch(join(dir, 'skip.txt'), 'x', 1_700_000_100);
|
||||
touch(join(dir, '.hidden.png'), 'x', 1_700_000_100);
|
||||
mkdirSync(join(dir, 'sub dir'));
|
||||
symlinkSync(dir, join(root, 'link'));
|
||||
|
||||
const listing = run('~/link');
|
||||
expect(listing?.dir).toBe(dir);
|
||||
expect(listing?.truncated).toBe(false);
|
||||
const byName = Object.fromEntries((listing?.entries ?? []).map((e) => [e.name, e]));
|
||||
// Any case, as the local listing: `shot.Png` too.
|
||||
expect(Object.keys(byName).sort()).toEqual(['doc.pdf', "it's a | frame.PNG", 'shot.Png', 'sub dir']);
|
||||
expect(byName["it's a | frame.PNG"]).toMatchObject({ kind: 'file', size: 5, mtimeMs: 1_700_000_000_000 });
|
||||
expect(byName['sub dir']).toMatchObject({ kind: 'directory' });
|
||||
});
|
||||
|
||||
it('is not thrown off by a login shell whose `cd` prints the directory (Hufflepuff: alias cd=folderprompt)', () => {
|
||||
// sshd hands the command to the remote user's LOGIN shell. There `cd` is an
|
||||
// alias that echoes the new directory, so `r=$(cd -P "$d" && pwd -P)` captured
|
||||
// the path twice and the listing failed ("zsh: no matches found: /x\n/x/*").
|
||||
// The script has to run under an explicit `sh`, which reads no rc file.
|
||||
const dir = join(root, 'frames');
|
||||
mkdirSync(dir);
|
||||
touch(join(dir, 'a.png'), 'x', 1_700_000_000);
|
||||
const stdout = execFileSync(
|
||||
'bash',
|
||||
['-c', `cd() { builtin cd "$@" && pwd; }; ${buildRemoteFolderListCommand(dir, ['png'], 100)}`],
|
||||
{ encoding: 'utf8', env: { ...process.env, HOME: root } }
|
||||
);
|
||||
const listing = parseRemoteFolderListOutput(stdout);
|
||||
expect(listing).not.toBeNull();
|
||||
expect(listing).not.toBe('not-a-folder');
|
||||
expect((listing as { dir: string }).dir).toBe(dir);
|
||||
expect((listing as { entries: { name: string }[] }).entries.map((e) => e.name)).toEqual(['a.png']);
|
||||
});
|
||||
|
||||
it('caps entries; tells a missing folder (null) from a file', () => {
|
||||
for (let i = 0; i < 5; i++) touch(join(root, `f${i}.png`), 'x', 1_700_000_000);
|
||||
const capped = run(root, 3);
|
||||
expect(capped?.entries).toHaveLength(3);
|
||||
expect(capped?.truncated).toBe(true);
|
||||
expect(run(join(root, 'missing'))).toBeNull();
|
||||
expect(run(join(root, 'f0.png'))).toBe('not-a-folder');
|
||||
});
|
||||
});
|
||||
|
||||
describe('validFolderFileName', () => {
|
||||
it('accepts bare supported names only', () => {
|
||||
expect(validFolderFileName('a b.png')).toBe('a b.png');
|
||||
for (const bad of ['', '.', '..', '.hidden.png', 'a/b.png', 'a\\b.png', 'x.xyz', 'a\0.png', 42]) {
|
||||
expect(validFolderFileName(bad)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('server wiring', () => {
|
||||
// The route harness builds its own Fastify instance, so a test through it
|
||||
// cannot notice the real server losing the option. Same style as the other
|
||||
// wiring guards: read the source, not a comment.
|
||||
it('gives the real server the same route-parameter limit the folder routes are tested with', () => {
|
||||
const source = readFileSync(join(__dirname, '../../src/web/server.ts'), 'utf-8');
|
||||
const instances = source.match(/Fastify\(\{[^}]*\}[^)]*\)/g) ?? [];
|
||||
expect(instances.length).toBeGreaterThanOrEqual(2);
|
||||
for (const instance of instances) {
|
||||
expect(instance).toContain('maxParamLength: MAX_ROUTE_PARAM_LENGTH');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -308,7 +308,7 @@ describe('callers consult the hook first', () => {
|
||||
|
||||
it('response viewer links route through the hook and keep the file-path handler first', () => {
|
||||
const bind = APP_JS.indexOf('_bindResponseViewerInteractions(body) {');
|
||||
const section = APP_JS.slice(bind, bind + 2500);
|
||||
const section = APP_JS.slice(bind, bind + 3500);
|
||||
const pathHandler = section.indexOf("closest('a.rv-path')");
|
||||
const urlHandler = section.indexOf("closest('a[href]')");
|
||||
expect(pathHandler).toBeGreaterThan(-1);
|
||||
|
||||
Reference in new issue
Block a user