mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-02 13:39:41 +02:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24ed43935c |
+10
-51
@@ -135,14 +135,6 @@ const MUX_STARTUP_DELAY_MS = 300;
|
||||
/** Delay before declaring session idle after last output (2 seconds) */
|
||||
const IDLE_DETECTION_DELAY_MS = 2000;
|
||||
|
||||
// How long after construction a RECOVERED session's wire activity stamp keeps
|
||||
// its restored previous-run value. Recovery attaches every pane at boot and the
|
||||
// attach repaint arrives as ordinary PTY output; without this window that
|
||||
// repaint would overwrite every restored stamp within the same second, which is
|
||||
// exactly the restart flattening the restore exists to prevent. Real actions
|
||||
// (input, task assignment, respawn) always stamp through it.
|
||||
const WIRE_ACTIVITY_SETTLE_MS = 15_000;
|
||||
|
||||
// Note: Auto-compact/clear timing constants moved to session-auto-ops.ts
|
||||
|
||||
/** Graceful shutdown delay when stopping session (100ms) */
|
||||
@@ -400,12 +392,6 @@ export class Session extends EventEmitter {
|
||||
private _textOutput = new BufferAccumulator(MAX_TEXT_OUTPUT_SIZE, TEXT_OUTPUT_TRIM_SIZE);
|
||||
private _errorBuffer: string = '';
|
||||
private _lastActivityAt: number;
|
||||
// Display twin of _lastActivityAt, reported by toState()/the getter. It can
|
||||
// lag behind on recovery: the restored previous-run stamp survives the attach
|
||||
// repaint (see _markActivity), so a restart does not flatten the home
|
||||
// screens' quiet ordering. Idle detection never reads it.
|
||||
private _wireActivityAt: number;
|
||||
private _wireActivitySettleUntil: number;
|
||||
private _claudeSessionId: string | null = null;
|
||||
private _totalCost: number = 0;
|
||||
private _messages: ClaudeMessage[] = [];
|
||||
@@ -606,8 +592,6 @@ export class Session extends EventEmitter {
|
||||
attachmentHistory?: SessionAttachmentHistoryItem[];
|
||||
/** Restored wall-clock ms of the pane's last Enter (see `lastSubmitAt`). */
|
||||
lastSubmitAt?: number;
|
||||
/** Restored wall-clock ms of the pane's last output (recovery only; see `_wireActivityAt`). */
|
||||
lastActivityAt?: number;
|
||||
/** Remote execution metadata for sessions launched through SSH inside local tmux. */
|
||||
remote?: SessionRemote;
|
||||
/** Docker execution metadata for sessions launched inside a container via local tmux. */
|
||||
@@ -636,18 +620,9 @@ export class Session extends EventEmitter {
|
||||
// NOW, not `createdAt`: recovery passes the ORIGINAL creation time of a
|
||||
// days-old tmux session, and seeding last-activity from it would report a
|
||||
// freshly re-attached pane as having been silent for days, which the idle
|
||||
// confirmation reads as "already quiet". For a genuinely new session the
|
||||
// two are the same instant.
|
||||
// confirmation reads as "already quiet" and the home screens print as its
|
||||
// idle duration. For a genuinely new session the two are the same instant.
|
||||
this._lastActivityAt = Date.now();
|
||||
// The WIRE copy of the stamp is allowed to be older: recovery threads the
|
||||
// previous run's value so a restart does not flatten the home screens'
|
||||
// most-recently-quiet ordering (every stamp otherwise resets to boot time,
|
||||
// and the attach repaint re-bumps the rest within the same second). The
|
||||
// settle window in _markActivity() carries the restored value through that
|
||||
// repaint; the private stamp above stays boot-anchored because the idle
|
||||
// confirmation reads it as "how long has the pane been quiet".
|
||||
this._wireActivityAt = config.lastActivityAt || Date.now();
|
||||
this._wireActivitySettleUntil = config.lastActivityAt ? Date.now() + WIRE_ACTIVITY_SETTLE_MS : 0;
|
||||
// Set claudeSessionId — when resuming, the Claude conversation ID is the resumed one.
|
||||
this._claudeSessionId = config.resumeSessionId || this.id;
|
||||
// Restored from state.json on boot recovery. start() resets _claudeSessionId
|
||||
@@ -819,21 +794,7 @@ export class Session extends EventEmitter {
|
||||
}
|
||||
|
||||
get lastActivityAt(): number {
|
||||
return this._wireActivityAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamp activity NOW. The private stamp (idle detection's "how long has the
|
||||
* pane been quiet") always moves; the wire stamp holds its restored value
|
||||
* through the post-recovery attach-repaint window unless the activity is a
|
||||
* real action (input, task assignment, respawn), which always writes through.
|
||||
*/
|
||||
private _markActivity(realAction = false): void {
|
||||
this._lastActivityAt = Date.now();
|
||||
if (realAction || Date.now() >= this._wireActivitySettleUntil) {
|
||||
this._wireActivityAt = this._lastActivityAt;
|
||||
this._wireActivitySettleUntil = 0;
|
||||
}
|
||||
return this._lastActivityAt;
|
||||
}
|
||||
|
||||
get claudeSessionId(): string | null {
|
||||
@@ -1258,9 +1219,7 @@ export class Session extends EventEmitter {
|
||||
parentSessionId: this._parentSessionId,
|
||||
currentTaskId: this._currentTaskId,
|
||||
createdAt: this.createdAt,
|
||||
// The wire twin, not the private stamp: it survives the post-recovery
|
||||
// attach repaint, so the home screens' quiet ordering survives a restart.
|
||||
lastActivityAt: this._wireActivityAt,
|
||||
lastActivityAt: this._lastActivityAt,
|
||||
name: this._name,
|
||||
mode: this.mode,
|
||||
autoClearEnabled: this._autoOps.autoClearEnabled,
|
||||
@@ -1626,7 +1585,7 @@ export class Session extends EventEmitter {
|
||||
|
||||
// BufferAccumulator handles auto-trimming when max size exceeded
|
||||
this._terminalBuffer.append(data);
|
||||
this._markActivity();
|
||||
this._lastActivityAt = Date.now();
|
||||
this.emit('terminal', data);
|
||||
this.emit('output', data);
|
||||
}
|
||||
@@ -2525,7 +2484,7 @@ export class Session extends EventEmitter {
|
||||
this._messages = [];
|
||||
this._lineBuffer = '';
|
||||
this._altScreenSeqCarry = '';
|
||||
this._markActivity(true);
|
||||
this._lastActivityAt = Date.now();
|
||||
}
|
||||
|
||||
private _clearAllTimers(): void {
|
||||
@@ -3124,7 +3083,7 @@ export class Session extends EventEmitter {
|
||||
// Legacy method for sending input - wraps runPrompt
|
||||
async sendInput(input: string): Promise<void> {
|
||||
this._status = 'busy';
|
||||
this._markActivity(true);
|
||||
this._lastActivityAt = Date.now();
|
||||
this.runPrompt(input).catch((err) => {
|
||||
const errorMsg = getErrorMessage(err);
|
||||
// Clean up task state so the task queue doesn't get stuck
|
||||
@@ -3132,7 +3091,7 @@ export class Session extends EventEmitter {
|
||||
const taskId = this._currentTaskId;
|
||||
this._currentTaskId = null;
|
||||
this._status = 'idle';
|
||||
this._markActivity(true);
|
||||
this._lastActivityAt = Date.now();
|
||||
this.emit('taskError', taskId, errorMsg);
|
||||
} else {
|
||||
this._status = 'idle';
|
||||
@@ -3293,13 +3252,13 @@ export class Session extends EventEmitter {
|
||||
this._textOutput.clear();
|
||||
this._errorBuffer = '';
|
||||
this._messages = [];
|
||||
this._markActivity(true);
|
||||
this._lastActivityAt = Date.now();
|
||||
}
|
||||
|
||||
clearTask(): void {
|
||||
this._currentTaskId = null;
|
||||
this._status = 'idle';
|
||||
this._markActivity(true);
|
||||
this._lastActivityAt = Date.now();
|
||||
}
|
||||
|
||||
getOutput(): string {
|
||||
|
||||
+26
-15
@@ -1116,17 +1116,12 @@ class CodemanApp {
|
||||
if (digitMatch) {
|
||||
const idx = parseInt(digitMatch[1], 10) - 1;
|
||||
// Sessions occupy 1..N and web tabs continue from N+1, matching the
|
||||
// numbers actually painted on the tabs. Resolve through the same
|
||||
// live-session projection the render paints: sessionOrder can
|
||||
// transiently hold a dead id (delete raced against the order sync),
|
||||
// and raw indexing then names the wrong tab for every key to its
|
||||
// right, web tabs included.
|
||||
const live = this.sessionOrder.filter((id) => this.sessions.has(id));
|
||||
if (idx < live.length) {
|
||||
// numbers actually painted on the tabs.
|
||||
if (idx < this.sessionOrder.length) {
|
||||
e.preventDefault();
|
||||
this.selectSession(live[idx]);
|
||||
this.selectSession(this.sessionOrder[idx]);
|
||||
} else {
|
||||
const webIdx = idx - live.length;
|
||||
const webIdx = idx - this.sessionOrder.length;
|
||||
const webId = (this.webviewOrder || [])[webIdx];
|
||||
if (webId) {
|
||||
e.preventDefault();
|
||||
@@ -3831,7 +3826,6 @@ class CodemanApp {
|
||||
// Collapse/expand changes whether the filter is reachable, so re-evaluate it
|
||||
// here too — not only at the render tails.
|
||||
this.applySidebarFilter(this._sidebarFilter);
|
||||
this.updateSidebarCount();
|
||||
this.updateConnectionLines();
|
||||
// The desktop home rail defers to the sidebar (both dock the session list
|
||||
// flush left), so a layout flip while the welcome screen is up has to
|
||||
@@ -3876,9 +3870,22 @@ class CodemanApp {
|
||||
this.toggleSessionSidebar();
|
||||
}
|
||||
|
||||
/**
|
||||
* The count is what is actually ON the list: session rows plus web-tab rows,
|
||||
* minus whatever the sidebar filter is hiding. `this.sessions.size` was the
|
||||
* original source and disagreed with the screen twice over — web tabs render
|
||||
* in the same list but are not sessions (3 sessions + 2 dashboards read "3"
|
||||
* above 5 rows), and a filter hides rows without touching the map. Counting
|
||||
* the rendered rows keeps one source of truth: the list itself.
|
||||
*/
|
||||
updateSidebarCount() {
|
||||
const el = document.getElementById('sessionSidebarCount');
|
||||
if (el) el.textContent = String(this.sessions?.size ?? 0);
|
||||
if (!el) return;
|
||||
const container = this.$('sessionTabs');
|
||||
const count = container
|
||||
? container.querySelectorAll('.session-tab:not(.tab-filtered-out)').length
|
||||
: (this.sessions?.size ?? 0);
|
||||
el.textContent = String(count);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3911,6 +3918,9 @@ class CodemanApp {
|
||||
const haystack = `${tab.getAttribute('aria-label') || ''} ${tab.getAttribute('title') || ''}`.toLowerCase();
|
||||
tab.classList.toggle('tab-filtered-out', !haystack.includes(needle));
|
||||
}
|
||||
// The count shows visible rows, so it moves with every filter change —
|
||||
// including keystrokes in the filter box, which call this directly.
|
||||
this.updateSidebarCount();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -4267,11 +4277,13 @@ class CodemanApp {
|
||||
// The full-render path already redraws the connection SVG; this incremental
|
||||
// one does not, and a badge appearing widens a tab and shifts every tab after
|
||||
// it, sliding the lineage arcs off their anchors. Only pay for it when there
|
||||
// is an arc to keep anchored.
|
||||
if (this._lineageEdgeCount > 0) this.updateConnectionLines();
|
||||
// is something anchored to tab rects: lineage arcs, or — in sidebar layout,
|
||||
// where lineage is skipped and the edge count stays 0 — the subagent/
|
||||
// ultracode connectors, whose rows a badge changes the HEIGHT of. Same
|
||||
// widening as the strip-scroll listener in session-lineage.js.
|
||||
if (this._lineageEdgeCount > 0 || this.isSessionSidebarActive()) this.updateConnectionLines();
|
||||
|
||||
this.applySidebarFilter(this._sidebarFilter);
|
||||
this.updateSidebarCount();
|
||||
}
|
||||
|
||||
// Auto-wrap desktop session tabs to a second row when they overflow one row,
|
||||
@@ -4472,7 +4484,6 @@ class CodemanApp {
|
||||
// innerHTML was rebuilt wholesale, so the sidebar filter classes are gone —
|
||||
// re-apply them or filtered-out sessions flicker back on every SSE tick.
|
||||
this.applySidebarFilter(this._sidebarFilter);
|
||||
this.updateSidebarCount();
|
||||
}
|
||||
|
||||
// Set up arrow key navigation for session tabs (accessibility)
|
||||
|
||||
@@ -997,13 +997,16 @@ function computeRewriteScrollLine(input) {
|
||||
* never match) and terminated by a known extension (so the end of the path is
|
||||
* unambiguous — a trailing `)` or `.` after the extension stays out). Longer
|
||||
* extensions come first in each family (`tsx|ts`), so the trailing `\b` cannot
|
||||
* be satisfied by the shorter branch mid-word.
|
||||
* be satisfied by the shorter branch mid-word. `/etc` is deliberately NOT a
|
||||
* root: DEFAULT_BLOCKED_TREES (config/attachment-guard.ts) refuses the whole
|
||||
* tree server-side, so every `/etc/...` link was a guaranteed 403 — a link
|
||||
* that renders clickable and then dies is worse than plain text.
|
||||
*
|
||||
* ⚠ Consumers must never share one instance: `lastIndex` is per-object state on
|
||||
* a `/g` regex, so {@link absoluteFilePathPattern} mints a fresh one per call.
|
||||
*/
|
||||
const FILE_PATH_LINK_PATTERN =
|
||||
/(\/(?:home|Users|tmp|var|private|etc|opt|mnt|srv|media|data|workspace)\/[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|ya?ml|csv|xml|sh|py|tsx|ts|jsx|js|mjs|cjs|css|html|toml|ini|sql|png|jpe?g|gif|webp|bmp|svg|pdf|docx|pptx|mp4|webm|mov|mp3|wav))\b/g;
|
||||
/(\/(?:home|Users|tmp|var|private|opt|mnt|srv|media|data|workspace)\/[^\s"'<>|;&\n\x00-\x1f]*\.(?:log|txt|json|md|ya?ml|csv|xml|sh|py|tsx|ts|jsx|js|mjs|cjs|css|html|toml|ini|sql|png|jpe?g|gif|webp|bmp|svg|pdf|docx|pptx|mp4|webm|mov|mp3|wav))\b/g;
|
||||
|
||||
/** A fresh, zero-state instance of {@link FILE_PATH_LINK_PATTERN}. */
|
||||
function absoluteFilePathPattern() {
|
||||
@@ -1014,9 +1017,14 @@ function absoluteFilePathPattern() {
|
||||
* Extensions the file-preview overlay renders itself. Everything else a link
|
||||
* points at goes to the tail/log viewer, which is the right home for a growing
|
||||
* text file and the wrong one for bytes (tailing a PNG shows binary noise).
|
||||
*
|
||||
* The media entries mirror VIDEO_ATTACHMENT_EXTENSIONS/AUDIO_ATTACHMENT_EXTENSIONS
|
||||
* (src/attachment-registry.ts, the single source) — they diverged once and an
|
||||
* in-workspace `.m4a` opened as binary noise in the log viewer while the same
|
||||
* file in /tmp played fine. test/media-extension-parity.test.ts pins the sync.
|
||||
*/
|
||||
const FILE_PREVIEW_EXTENSIONS = new Set(
|
||||
('png jpg jpeg gif webp bmp svg pdf docx pptx mp4 webm mov mp3 wav').split(' ')
|
||||
('png jpg jpeg gif webp bmp svg pdf docx pptx mp4 webm mov m4v ogv mp3 wav ogg oga m4a aac flac opus').split(' ')
|
||||
);
|
||||
|
||||
/** Whether a path's extension is one {@link FILE_PREVIEW_EXTENSIONS} covers. */
|
||||
|
||||
@@ -118,16 +118,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
* A WORKING pane is the opposite: it repaints about once a second, so its
|
||||
* last-activity stamp is always "now" and would report every running turn as
|
||||
* 0m. The turn's own start is the pane's last Enter (`lastSubmitAt`), which is
|
||||
* persisted server-side and therefore survives a Codeman restart. A working
|
||||
* session with NO submit stamp falls back to `lastActivityAt`, because that is
|
||||
* exactly what `sessionActivityAnchor` (constants.js) sorts it by: a row must
|
||||
* never be ranked by a number it does not show.
|
||||
* persisted server-side and therefore survives a Codeman restart. A session
|
||||
* that has never submitted has no anchor at all, and gets no stamp rather than
|
||||
* a made-up one.
|
||||
*
|
||||
* @returns {{key: string, at: number}|null}
|
||||
*/
|
||||
_mobileOverviewSince(state, session) {
|
||||
const activeAt = Number(session.lastActivityAt) || 0;
|
||||
const at = state === 'working' ? Number(session.lastSubmitAt) || activeAt : activeAt;
|
||||
const at = state === 'working' ? Number(session.lastSubmitAt) || 0 : Number(session.lastActivityAt) || 0;
|
||||
if (!at) return null;
|
||||
return { key: MOBILE_OVERVIEW_SINCE_LABEL[state] || state, at };
|
||||
},
|
||||
|
||||
@@ -3346,6 +3346,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (attachmentId) {
|
||||
const base = `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}`;
|
||||
const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg']);
|
||||
// VIDEO/AUDIO mirror VIDEO_ATTACHMENT_EXTENSIONS/AUDIO_ATTACHMENT_EXTENSIONS
|
||||
// (src/attachment-registry.ts, the single source); the frontend cannot import
|
||||
// it, so test/media-extension-parity.test.ts pins the copies equal.
|
||||
const VIDEO_EXTS = new Set(['mp4', 'webm', 'mov', 'm4v', 'ogv']);
|
||||
const AUDIO_EXTS = new Set(['mp3', 'wav', 'ogg', 'oga', 'm4a', 'aac', 'flac', 'opus']);
|
||||
// Size when we just registered the file ourselves, so a path opened from a
|
||||
|
||||
@@ -148,11 +148,6 @@ export function registerHookEventRoutes(
|
||||
...safeData,
|
||||
...(approvalId && { approvalId }),
|
||||
});
|
||||
// Full state ride-along, same shape as the working/idle handlers: the home
|
||||
// screens rank the blocked group on lastActivityAt, and without this a
|
||||
// permission prompt raised after page load kept ranking by whatever stamp
|
||||
// the browser loaded with. Debounced, so a hook burst costs one broadcast.
|
||||
ctx.broadcastSessionStateDebounced(sessionId);
|
||||
|
||||
// Send push notifications for hook events
|
||||
ctx.sendPushNotifications(`hook:${event}`, {
|
||||
|
||||
@@ -29,6 +29,9 @@
|
||||
* symlink pointing at a sensitive target is also caught.
|
||||
*/
|
||||
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const SENSITIVE_PATTERNS: RegExp[] = [
|
||||
// System account databases.
|
||||
/^\/etc\/shadow$/,
|
||||
@@ -99,10 +102,26 @@ const SENSITIVE_PATTERNS: RegExp[] = [
|
||||
/\/\.codeman[^/]*\/intents\.json$/,
|
||||
];
|
||||
|
||||
/**
|
||||
* Claude config members that are credential-bearing ONLY under the user's real
|
||||
* home directory: `~/.claude/settings.json` can hold `env.ANTHROPIC_API_KEY`
|
||||
* and `apiKeyHelper` by schema (settings.local.json shares that schema), and
|
||||
* `~/.claude.json` holds account/OAuth-adjacent state. A blanket
|
||||
* `/\.claude\/settings\.json$/` would also block every CASE-level
|
||||
* `.claude/settings.json`, which users legitimately view and edit in the File
|
||||
* Viewer (model override, hooks) — so these are anchored to homedir(), read at
|
||||
* CHECK time inside isSensitivePath, never captured at module load (wrong for
|
||||
* anything that changes HOME later, e.g. per-file test fixtures — same
|
||||
* reasoning as the `.ssh/` note above).
|
||||
*/
|
||||
const HOME_SENSITIVE_MEMBERS = ['.claude.json', '.claude/settings.json', '.claude/settings.local.json'];
|
||||
|
||||
/**
|
||||
* Returns true if the given ABSOLUTE, symlink-resolved path matches the
|
||||
* sensitive-file blocklist and must not be served to the browser.
|
||||
*/
|
||||
export function isSensitivePath(absPath: string): boolean {
|
||||
return SENSITIVE_PATTERNS.some((pattern) => pattern.test(absPath));
|
||||
if (SENSITIVE_PATTERNS.some((pattern) => pattern.test(absPath))) return true;
|
||||
const home = homedir();
|
||||
return HOME_SENSITIVE_MEMBERS.some((member) => absPath === join(home, member));
|
||||
}
|
||||
|
||||
@@ -2657,11 +2657,6 @@ export class WebServer extends EventEmitter {
|
||||
// the launch conversation until the user types again, even though
|
||||
// the re-attached CLI is on a post-`/clear` one.
|
||||
lastSubmitAt: savedState?.lastSubmitAt,
|
||||
// The pane's last output, previous run's value. Without it every
|
||||
// restart restamped all sessions "now" (constructor + the attach
|
||||
// repaint within the same second), flattening the home screens'
|
||||
// most-recently-quiet ordering to tab order after each deploy.
|
||||
lastActivityAt: savedState?.lastActivityAt,
|
||||
// Remote SSH metadata must round-trip on recovery: without it the
|
||||
// attach cwd falls back to the (nonexistent-locally) remote path and
|
||||
// respawn rebuilds a LOCAL command, breaking the pane and silently
|
||||
|
||||
@@ -270,75 +270,3 @@ describe('home sessions column: wiring', () => {
|
||||
expect(html.indexOf('src="mobile-overview.js"')).toBeGreaterThan(html.indexOf('src="constants.js"'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('home screens: one order, one numbering', () => {
|
||||
it('produces the same order on the rail and the phone overview for one input', () => {
|
||||
// Both surfaces claim to share CodemanSessionOrder. Nothing used to assert
|
||||
// they actually produce one order for one input, so a future local sort in
|
||||
// either builder would silently split them. The rail is one list; the phone
|
||||
// splits NEEDS YOU / CURRENT, so rail order must equal the concatenation.
|
||||
const fixture = [
|
||||
{ id: 'blocked-new', lastActivityAt: 5_000 },
|
||||
{ id: 'idle-old', lastActivityAt: 3_000 },
|
||||
{ id: 'run-new', status: 'busy', lastSubmitAt: 8_000, lastActivityAt: 9_500 },
|
||||
{ id: 'blocked-old', lastActivityAt: 1_000 },
|
||||
{ id: 'run-old', status: 'busy', lastSubmitAt: 2_000, lastActivityAt: 9_600 },
|
||||
{ id: 'idle-new', lastActivityAt: 9_000 },
|
||||
];
|
||||
const pendingHooks = new Map([
|
||||
['blocked-new', new Set(['permission_prompt'])],
|
||||
['blocked-old', new Set(['permission_prompt'])],
|
||||
]);
|
||||
const sessionOrder = fixture.map((s) => s.id);
|
||||
const app = loadHomeSessionsApp({
|
||||
sessions: sessionMap(fixture),
|
||||
sessionOrder,
|
||||
cases: CASES,
|
||||
pendingHooks,
|
||||
});
|
||||
|
||||
const railIds = app.buildHomeSessionRows().map((r: any) => r.id);
|
||||
const model = app.buildMobileOverviewModel({
|
||||
sessions: app.sessions,
|
||||
cases: CASES,
|
||||
sessionOrder,
|
||||
pendingHooks,
|
||||
});
|
||||
const phoneIds = [...model.needsYou, ...model.current].map((r: any) => r.id);
|
||||
|
||||
expect(railIds).toEqual(phoneIds);
|
||||
// And the shared order is the documented one: blocked longest-first, then
|
||||
// running longest-first, then quiet newest-first.
|
||||
expect(railIds).toEqual(['blocked-old', 'blocked-new', 'run-old', 'run-new', 'idle-new', 'idle-old']);
|
||||
});
|
||||
|
||||
it('numbers rows over the LIVE projection when sessionOrder holds a dead id', () => {
|
||||
// sessionOrder can transiently contain a deleted session (delete raced the
|
||||
// order sync). The strip paints numbers over live sessions only, and the
|
||||
// Alt+digit handler resolves through the same projection, so the rail must
|
||||
// number alpha=1, beta=2 with no hole where the ghost sits.
|
||||
const app = loadHomeSessionsApp({
|
||||
sessions: sessionMap([{ id: 'alpha' }, { id: 'beta' }]),
|
||||
sessionOrder: ['ghost', 'alpha', 'beta'],
|
||||
cases: CASES,
|
||||
});
|
||||
expect(app.buildHomeSessionRows().map((r: any) => [r.id, r.orderIndex])).toEqual([
|
||||
['alpha', 0],
|
||||
['beta', 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it('Alt+digit resolves through the live-session projection in app.js', () => {
|
||||
// Static guard for the handler half of the invariant above: the digit
|
||||
// branch must filter sessionOrder against live sessions before indexing,
|
||||
// for sessions AND for the web-tab continuation.
|
||||
const appJs = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
const start = appJs.indexOf('^Digit([1-9])$');
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const branch = appJs.slice(start, start + 1200);
|
||||
expect(branch).toContain('this.sessionOrder.filter((id) => this.sessions.has(id))');
|
||||
expect(branch).toContain('idx < live.length');
|
||||
expect(branch).toContain('idx - live.length');
|
||||
expect(branch).not.toContain('this.sessionOrder[idx]');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -150,6 +150,23 @@ describe('terminal link-provider regexes (shipped source)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('the file-path pattern refuses /etc roots (blocked server-side, so the link could only 403)', () => {
|
||||
// `/etc` sits in DEFAULT_BLOCKED_TREES (config/attachment-guard.ts), so an
|
||||
// /etc link is guaranteed dead: it renders clickable, then the preview 403s.
|
||||
// It used to be in the root alternation, which linked exactly those paths.
|
||||
const ext = shippedPattern('FILE_PATH_LINK_PATTERN');
|
||||
const cases = [
|
||||
'see /etc/hosts here',
|
||||
// Extension-bearing, so only the root removal keeps it out.
|
||||
'see /etc/app/config.json here',
|
||||
'cat /etc/nginx/nginx.conf.txt',
|
||||
];
|
||||
for (const line of cases) {
|
||||
ext.lastIndex = 0;
|
||||
expect(ext.exec(line), line).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('terminal-ui builds its path pattern from the shared factory', () => {
|
||||
// Structural guard: a local literal here would drift from the response
|
||||
// viewer's linkifier, which is the divergence the move exists to prevent.
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* @fileoverview Media-extension parity — attachment registry ⇄ frontend copies.
|
||||
*
|
||||
* CLAUDE.md single-sources playable media extensions in
|
||||
* `VIDEO_ATTACHMENT_EXTENSIONS`/`AUDIO_ATTACHMENT_EXTENSIONS`
|
||||
* (src/attachment-registry.ts): the workspace preview and the out-of-workspace
|
||||
* attachment path must agree on what plays. The frontend cannot import that
|
||||
* module, so two hand-maintained copies exist and BOTH have drifted:
|
||||
*
|
||||
* - `FILE_PREVIEW_EXTENSIONS` (constants.js) decides whether a clicked
|
||||
* terminal/chat path opens the preview overlay or the tail/log viewer. It
|
||||
* was missing `m4v ogv ogg oga m4a aac flac opus`, so an in-workspace
|
||||
* `.m4a` routed to the log viewer and rendered as binary noise while the
|
||||
* same file in /tmp played fine.
|
||||
* - `VIDEO_EXTS`/`AUDIO_EXTS` (panels-ui.js) pick the <video>/<audio> markup
|
||||
* for registered attachments; an entry missing there renders a text dump
|
||||
* instead of a player.
|
||||
*
|
||||
* Same technique as test/sse-registry-parity.test.ts: the backend sets are
|
||||
* imported, the frontend copies are extracted from the shipped source as text
|
||||
* (no build-time link exists), and the sets are compared. No port needed.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { AUDIO_ATTACHMENT_EXTENSIONS, VIDEO_ATTACHMENT_EXTENSIONS } from '../src/attachment-registry.js';
|
||||
|
||||
const publicFile = (name: string) =>
|
||||
readFileSync(resolve(import.meta.dirname, '..', 'src', 'web', 'public', name), 'utf8');
|
||||
|
||||
/** `FILE_PREVIEW_EXTENSIONS` is a space-separated string literal in constants.js. */
|
||||
function filePreviewExtensions(): Set<string> {
|
||||
const src = publicFile('constants.js');
|
||||
const m = src.match(/const FILE_PREVIEW_EXTENSIONS = new Set\(\s*\('([^']+)'\)\.split\(' '\)\s*\)/);
|
||||
expect(m, 'FILE_PREVIEW_EXTENSIONS literal not found in constants.js').not.toBeNull();
|
||||
return new Set(m![1].split(' '));
|
||||
}
|
||||
|
||||
/** `VIDEO_EXTS`/`AUDIO_EXTS` are quoted-string array Sets in panels-ui.js. */
|
||||
function panelsUiSet(name: string): Set<string> {
|
||||
const src = publicFile('panels-ui.js');
|
||||
const m = src.match(new RegExp(`const ${name} = new Set\\(\\[([^\\]]+)\\]\\)`));
|
||||
expect(m, `${name} literal not found in panels-ui.js`).not.toBeNull();
|
||||
const values = [...m![1].matchAll(/'([^']+)'/g)].map((q) => q[1]);
|
||||
return new Set(values);
|
||||
}
|
||||
|
||||
const sorted = (s: ReadonlySet<string>) => [...s].sort();
|
||||
|
||||
describe('media extension parity (attachment registry ⇄ frontend)', () => {
|
||||
it('extracts non-trivial sets from every source (guards the parsers)', () => {
|
||||
expect(VIDEO_ATTACHMENT_EXTENSIONS.size).toBeGreaterThanOrEqual(5);
|
||||
expect(AUDIO_ATTACHMENT_EXTENSIONS.size).toBeGreaterThanOrEqual(8);
|
||||
expect(filePreviewExtensions().size).toBeGreaterThan(10);
|
||||
expect(panelsUiSet('VIDEO_EXTS').size).toBeGreaterThanOrEqual(5);
|
||||
expect(panelsUiSet('AUDIO_EXTS').size).toBeGreaterThanOrEqual(8);
|
||||
});
|
||||
|
||||
it('every playable media extension routes to the preview overlay, not the log viewer', () => {
|
||||
const preview = filePreviewExtensions();
|
||||
const missing = [...VIDEO_ATTACHMENT_EXTENSIONS, ...AUDIO_ATTACHMENT_EXTENSIONS].filter((e) => !preview.has(e));
|
||||
expect(
|
||||
missing,
|
||||
`media extensions in attachment-registry.ts but not constants.js FILE_PREVIEW_EXTENSIONS: ${missing.join(', ')}`
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("panels-ui.js VIDEO_EXTS exactly equals the registry's video set", () => {
|
||||
expect(sorted(panelsUiSet('VIDEO_EXTS'))).toEqual(sorted(VIDEO_ATTACHMENT_EXTENSIONS));
|
||||
});
|
||||
|
||||
it("panels-ui.js AUDIO_EXTS exactly equals the registry's audio set", () => {
|
||||
expect(sorted(panelsUiSet('AUDIO_EXTS'))).toEqual(sorted(AUDIO_ATTACHMENT_EXTENSIONS));
|
||||
});
|
||||
});
|
||||
@@ -277,28 +277,15 @@ describe('mobile overview model', () => {
|
||||
expect(rows.i.createdAt).toBe(now - 7200_000);
|
||||
});
|
||||
|
||||
it('falls back to the sort anchor for a working row with no submit stamp', () => {
|
||||
// A session that has never submitted has no turn start to measure from, but
|
||||
// `sessionActivityAnchor` still RANKS it by lastActivityAt. The stamp must
|
||||
// show that same number rather than nothing: a row sorted by a value it
|
||||
// does not display reads as randomly placed.
|
||||
const now = Date.now();
|
||||
it('leaves the stamp off rather than inventing an anchor', () => {
|
||||
const app = loadOverviewApp();
|
||||
const model = app.buildMobileOverviewModel({
|
||||
sessions: [session({ id: 'w', status: 'busy', lastActivityAt: now })],
|
||||
cases: CASES,
|
||||
});
|
||||
expect(model.current[0].since).toEqual({ key: 'working', at: now });
|
||||
expect(model.current[0].createdAt).toBe(0);
|
||||
});
|
||||
|
||||
it('still leaves the stamp off when there is no anchor at all', () => {
|
||||
const app = loadOverviewApp();
|
||||
const model = app.buildMobileOverviewModel({
|
||||
sessions: [session({ id: 'w', status: 'busy' })],
|
||||
// A session that has never submitted has no turn start to measure from.
|
||||
sessions: [session({ id: 'w', status: 'busy', lastActivityAt: Date.now() })],
|
||||
cases: CASES,
|
||||
});
|
||||
expect(model.current[0].since).toBeNull();
|
||||
expect(model.current[0].createdAt).toBe(0);
|
||||
});
|
||||
|
||||
it('formats a moment as "ago" and a span as a bare duration', () => {
|
||||
|
||||
@@ -117,6 +117,16 @@ describe('response viewer file-path linkifier', () => {
|
||||
expect(root.textContent).toBe('Ratio 3/4 on 2026/08/16, see src/app.ts');
|
||||
});
|
||||
|
||||
it('never linkifies /etc paths — the server blocks the whole tree, so the link could only 403', () => {
|
||||
// /etc sits in DEFAULT_BLOCKED_TREES (config/attachment-guard.ts); it used
|
||||
// to be a root in the shared pattern, which made every /etc link a
|
||||
// guaranteed-dead click on both surfaces.
|
||||
const root = linkify('<p>Check /etc/hosts and /etc/app/config.json for the mapping.</p>');
|
||||
|
||||
expect(paths(root)).toHaveLength(0);
|
||||
expect(root.textContent).toBe('Check /etc/hosts and /etc/app/config.json for the mapping.');
|
||||
});
|
||||
|
||||
it('cannot turn model text into markup', () => {
|
||||
// The anchor is built with createElement + textContent, so even a
|
||||
// path-shaped payload stays text. (`<` also ends a match, so the linkifier
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
* feature), so the "stays attachable" cases matter just as much: over-blocking
|
||||
* breaks the publish skill and the review-card loop.
|
||||
*/
|
||||
import { homedir } from 'node:os';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isSensitivePath } from '../src/web/sensitive-path.js';
|
||||
|
||||
@@ -122,4 +123,34 @@ describe('isSensitivePath', () => {
|
||||
expect(isSensitivePath('/srv/app/looks-innocent')).toBe(false);
|
||||
expect(isSensitivePath(`${HOME}/.ssh/looks-innocent`)).toBe(true);
|
||||
});
|
||||
|
||||
describe('home-anchored Claude config (credential-bearing by schema)', () => {
|
||||
// ~/.claude/settings.json can hold `env: {ANTHROPIC_API_KEY}` and
|
||||
// `apiKeyHelper` by schema (settings.local.json shares it), and
|
||||
// ~/.claude.json holds account/OAuth-adjacent state. These are anchored to
|
||||
// the REAL homedir, read at CHECK time — test/setup.ts points HOME at a
|
||||
// per-file fixture, so a homedir() captured at module load would be a
|
||||
// different directory than the one this suite resolves.
|
||||
const home = homedir();
|
||||
|
||||
it.each([
|
||||
['claude account state', `${home}/.claude.json`],
|
||||
['claude user settings', `${home}/.claude/settings.json`],
|
||||
['claude user local settings', `${home}/.claude/settings.local.json`],
|
||||
])('blocks the %s', (_label, path) => {
|
||||
expect(isSensitivePath(path)).toBe(true);
|
||||
});
|
||||
|
||||
// A blanket `/\.claude\/settings\.json$/` would also catch every CASE-level
|
||||
// settings file, which users legitimately view and edit in the File Viewer
|
||||
// (model override, hooks) — the home anchor is what keeps those servable.
|
||||
it.each([
|
||||
['a case-level .claude/settings.json', '/srv/app/.claude/settings.json'],
|
||||
['a case-level .claude/settings.local.json', '/srv/app/.claude/settings.local.json'],
|
||||
['a .claude/settings.json under some OTHER home', `${HOME}/.claude/settings.json`],
|
||||
['a .claude.json under some OTHER home', `${HOME}/.claude.json`],
|
||||
])('keeps %s servable', (_label, path) => {
|
||||
expect(isSensitivePath(path)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -246,45 +246,3 @@ describe('Session interactive idle detection', () => {
|
||||
expect(events).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('wire activity stamp across recovery', () => {
|
||||
// The stamp both home screens sort the quiet group on. Recovery restores the
|
||||
// previous run's value, and the settle window keeps the boot attach repaint
|
||||
// (ordinary PTY output, arriving within seconds of construction) from
|
||||
// restamping every session "now": measured live, a restart left 17 of 17
|
||||
// sessions with an identical lastActivityAt, which flattens the ordering to
|
||||
// tab order after every deploy.
|
||||
const OLD = 1_700_000_000_000;
|
||||
const restored = () =>
|
||||
new Session({ workingDir: '/tmp', mode: 'claude', lastActivityAt: OLD } as ConstructorParameters<
|
||||
typeof Session
|
||||
>[0]);
|
||||
|
||||
it('restores the previous-run stamp and holds it through attach-repaint output', () => {
|
||||
const session = restored();
|
||||
expect(session.lastActivityAt).toBe(OLD);
|
||||
(session as unknown as SessionInternals)._handleTerminalOutput('attach repaint bytes');
|
||||
expect(session.lastActivityAt).toBe(OLD);
|
||||
expect(session.toState().lastActivityAt).toBe(OLD);
|
||||
});
|
||||
|
||||
it('a real action writes through the settle window', () => {
|
||||
const session = restored();
|
||||
session.assignTask('t1');
|
||||
expect(session.lastActivityAt).toBeGreaterThan(OLD);
|
||||
});
|
||||
|
||||
it('output after the window moves the stamp normally', () => {
|
||||
const session = restored();
|
||||
(session as unknown as { _wireActivitySettleUntil: number })._wireActivitySettleUntil = Date.now() - 1;
|
||||
(session as unknown as SessionInternals)._handleTerminalOutput('real output');
|
||||
expect(session.lastActivityAt).toBeGreaterThan(OLD);
|
||||
});
|
||||
|
||||
it('a fresh session has no window: first output stamps immediately', () => {
|
||||
const before = Date.now();
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
|
||||
(session as unknown as SessionInternals)._handleTerminalOutput('x');
|
||||
expect(session.lastActivityAt).toBeGreaterThanOrEqual(before);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -394,15 +394,32 @@ describe('session list layout', () => {
|
||||
expect((drawer.win.document.activeElement as HTMLElement).className).toContain('session-tab');
|
||||
});
|
||||
|
||||
it('shows the live session count in the sidebar header', () => {
|
||||
it('counts the rows actually on the list: web tabs included, filtered rows excluded', () => {
|
||||
// this.sessions.size was the original source and disagreed with the screen
|
||||
// twice over: web tabs render in the same list but are not sessions (3
|
||||
// sessions + 2 dashboards read "3" above 5 rows), and the filter hides
|
||||
// rows without touching the map.
|
||||
const { win, app } = boot({ stored: { sessionListLayout: 'sidebar' } });
|
||||
app.sessions = new Map([
|
||||
['a', {}],
|
||||
['b', {}],
|
||||
['c', {}],
|
||||
]);
|
||||
app.applySessionListLayout();
|
||||
expect(win.document.getElementById('sessionSidebarCount')?.textContent).toBe('3');
|
||||
tabsEl(win).innerHTML = `
|
||||
<div class="session-tab" data-id="a" aria-label="api server" title="/srv/api"></div>
|
||||
<div class="session-tab" data-id="b" aria-label="docs" title="/home/docs"></div>
|
||||
<div class="session-tab session-tab--web" data-webview-id="w" aria-label="Grafana web tab" title="http://x/g"></div>
|
||||
`;
|
||||
app.updateSidebarCount();
|
||||
const count = () => win.document.getElementById('sessionSidebarCount')?.textContent;
|
||||
expect(count()).toBe('3');
|
||||
|
||||
// The count follows the filter — applySidebarFilter is what the filter box
|
||||
// calls per keystroke, so it must move without waiting for a re-render.
|
||||
app.applySidebarFilter('api');
|
||||
expect(count()).toBe('1');
|
||||
app.applySidebarFilter('');
|
||||
expect(count()).toBe('3');
|
||||
});
|
||||
|
||||
it('forces tall rows and no wrapping in the sidebar, and leaves the strip rules alone', () => {
|
||||
|
||||
Reference in New Issue
Block a user