mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-02 00:59:32 +01:00
feat(preview): folder grid — browse every previewable file of a folder
Folder paths in the terminal and the response viewer are now links (rooted or ~/ without an extension, relative with a trailing slash); a click opens a grid of the folder's supported files, newest first, with subfolder chips and a parent button. A tile opens the file preview, which pages through the folder with ‹ › / ←/→; the preview of any file gets a "Show folder" button. Server: POST /api/sessions/:id/folders grants + lists a folder (local fs or one ssh round trip for a remote case) under the attachment guard; GET …/folders/:folderId/files/:name/(raw|preview|thumbnail) serves one file by bare name through resolveServableAttachmentPath, so browser requests still never carry a path. Grants live in their own small registry so a big folder cannot evict the session's attachments. The attachment raw route's body is now the shared serveServableRaw helper. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
7d46a9d336
commit
1010d80b4f
16 files changed
+1706
-44
No files matched your search
@@ -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,349 @@
|
||||
/**
|
||||
* @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('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('"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' });
|
||||
});
|
||||
});
|
||||
@@ -41,6 +41,7 @@ const PATTERN_NAMES = [
|
||||
'cmdPattern',
|
||||
'FILE_PATH_LINK_PATTERN',
|
||||
'RELATIVE_FILE_PATH_LINK_PATTERN',
|
||||
'FOLDER_PATH_LINK_PATTERN',
|
||||
'bashPattern',
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
/**
|
||||
* @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 { mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';
|
||||
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(),
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
buildRemoteFolderListCommand,
|
||||
parseRemoteFolderListOutput,
|
||||
remoteCreateReadStream,
|
||||
remoteListFolder,
|
||||
remoteProbePaths,
|
||||
} from '../../src/remote-files.js';
|
||||
|
||||
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('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);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
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, '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]));
|
||||
expect(Object.keys(byName).sort()).toEqual(['doc.pdf', "it's a | frame.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('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 ['', '.', '..', 'a/b.png', 'a\\b.png', 'x.xyz', 'a\0.png', 42]) {
|
||||
expect(validFolderFileName(bad)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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