From 97d2521b5633a3eeedad65e2c865a3fbb574217a Mon Sep 17 00:00:00 2001 From: maxliux5 <5958865+maxliux5@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:53:10 +0000 Subject: [PATCH 1/2] fix(workbench): list local agent sessions from every directory The sidebar only listed Claude Code / Codex sessions whose directory was already a workdir (by default the LoopX checkout and /tmp), so a new user saw almost none of their history. Follow Persona: list sessions from every existing directory, and bound the list by the per-agent cap, the existing probe filter and a new hidden-directory list (LOOCHAT_HIDDEN_SESSION_DIRS). Workdirs still bound where threads may work. Importing a session from outside them now adds its directory, the same as adding it from the page; only the person's import click does this, the LoopX Goal sync never widens the workdirs. Sessions in a home directory or the root that no workdir covers are not listed, since they could never be continued. Co-Authored-By: Claude Opus 5.5 Signed-off-by: maxliux5 <5958865+maxliux5@users.noreply.github.com> --- apps/workbench/.env.example | 5 +++ apps/workbench/README.md | 2 +- apps/workbench/packages/daemon/src/config.ts | 4 +++ apps/workbench/packages/daemon/src/http.ts | 5 +-- apps/workbench/packages/daemon/src/index.ts | 6 ++-- .../packages/daemon/src/local-sessions.ts | 30 ++++++++++------ apps/workbench/packages/daemon/src/threads.ts | 25 ++++++++----- .../workbench/packages/daemon/src/workdirs.ts | 2 +- .../packages/daemon/test/api.test.ts | 31 +++++++++++----- .../daemon/test/local-sessions.test.ts | 36 ++++++++++++++----- 10 files changed, 103 insertions(+), 43 deletions(-) diff --git a/apps/workbench/.env.example b/apps/workbench/.env.example index 4e849df115..8556e39ebc 100644 --- a/apps/workbench/.env.example +++ b/apps/workbench/.env.example @@ -26,6 +26,11 @@ LOOCHAT_DSH_BIN= # Working directories offered in the UI, comma-separated. Empty means the daemon's start directory. LOOCHAT_WORKDIRS=/path/to/project-a,/path/to/project-b +# The sidebar lists this machine's Claude Code / Codex / … sessions from every directory; importing +# one from outside the working directories adds its directory. Directories listed here (and those +# below them), comma-separated, are left out of that list. +LOOCHAT_HIDDEN_SESSION_DIRS= + # Shell that runs in a web terminal. Empty means $SHELL, then /bin/bash. LOOCHAT_TERM_SHELL= diff --git a/apps/workbench/README.md b/apps/workbench/README.md index 3542288a30..7e39003895 100644 --- a/apps/workbench/README.md +++ b/apps/workbench/README.md @@ -246,7 +246,7 @@ npm test -w @calli/e2e -- --test-concurrency=1 test/smoke.spec.mjs - HTTP 监听上的 API 需要 `Authorization: Bearer `,`/api/health` 除外;仅本机用户能访问的私有 Unix socket 免 token,由本机用户文件权限保护。 - daemon 等同于远程 shell。只把它暴露在可信网络(VPN)中。 -- 工作目录必须在 `LOOCHAT_WORKDIRS` 白名单内。 +- 工作目录必须在 `LOOCHAT_WORKDIRS` 白名单内,或是从页面添加的目录。侧栏列出本机所有目录里的 Agent 会话;导入白名单外的会话时,会把它所在的目录加入工作目录(home 或根目录本身除外)。不想列出的目录写进 `LOOCHAT_HIDDEN_SESSION_DIRS`。 ## 许可证 diff --git a/apps/workbench/packages/daemon/src/config.ts b/apps/workbench/packages/daemon/src/config.ts index 72c26114d7..051eb8c119 100644 --- a/apps/workbench/packages/daemon/src/config.ts +++ b/apps/workbench/packages/daemon/src/config.ts @@ -11,6 +11,8 @@ export interface Config { dataDir: string; /** Directories the UI may start threads in. Empty means the daemon's cwd only. */ workdirs: string[]; + /** Directories whose agent sessions the session list leaves out. Every other one is listed. */ + hiddenSessionDirs: string[]; /** Full argv used to start the Claude ACP adapter. */ claudeCommand: string[]; /** Executable used to start pi in RPC mode. */ @@ -127,6 +129,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { const dataDir = resolve(env.LOOCHAT_DATA_DIR || './data'); const workdirs = splitList(env.LOOCHAT_WORKDIRS).map((d) => (isAbsolute(d) ? d : resolve(d))); + const hiddenSessionDirs = splitList(env.LOOCHAT_HIDDEN_SESSION_DIRS).map((d) => (isAbsolute(d) ? d : resolve(d))); const claudeCommand = env.LOOCHAT_CLAUDE_ACP_BIN ? [env.LOOCHAT_CLAUDE_ACP_BIN] : defaultClaudeCommand(); const piCommand = [env.LOOCHAT_PI_BIN || 'pi']; @@ -153,6 +156,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { token, dataDir, workdirs, + hiddenSessionDirs, claudeCommand, piCommand, agyCommand, diff --git a/apps/workbench/packages/daemon/src/http.ts b/apps/workbench/packages/daemon/src/http.ts index 7fa71d39d4..fbb869542a 100644 --- a/apps/workbench/packages/daemon/src/http.ts +++ b/apps/workbench/packages/daemon/src/http.ts @@ -921,10 +921,11 @@ export function createHttpServer(deps: HttpDeps): Server { return sendJson(res, 200, machineUsage.report(hours, url.searchParams.get('model'), url.searchParams.get('launcher'))); } - // POST /api/threads/import: turn an existing agent session into a thread + // POST /api/threads/import: turn an existing agent session into a thread. The person asked for + // this one, so a session from outside the workdirs brings its directory in. if (method === 'POST' && path === '/api/threads/import') { const body = await readJson(req); - return sendJson(res, 201, await manager.importSession({ agent: body.agent, sessionId: body.sessionId })); + return sendJson(res, 201, await manager.importSession({ agent: body.agent, sessionId: body.sessionId, addDirectory: true })); } // GET /api/worktree-options?cwd=: whether a new thread there could start in a git worktree diff --git a/apps/workbench/packages/daemon/src/index.ts b/apps/workbench/packages/daemon/src/index.ts index 36ea6eaab8..7d2478373f 100644 --- a/apps/workbench/packages/daemon/src/index.ts +++ b/apps/workbench/packages/daemon/src/index.ts @@ -94,6 +94,7 @@ async function main(): Promise { const localSessions: LocalSessions = new LocalSessions({ adapters, workdirs: () => manager.allowedWorkdirs, + hidden: () => config.hiddenSessionDirs, importedSessions: () => store.agentSessionOwners(), instances: () => registry.list().map((instance) => ({ id: instance.id, hidden: !!instance.hidden, store: sessionStoreKey(instance) })), enricher: new SessionEnricher({ bindings: () => loopx.lookup().bindings(), goal: (goalId) => loopx.lookup().goal(goalId) }), @@ -115,9 +116,8 @@ async function main(): Promise { // a scratch area there too. const dirs = new Workdirs(workdirs, join(config.dataDir, 'workdirs.json'), join(config.dataDir, 'scratch')); const manager = new ThreadManager(store, adapters, dirs, new AttachmentStore(config.dataDir), () => registry.list()); - // The session list scans once here (it asks the manager for the allowed directories) and then - // only when a request finds it stale; the meter keeps its own timer, files only. Stopped in - // shutdown with everything else. + // The session list scans once here and then only when a request finds it stale; the meter keeps + // its own timer, files only. Stopped in shutdown with everything else. // LoopX Goal conversations: bindings, the core client and the Goal context; ordinary threads never touch it. const loopx = new LoopxService({ dataDir: config.dataDir, adapters, dirs }); loopx.attach(manager); diff --git a/apps/workbench/packages/daemon/src/local-sessions.ts b/apps/workbench/packages/daemon/src/local-sessions.ts index efbe9adc7f..df0537b3e4 100644 --- a/apps/workbench/packages/daemon/src/local-sessions.ts +++ b/apps/workbench/packages/daemon/src/local-sessions.ts @@ -1,6 +1,6 @@ import { stat } from 'node:fs/promises'; import type { AgentAdapter, AgentSessionSummary } from './adapters/types.js'; -import { isWithinWorkdirs } from './workdirs.js'; +import { isWithinWorkdirs, tooWide } from './workdirs.js'; import type { SessionEnricher, SessionLoopx } from './session-enrich.js'; /** A conversation an agent on this machine already has, that is not a thread here yet. */ @@ -28,7 +28,12 @@ export interface LocalSessionPage { export interface LocalSessionsDeps { adapters: Map; + /** Where threads may work now. A session elsewhere is still listed, since importing it adds its + * directory; only one in a directory too wide to add (a home directory itself) needs to be in here. */ workdirs: () => string[]; + /** Directories whose sessions (and those below them) are not listed: the person's way to keep a + * project out of the list. Every other directory on the machine is listed. */ + hidden?: () => string[]; /** Every thread's agent session, sessionId → instance id, read once per page call: a session * that is a thread anywhere is not external. */ importedSessions: () => Map; @@ -67,8 +72,10 @@ const MAX_PER_AGENT = 2000; * from — asking an agent costs a process, so a scan runs once after startup and then only when a * request finds the list stale. Only the outline is kept (agent, session id, directory, title, * last activity); the past turns are read by the existing import only when one is opened. - * Sessions outside the allowed directories, in removed directories, or already a thread here are - * left out. Together with machine-usage.ts this is the one subsystem that reads what the agents + * Every directory on the machine is listed, as the agents' own pickers do: the allowed workdirs + * bound where a thread may work, not what can be found, and importing a session from elsewhere + * adds its directory then. Sessions in hidden or removed directories, in a home directory or the + * root that no workdir covers, or already a thread here, are left out; the newest MAX_PER_AGENT of each store bound the rest. Together with machine-usage.ts this is the one subsystem that reads what the agents * on this machine have been doing; `LOOCHAT_LOCAL_SCAN=off` stands both down. */ export class LocalSessions { @@ -117,15 +124,18 @@ export class LocalSessions { if (!this.enabled) return; const now = this.deps.now?.() ?? Date.now(); const workdirs = this.deps.workdirs(); - const allowed = new Map(); + const hidden = this.deps.hidden?.() ?? []; + const listable = new Map(); const ok = async (cwd: string): Promise => { - let within = allowed.get(cwd); - if (within === undefined) { - // A session whose directory has since been removed cannot be continued, so it is not listed. - within = !!cwd && isWithinWorkdirs(cwd, workdirs) && (await isDirectory(cwd)); - allowed.set(cwd, within); + let listed = listable.get(cwd); + if (listed === undefined) { + // A session whose directory has since been removed, or that could never become a workdir, + // cannot be continued here, so it is not listed. + listed = !!cwd && !(hidden.length && isWithinWorkdirs(cwd, hidden)) + && (isWithinWorkdirs(cwd, workdirs) || !tooWide(cwd)) && (await isDirectory(cwd)); + listable.set(cwd, listed); } - return within; + return listed; }; // One representative per store: instances of one adapter that share the store's env list the diff --git a/apps/workbench/packages/daemon/src/threads.ts b/apps/workbench/packages/daemon/src/threads.ts index 9b379bed8f..f3d9d5de26 100644 --- a/apps/workbench/packages/daemon/src/threads.ts +++ b/apps/workbench/packages/daemon/src/threads.ts @@ -49,7 +49,7 @@ import { HttpError } from './errors.js'; import { handoverBrief, handoverPrompt, synthesizeBrief, turnMessage } from './handover.js'; import { McpManager } from './mcp.js'; import { SkillsManager } from './skills.js'; -import { isWithinWorkdirs, Workdirs } from './workdirs.js'; +import { isWithinWorkdirs, tooWide, Workdirs } from './workdirs.js'; import { coalesceToolEvents, compactDeltas, toolText, type EmittedEvent, type EventType, type StoredEvent, type TurnChannel } from './events.js'; import type { SearchHit, SectionRecord, Store, ThreadRecord, ThreadWorktree, TodoProposal, TodoRecord, TodoUrgency } from './store.js'; import { readBrief, type ThreadBrief } from './brief.js'; @@ -592,7 +592,8 @@ export class ThreadManager { } /** - * Conversations the agent already has, in directories the hub is allowed to work in. + * Conversations the agent already has, in any directory that still exists and could be a + * workdir: importing one from outside the workdirs adds its directory (see {@link importSession}). * `threadId` is set for those that are already a thread here (including archived ones). */ async listAgentSessions(agent: string): Promise> { @@ -602,14 +603,15 @@ export class ThreadManager { throw new HttpError(400, `${agent} has no session history to import`); } const sessions = await adapter.listSessions(); - const allowed = new Map(); + const offered = new Map(); const workdirs = this.workdirs; return sessions .filter((s) => !isProbeSession(s.title)) - // A session whose directory has since been removed cannot be continued, so it is not offered. + // A session whose directory has since been removed, or that could never become a workdir, + // cannot be continued, so it is not offered. .filter((s) => { - if (!allowed.has(s.cwd)) allowed.set(s.cwd, !!s.cwd && isWithinWorkdirs(s.cwd, workdirs) && isDirectory(s.cwd)); - return allowed.get(s.cwd); + if (!offered.has(s.cwd)) offered.set(s.cwd, !!s.cwd && (isWithinWorkdirs(s.cwd, workdirs) || !tooWide(s.cwd)) && isDirectory(s.cwd)); + return offered.get(s.cwd); }) .map((s) => ({ ...s, threadId: this.store.findThreadByAgentSession(agent, s.id)?.id ?? null })) // Newest first; sessions with no date go last. @@ -620,8 +622,13 @@ export class ThreadManager { * Makes a thread out of a conversation the agent already has. Its past turns are written to the * event log once; the thread then continues the same agent session, so the terminal and the hub * keep sharing it. + * + * A session outside the workdirs is imported only with `addDirectory`, which the person's own + * import click sets: its directory then becomes a workdir, as if added from the page (a home + * directory or the root itself is refused as too wide). Imports nobody clicked, such as the + * LoopX Goal sync, never widen where threads may work. */ - async importSession(input: { agent?: unknown; sessionId?: unknown }): Promise { + async importSession(input: { agent?: unknown; sessionId?: unknown; addDirectory?: boolean }): Promise { const agent = String(input.agent ?? ''); const sessionId = String(input.sessionId ?? ''); const adapter = this.adapters.get(agent); @@ -630,12 +637,14 @@ export class ThreadManager { const summary = adapter.getSession ? await adapter.getSession(sessionId) : (await this.listAgentSessions(agent)).find((s) => s.id === sessionId); - if (!summary || summary.id !== sessionId || !summary.cwd || !isWithinWorkdirs(summary.cwd, this.workdirs) || !isDirectory(summary.cwd)) { + const outside = !!summary?.cwd && !isWithinWorkdirs(summary.cwd, this.workdirs); + if (!summary || summary.id !== sessionId || !summary.cwd || (outside && !input.addDirectory) || !isDirectory(summary.cwd)) { throw new HttpError(404, 'session not found, or it is outside the allowed workdirs'); } const key = `${agent}:${sessionId}`; if (this.store.findThreadByAgentSession(agent, sessionId) || this.importing.has(key)) throw new HttpError(409, 'this session is already a thread'); if (!adapter.loadHistory) throw new HttpError(400, `${agent} has no session history to import`); + if (outside) this.addWorkdir(summary.cwd); this.importing.add(key); try { diff --git a/apps/workbench/packages/daemon/src/workdirs.ts b/apps/workbench/packages/daemon/src/workdirs.ts index 6319da1825..b083831b02 100644 --- a/apps/workbench/packages/daemon/src/workdirs.ts +++ b/apps/workbench/packages/daemon/src/workdirs.ts @@ -24,7 +24,7 @@ export function isWithinWorkdirs(dir: string, workdirs: string[]): boolean { } /** Too wide to hand to an agent as a whole: the filesystem root, and a home directory itself. */ -function tooWide(dir: string): boolean { +export function tooWide(dir: string): boolean { const target = real(dir); return target === sep || target === real(homedir()); } diff --git a/apps/workbench/packages/daemon/test/api.test.ts b/apps/workbench/packages/daemon/test/api.test.ts index a7b1a3d13e..71c2b1b07c 100644 --- a/apps/workbench/packages/daemon/test/api.test.ts +++ b/apps/workbench/packages/daemon/test/api.test.ts @@ -995,9 +995,11 @@ const events = async (threadId: string) => test('import: Codex reads just the chosen session and rechecks its directory and duplicate status', async () => { const file = join(dataDir, 'codex-import-sessions.json'); const log = join(dataDir, 'codex-import-rpc.jsonl'); + const elsewhere = mkdtempSync(join(tmpdir(), 'loochat-test-codex-elsewhere-')); writeFileSync(file, JSON.stringify([ { id: 'hist-indexed', cwd: workdir, name: 'Indexed session' }, - { id: 'hist-outside', cwd: tmpdir(), name: 'Outside' }, + { id: 'hist-outside', cwd: elsewhere, name: 'Outside' }, + { id: 'hist-home', cwd: homedir(), name: 'In home' }, { id: 'hist-removed', cwd: join(workdir, 'missing-project'), name: 'Removed' }, { id: 'hist-subagent', cwd: workdir, name: 'Scratch', source: { subAgent: 'review' } }, ])); @@ -1013,9 +1015,12 @@ test('import: Codex reads just the chosen session and rechecks its directory and body: JSON.stringify({ agent: 'codex', sessionId }), }); try { - for (const id of ['hist-outside', 'hist-removed', 'hist-missing', 'hist-subagent']) { + for (const id of ['hist-removed', 'hist-missing', 'hist-subagent']) { assert.equal((await requestImport(id)).status, 404, id); } + // The home directory itself is too wide to become a workdir, so its session cannot come in. + assert.equal((await requestImport('hist-home')).status, 400); + assert.ok(!m.workdirsConfig().workdirs.includes(homedir())); const imported = await requestImport('hist-indexed'); assert.equal(imported.status, 201); const thread = await imported.json() as { id: string; title: string; agentSessionId: string }; @@ -1026,13 +1031,24 @@ test('import: Codex reads just the chosen session and rechecks its directory and const calls = readFileSync(log, 'utf8').trim().split('\n').map((line) => JSON.parse(line)); assert.equal(calls.filter((c) => c.method === 'thread/list').length, 0); assert.equal(calls.filter((c) => c.method === 'thread/turns/list').length, 1, 'only the valid import reads history'); + + // A session from outside the workdirs comes in when the person imports it, and brings its directory. + const outside = await requestImport('hist-outside'); + assert.equal(outside.status, 201); + assert.equal(((await outside.json()) as { cwd: string }).cwd, elsewhere); + assert.ok(m.workdirsConfig().workdirs.includes(elsewhere)); + // An import nobody clicked (the LoopX Goal sync) never widens the workdirs. + writeFileSync(file, JSON.stringify([{ id: 'hist-quiet', cwd: join(dataDir), name: 'Quiet' }])); + await assert.rejects(() => m.importSession({ agent: 'codex', sessionId: 'hist-quiet' }), /outside the allowed workdirs/); + assert.ok(!m.workdirsConfig().workdirs.includes(dataDir)); } finally { srv.close(); await m.shutdown(); + rmSync(elsewhere, { recursive: true, force: true }); } }); -test('import: sessions the agent already has are listed, and only those in allowed directories', async () => { +test('import: sessions the agent already has are listed from every existing directory', async () => { const outside = mkdtempSync(join(tmpdir(), 'loochat-test-outside-')); try { writeFileSync( @@ -1048,17 +1064,14 @@ test('import: sessions the agent already has are listed, and only those in allow const res = await api('/api/agents/claude/sessions'); assert.equal(res.status, 200); const list = (await res.json()) as Array<{ id: string; cwd: string; title: string; threadId: string | null }>; - // Five sessions over three pages; the one outside the workdirs and the one whose directory is gone are left out. - // Newest first, and the one with no date last. - assert.deepEqual(list.map((s) => s.id), ['hist-b', 'hist-a', 'hist-c']); + // Five sessions over three pages; the one whose directory is gone is left out, the one outside + // the workdirs is offered (importing it adds its directory). Newest first, and the one with no date last. + assert.deepEqual(list.map((s) => s.id), ['hist-elsewhere', 'hist-b', 'hist-a', 'hist-c']); assert.ok(list.every((s) => s.threadId === null)); assert.equal((await api('/api/agents/nope/sessions')).status, 404); assert.equal((await api('/api/agents/claude/sessions', {}, false)).status, 401); - // A session outside the allowed directories cannot be imported by naming it directly. - const sneaky = await api('/api/threads/import', { method: 'POST', body: JSON.stringify({ agent: 'claude', sessionId: 'hist-elsewhere' }) }); - assert.equal(sneaky.status, 404); assert.equal((await api('/api/threads/import', { method: 'POST', body: JSON.stringify({ agent: 'claude', sessionId: 'no-such' }) })).status, 404); assert.equal((await api('/api/threads/import', { method: 'POST', body: JSON.stringify({ agent: 'nope', sessionId: 'hist-a' }) })).status, 400); assert.equal((await api('/api/threads/import', { method: 'POST', body: JSON.stringify({}) })).status, 400); diff --git a/apps/workbench/packages/daemon/test/local-sessions.test.ts b/apps/workbench/packages/daemon/test/local-sessions.test.ts index d78b1ef80f..6c1b5a2ac1 100644 --- a/apps/workbench/packages/daemon/test/local-sessions.test.ts +++ b/apps/workbench/packages/daemon/test/local-sessions.test.ts @@ -1,7 +1,7 @@ import { test, before, after } from 'node:test'; import assert from 'node:assert/strict'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; +import { homedir, tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { Server } from 'node:http'; @@ -46,7 +46,8 @@ after(() => { rmSync(outside, { recursive: true, force: true }); }); -/** The fake agent's session list: two in the workdir, one outside it, one in a removed directory. */ +/** The fake agent's session list: some in the workdir, one outside it, one in the home directory + * itself, one in a removed directory. */ function givenSessions(): void { mkdirSync(join(workdir, 'app'), { recursive: true }); imported = new Map(); @@ -56,17 +57,20 @@ function givenSessions(): void { { sessionId: 's-tied', cwd: workdir, title: 'Same second, other agent file order', updatedAt: '2026-03-02T10:00:00.000Z' }, { sessionId: 's-out', cwd: outside, title: 'Elsewhere', updatedAt: '2026-03-03T10:00:00.000Z' }, { sessionId: 's-gone', cwd: join(workdir, 'deleted'), title: 'Directory removed', updatedAt: '2026-03-04T10:00:00.000Z' }, + { sessionId: 's-home', cwd: homedir(), title: 'Started in home', updatedAt: '2026-03-04T11:00:00.000Z' }, { sessionId: 's-usage', cwd: workdir, title: '/usage', updatedAt: '2026-03-05T10:00:00.000Z' }, { sessionId: 's-nodate', cwd: workdir, title: 'No date', updatedAt: null }, ])); } -test('the scan lists this machine\'s sessions: newest first, only in existing allowed directories', async () => { +test('the scan lists this machine\'s sessions from every existing directory, newest first', async () => { givenSessions(); await scanner.scan(); const page = scanner.page(100, null); // Newest first; the two sharing a second stay apart by id, and the one with no date goes last. - assert.deepEqual(page.sessions.map((s) => s.sessionId), ['s-tied', 's-new', 's-old', 's-nodate']); + // The one outside the workdirs is listed too (importing it adds its directory); the one in a + // removed directory and the one in the home directory itself, which can never be a workdir, are not. + assert.deepEqual(page.sessions.map((s) => s.sessionId), ['s-out', 's-tied', 's-new', 's-old', 's-nodate']); assert.equal(page.nextCursor, null); assert.ok(page.scannedAt); // The quota probe's leftover `/usage` sessions are not offered as conversations. @@ -78,10 +82,10 @@ test('the scan lists this machine\'s sessions: newest first, only in existing al test('pages continue at the cursor, and one timestamp shared by two rows splits them', async () => { givenSessions(); await scanner.scan(); - const first = scanner.page(2, null); - assert.deepEqual(first.sessions.map((s) => s.sessionId), ['s-tied', 's-new']); + const first = scanner.page(3, null); + assert.deepEqual(first.sessions.map((s) => s.sessionId), ['s-out', 's-tied', 's-new']); assert.ok(first.nextCursor); - const second = scanner.page(2, first.nextCursor); + const second = scanner.page(3, first.nextCursor); assert.deepEqual(second.sessions.map((s) => s.sessionId), ['s-old', 's-nodate']); // The whole list fit in two pages: no cursor, no more to read. assert.equal(second.nextCursor, null); @@ -183,7 +187,21 @@ test('a failing agent keeps its last list; the rest of the scan is unaffected', await scanner.scan(); writeFileSync(sessionsFile, 'not json'); await scanner.scan(); - assert.equal(scanner.page(100, null).sessions.length, 4); + assert.equal(scanner.page(100, null).sessions.length, 5); +}); + +test('hidden directories stay out of the list, and a workdir may still cover the home directory', async () => { + givenSessions(); + const hiding = new LocalSessions({ + adapters, + // A hub started with the home directory as a workdir can continue sessions there. + workdirs: () => [workdir, homedir()], + hidden: () => [outside, join(workdir, 'app')], + importedSessions: () => imported, + instances: () => instances, + }); + await hiding.scan(); + assert.deepEqual(hiding.page(100, null).sessions.map((s) => s.sessionId), ['s-home', 's-tied', 's-old', 's-nodate']); }); test('GET /api/local-sessions serves a page and keeps the scan fresh', async () => { @@ -200,7 +218,7 @@ test('GET /api/local-sessions serves a page and keeps the scan fresh', async () assert.equal(page.sessions.length, 2); const next = await fetch(root + `/api/local-sessions?limit=100&cursor=${encodeURIComponent(page.nextCursor)}`, { headers: auth }); const rest = await next.json() as { sessions: Array<{ sessionId: string }>; nextCursor: string | null }; - assert.equal(rest.sessions.length, 2); + assert.equal(rest.sessions.length, 3); assert.equal(rest.nextCursor, null); } finally { server.close(); From f222b8a91e3e09f7090433f963762ca0143a27cf Mon Sep 17 00:00:00 2001 From: maxliux5 <5958865+maxliux5@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:46:50 +0000 Subject: [PATCH 2/2] fix(workbench): address review on listing sessions from every directory - Import checks a new directory first and adds it only once the thread exists, so a failed import leaves the workdirs (and any added child directory) as they were. - Both session lists share one rule (offeredSessionDir), so LOOCHAT_HIDDEN_SESSION_DIRS also applies to the per-agent list. - The LoopX Goal sync skips sessions outside the workdirs instead of asking their agent again on every scan. - The page reads the roots again after an import, so a directory the import added shows without a reload (covered by a browser e2e). Co-Authored-By: Claude Opus 5.5 Signed-off-by: maxliux5 <5958865+maxliux5@users.noreply.github.com> --- .../daemon/src/adapters/loopx/service.ts | 5 +- apps/workbench/packages/daemon/src/index.ts | 1 + .../packages/daemon/src/local-sessions.ts | 12 ++++- apps/workbench/packages/daemon/src/threads.ts | 26 ++++++--- .../workbench/packages/daemon/src/workdirs.ts | 16 ++++-- .../packages/daemon/test/api.test.ts | 34 ++++++++++++ .../daemon/test/session-loopx.test.ts | 14 ++++- .../e2e/test/import-outside-roots.spec.mjs | 54 +++++++++++++++++++ apps/workbench/packages/web/src/App.tsx | 2 + 9 files changed, 147 insertions(+), 17 deletions(-) create mode 100644 apps/workbench/packages/e2e/test/import-outside-roots.spec.mjs diff --git a/apps/workbench/packages/daemon/src/adapters/loopx/service.ts b/apps/workbench/packages/daemon/src/adapters/loopx/service.ts index 719093f036..82f20f688e 100644 --- a/apps/workbench/packages/daemon/src/adapters/loopx/service.ts +++ b/apps/workbench/packages/daemon/src/adapters/loopx/service.ts @@ -126,7 +126,7 @@ export class LoopxService implements LoopxHooks { * read then, not before) and bound to that Goal under the Goal's registered root; one on a Goal the core * no longer has stays as it is, marked in lists but bound to nothing. Safe to run again. */ - async syncSessions(sessions: Array<{ agent: string; sessionId: string; updatedAt: string | null; loopx?: SessionLoopx }>, idleMs = 60_000): Promise { + async syncSessions(sessions: Array<{ agent: string; sessionId: string; cwd?: string; updatedAt: string | null; loopx?: SessionLoopx }>, idleMs = 60_000): Promise { const manager = this.manager; if (!manager) return; const titles = new Map(); @@ -145,6 +145,9 @@ export class LoopxService implements LoopxHooks { if (!thread) { // A conversation that is still being written to by its host is left until it has been quiet a while. if (session.updatedAt && Date.now() - Date.parse(session.updatedAt) < idleMs) continue; + // The list shows sessions from every directory, but this sync never widens the workdirs: one + // outside them is left for the person to import, without asking its agent again every scan. + if (session.cwd !== undefined && !isWithinWorkdirs(session.cwd, this.deps.dirs.all())) continue; thread = await manager.importSession({ agent: session.agent, sessionId: session.sessionId }).catch((err) => { console.warn(`loopx: could not import session for Goal ${info.goalId}: ${err instanceof Error ? err.message : err}`); return null; }); if (!thread) continue; } diff --git a/apps/workbench/packages/daemon/src/index.ts b/apps/workbench/packages/daemon/src/index.ts index 7d2478373f..bd5fa32d4a 100644 --- a/apps/workbench/packages/daemon/src/index.ts +++ b/apps/workbench/packages/daemon/src/index.ts @@ -123,6 +123,7 @@ async function main(): Promise { loopx.attach(manager); manager.loopx = loopx; manager.sessionIndex = (sessionId) => localSessions.find(sessionId); + manager.hiddenSessionDirs = config.hiddenSessionDirs; localSessions.start(); machineUsage?.start(); manager.recoverInterrupted(); diff --git a/apps/workbench/packages/daemon/src/local-sessions.ts b/apps/workbench/packages/daemon/src/local-sessions.ts index df0537b3e4..c4f0af8c7c 100644 --- a/apps/workbench/packages/daemon/src/local-sessions.ts +++ b/apps/workbench/packages/daemon/src/local-sessions.ts @@ -59,6 +59,15 @@ export function isProbeSession(title: string): boolean { return title.trim() === '/usage'; } +/** + * Whether a session in `cwd` is offered for import, the one rule both session lists share: not in + * a hidden directory, and either in a workdir already or in one importing could add (a home + * directory or the root itself never can). Whether the directory still exists is checked apart. + */ +export function offeredSessionDir(cwd: string, workdirs: string[], hidden: string[]): boolean { + return !!cwd && !(hidden.length && isWithinWorkdirs(cwd, hidden)) && (isWithinWorkdirs(cwd, workdirs) || !tooWide(cwd)); +} + /** A request kicks a scan when the last one is older than this. Asking an agent costs a process, * so a page that stays open rescans every few minutes, not every poll. */ const FRESH_MS = 5 * 60_000; @@ -131,8 +140,7 @@ export class LocalSessions { if (listed === undefined) { // A session whose directory has since been removed, or that could never become a workdir, // cannot be continued here, so it is not listed. - listed = !!cwd && !(hidden.length && isWithinWorkdirs(cwd, hidden)) - && (isWithinWorkdirs(cwd, workdirs) || !tooWide(cwd)) && (await isDirectory(cwd)); + listed = offeredSessionDir(cwd, workdirs, hidden) && (await isDirectory(cwd)); listable.set(cwd, listed); } return listed; diff --git a/apps/workbench/packages/daemon/src/threads.ts b/apps/workbench/packages/daemon/src/threads.ts index f3d9d5de26..4d8bd9015a 100644 --- a/apps/workbench/packages/daemon/src/threads.ts +++ b/apps/workbench/packages/daemon/src/threads.ts @@ -49,7 +49,7 @@ import { HttpError } from './errors.js'; import { handoverBrief, handoverPrompt, synthesizeBrief, turnMessage } from './handover.js'; import { McpManager } from './mcp.js'; import { SkillsManager } from './skills.js'; -import { isWithinWorkdirs, tooWide, Workdirs } from './workdirs.js'; +import { isWithinWorkdirs, Workdirs } from './workdirs.js'; import { coalesceToolEvents, compactDeltas, toolText, type EmittedEvent, type EventType, type StoredEvent, type TurnChannel } from './events.js'; import type { SearchHit, SectionRecord, Store, ThreadRecord, ThreadWorktree, TodoProposal, TodoRecord, TodoUrgency } from './store.js'; import { readBrief, type ThreadBrief } from './brief.js'; @@ -61,7 +61,7 @@ import { aggregateThreadStats, statsOfTrace, type ThreadStats, type TurnStatsRow import { askedText } from './util.js'; import { MessageEdits } from './message-edits.js'; import { addWorktree, countChanges, findCheckout, initRepository, removeWorktree, samePath, worktreeLeftovers, type Checkout, type Worktree } from './worktrees.js'; -import { isProbeSession } from './local-sessions.js'; +import { isProbeSession, offeredSessionDir } from './local-sessions.js'; /** Why a copy cannot get a worktree of its own, said to whoever asked for one anyway. */ const WORKTREE_REFUSALS = { @@ -435,6 +435,8 @@ export class ThreadManager { /** The LoopX Goal adapter, when one is attached: a thread it binds is a Goal conversation, every other is ordinary. */ loopx: LoopxHooks | null = null; /** What the last local-session scan knows of a native session: where it came from, and its Goal. */ + /** Directories whose sessions are not offered for import (`LOOCHAT_HIDDEN_SESSION_DIRS`). */ + hiddenSessionDirs: string[] = []; sessionIndex: ((sessionId: string) => { origin?: 'app' | 'cli' | null; loopx?: import('./session-enrich.js').SessionLoopx } | undefined) | null = null; /** The skills every agent instance on this machine can reach. Read-mostly, by the skills page. */ @@ -592,8 +594,9 @@ export class ThreadManager { } /** - * Conversations the agent already has, in any directory that still exists and could be a - * workdir: importing one from outside the workdirs adds its directory (see {@link importSession}). + * Conversations the agent already has, in any directory that still exists, is not hidden and + * could be a workdir (the sidebar's rule, {@link offeredSessionDir}): importing one from outside + * the workdirs adds its directory (see {@link importSession}). * `threadId` is set for those that are already a thread here (including archived ones). */ async listAgentSessions(agent: string): Promise> { @@ -605,12 +608,13 @@ export class ThreadManager { const sessions = await adapter.listSessions(); const offered = new Map(); const workdirs = this.workdirs; + const hidden = this.hiddenSessionDirs; return sessions .filter((s) => !isProbeSession(s.title)) // A session whose directory has since been removed, or that could never become a workdir, // cannot be continued, so it is not offered. .filter((s) => { - if (!offered.has(s.cwd)) offered.set(s.cwd, !!s.cwd && (isWithinWorkdirs(s.cwd, workdirs) || !tooWide(s.cwd)) && isDirectory(s.cwd)); + if (!offered.has(s.cwd)) offered.set(s.cwd, offeredSessionDir(s.cwd, workdirs, hidden) && isDirectory(s.cwd)); return offered.get(s.cwd); }) .map((s) => ({ ...s, threadId: this.store.findThreadByAgentSession(agent, s.id)?.id ?? null })) @@ -625,8 +629,9 @@ export class ThreadManager { * * A session outside the workdirs is imported only with `addDirectory`, which the person's own * import click sets: its directory then becomes a workdir, as if added from the page (a home - * directory or the root itself is refused as too wide). Imports nobody clicked, such as the - * LoopX Goal sync, never widen where threads may work. + * directory or the root itself is refused as too wide). The directory is checked first and + * added only once the thread exists, so a failed import leaves the workdirs as they were. + * Imports nobody clicked, such as the LoopX Goal sync, never widen where threads may work. */ async importSession(input: { agent?: unknown; sessionId?: unknown; addDirectory?: boolean }): Promise { const agent = String(input.agent ?? ''); @@ -644,7 +649,8 @@ export class ThreadManager { const key = `${agent}:${sessionId}`; if (this.store.findThreadByAgentSession(agent, sessionId) || this.importing.has(key)) throw new HttpError(409, 'this session is already a thread'); if (!adapter.loadHistory) throw new HttpError(400, `${agent} has no session history to import`); - if (outside) this.addWorkdir(summary.cwd); + const refused = outside ? this.dirs.refusal(summary.cwd) : null; + if (refused) throw new HttpError(400, refused); this.importing.add(key); try { @@ -682,6 +688,10 @@ export class ThreadManager { this.attachments.removeThread(id); throw err; } + if (outside) { + // Checked above; only a directory removed in between could fail here, and the thread stands either way. + try { this.dirs.add(summary.cwd); } catch (err) { console.warn(`import: could not add ${summary.cwd} as a workdir: ${err instanceof Error ? err.message : err}`); } + } for (const ev of events) for (const l of this.listeners) l(ev); return this.threadView(id); } finally { diff --git a/apps/workbench/packages/daemon/src/workdirs.ts b/apps/workbench/packages/daemon/src/workdirs.ts index b083831b02..67448925c3 100644 --- a/apps/workbench/packages/daemon/src/workdirs.ts +++ b/apps/workbench/packages/daemon/src/workdirs.ts @@ -72,13 +72,21 @@ export class Workdirs { return this.roots().map((path) => ({ path, removable: !this.base.includes(path) })); } + /** Why {@link add} would refuse `input`, or null when it would take it; changes nothing. */ + refusal(input: string): string | null { + if (!input || !isAbsolute(input)) return 'give an absolute path'; + const dir = resolve(input); + if (!existsSync(dir) || !statSync(dir).isDirectory()) return 'no such directory'; + if (tooWide(dir)) return 'too wide: pick a project folder, not the root or a home directory itself'; + if (isWithinWorkdirs(dir, this.roots())) return 'already allowed'; + return null; + } + /** Adds a directory from the page. Refuses what does not exist, what is already covered, and what is too wide. */ add(input: string): void { - if (!input || !isAbsolute(input)) throw new Error('give an absolute path'); + const refused = this.refusal(input); + if (refused) throw new Error(refused); const dir = resolve(input); - if (!existsSync(dir) || !statSync(dir).isDirectory()) throw new Error('no such directory'); - if (tooWide(dir)) throw new Error('too wide: pick a project folder, not the root or a home directory itself'); - if (isWithinWorkdirs(dir, this.roots())) throw new Error('already allowed'); // A new root that holds added ones takes their place. this.extra = [...this.extra.filter((p) => !isWithinWorkdirs(p, [dir])), dir]; this.save(); diff --git a/apps/workbench/packages/daemon/test/api.test.ts b/apps/workbench/packages/daemon/test/api.test.ts index 71c2b1b07c..a92cf9d9a8 100644 --- a/apps/workbench/packages/daemon/test/api.test.ts +++ b/apps/workbench/packages/daemon/test/api.test.ts @@ -1048,6 +1048,40 @@ test('import: Codex reads just the chosen session and rechecks its directory and } }); +test('import: a failed import leaves the workdirs as they were; hidden directories are not offered', async () => { + const base = mkdtempSync(join(tmpdir(), 'loochat-test-import-fail-')); + const project = join(base, 'project'); + const child = join(project, 'child'); + const hidden = join(base, 'hidden'); + mkdirSync(child, { recursive: true }); + mkdirSync(hidden); + const sessions = [ + { id: 'in-project', cwd: project, title: 'Unreadable history', updatedAt: '2026-03-02T10:00:00.000Z' }, + { id: 'in-hidden', cwd: hidden, title: 'Kept out', updatedAt: '2026-03-01T10:00:00.000Z' }, + ]; + const adapter = { + id: 'stub', capabilities: { history: true }, + listSessions: async () => sessions, + loadHistory: async () => { throw new Error('history unreadable'); }, + } as unknown as AgentAdapter; + const dirs = new Workdirs([workdir], join(base, 'workdirs.json')); + dirs.add(child); + const m = new ThreadManager(store, new Map([['stub', adapter]]), dirs, new AttachmentStore(dataDir)); + m.hiddenSessionDirs = [hidden]; + try { + // The per-agent list follows the sidebar's rule: the hidden directory's session is not offered. + assert.deepEqual((await m.listAgentSessions('stub')).map((s) => s.id), ['in-project']); + // Its history cannot be read: no thread, and the added child is not replaced by its parent. + await assert.rejects(() => m.importSession({ agent: 'stub', sessionId: 'in-project', addDirectory: true }), /history unreadable/); + assert.deepEqual(m.workdirsConfig().workdirs, [workdir, child]); + assert.deepEqual(JSON.parse(readFileSync(join(base, 'workdirs.json'), 'utf8')), [child]); + assert.equal(store.findThreadByAgentSession('stub', 'in-project'), null); + } finally { + await m.shutdown(); + rmSync(base, { recursive: true, force: true }); + } +}); + test('import: sessions the agent already has are listed from every existing directory', async () => { const outside = mkdtempSync(join(tmpdir(), 'loochat-test-outside-')); try { diff --git a/apps/workbench/packages/daemon/test/session-loopx.test.ts b/apps/workbench/packages/daemon/test/session-loopx.test.ts index 8f0a4410d5..68729f6752 100644 --- a/apps/workbench/packages/daemon/test/session-loopx.test.ts +++ b/apps/workbench/packages/daemon/test/session-loopx.test.ts @@ -58,7 +58,7 @@ before(async () => { }); after(() => server.close()); -interface Fixture { id: string; text: string; ageMs?: number; originator?: string } +interface Fixture { id: string; text: string; ageMs?: number; originator?: string; cwd?: string } /** Four kinds of conversation, as session files the fake agent reads back. */ function world(fixtures: Fixture[]) { @@ -73,7 +73,7 @@ function world(fixtures: Fixture[]) { const adapter = { id: 'codex', capabilities: { history: true }, - listSessions: async () => fixtures.map((f) => ({ id: f.id, cwd: goalRoot, title: `title ${f.id}`, updatedAt: new Date(Date.now() - (f.ageMs ?? 3_600_000)).toISOString() })), + listSessions: async () => fixtures.map((f) => ({ id: f.id, cwd: f.cwd ?? goalRoot, title: `title ${f.id}`, updatedAt: new Date(Date.now() - (f.ageMs ?? 3_600_000)).toISOString() })), sessionLocation: async (id: string | null) => ({ configDir: dir, sessionPath: files.get(id ?? '') ?? null }), sessionOrigin: (line: string) => new CodexAppServerAdapter(['codex']).sessionOrigin(line), }; @@ -155,6 +155,16 @@ test('scanning again imports and binds nothing twice', async () => { assert.equal(service.bindings.entries().length, bindings); }); +test('a Goal session outside the workdirs is listed but left for the person to import', async () => { + const elsewhere = mkdtempSync(join(tmpdir(), 'loopx-sessions-elsewhere-')); + const { local, imports } = world([{ id: 's-away', text: bootstrap('g-text'), cwd: elsewhere }]); + await local.scan(); + await local.scan(); + // The sidebar has it, but the background sync neither imports it nor widens the workdirs. + assert.equal(local.find('s-away')?.loopx?.goalId, 'g-text'); + assert.deepEqual(imports, []); +}); + test('a session its host is still writing to waits until it has been quiet', async () => { const { local, imports } = world([{ id: 's-busy', text: bootstrap('g-text'), ageMs: 5_000 }]); await local.scan(); diff --git a/apps/workbench/packages/e2e/test/import-outside-roots.spec.mjs b/apps/workbench/packages/e2e/test/import-outside-roots.spec.mjs new file mode 100644 index 0000000000..c35753e124 --- /dev/null +++ b/apps/workbench/packages/e2e/test/import-outside-roots.spec.mjs @@ -0,0 +1,54 @@ +// Importing a sidebar session from outside the project roots adds its directory as a root; the +// page reads the roots again, so the new one is there without a reload. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import { join } from 'node:path'; +import { startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +let elsewhere, messagesDir, daemon, browser; +const sessionId = randomUUID(); + +before(async () => { + elsewhere = mkdtempSync(join(tmpdir(), 'loochat-e2e-elsewhere-')); + messagesDir = mkdtempSync(join(tmpdir(), 'loochat-e2e-msgs-')); + // The session is there before the hub starts, so its first scan finds it. + const sessions = join(messagesDir, 'pi-agent', 'sessions', 'e2e'); + mkdirSync(sessions, { recursive: true }); + writeFileSync(join(sessions, `e2e_${sessionId}.jsonl`), JSON.stringify({ type: 'session', id: sessionId, cwd: elsewhere }) + '\n' + JSON.stringify({ type: 'session_info', name: '别处的会话' }) + '\n'); + writeFileSync(join(messagesDir, 'messages.json'), JSON.stringify({ + [sessionId]: [{ role: 'user', content: '你好' }, { role: 'assistant', content: [{ type: 'text', text: '在别的目录里' }] }], + })); + daemon = await startDaemon({ FAKE_PI_MESSAGES_FILE: join(messagesDir, 'messages.json'), PI_CODING_AGENT_DIR: join(messagesDir, 'pi-agent') }); + browser = await launchBrowser(); +}); + +after(async () => { + await browser?.close(); + await daemon?.stop(); + rmSync(elsewhere, { recursive: true, force: true }); + rmSync(messagesDir, { recursive: true, force: true }); +}); + +test('importing a session from outside the roots adds its directory, and the page shows it', async () => { + const before = await (await api(daemon, '/api/config')).json(); + assert.ok(!before.workdirs.includes(elsewhere)); + + const context = await browser.newContext({ viewport: { width: 1440, height: 960 } }); + const page = await context.newPage(); + try { + await openUi(page, daemon); + const row = page.locator('.thread-row.external', { hasText: '别处的会话' }); + // The scan after startup may still be running when the page first asks; a reload reads it again. + await row.waitFor({ timeout: 10_000 }).catch(async () => { await page.reload(); await row.waitFor({ timeout: 10_000 }); }); + const reread = page.waitForResponse((res) => new URL(res.url()).pathname === '/api/config' && res.request().method() === 'GET', { timeout: 15_000 }); + await row.locator('.thread-item').click(); + const roots = await (await reread).json(); + assert.ok(roots.workdirs.includes(elsewhere), 'the page reads the roots with the new directory'); + assert.ok((await (await api(daemon, '/api/config')).json()).workdirs.includes(elsewhere)); + } finally { + await context.close(); + } +}); diff --git a/apps/workbench/packages/web/src/App.tsx b/apps/workbench/packages/web/src/App.tsx index 7397d0dcb4..ef022d1912 100644 --- a/apps/workbench/packages/web/src/App.tsx +++ b/apps/workbench/packages/web/src/App.tsx @@ -712,6 +712,8 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } setExternalSessions((prev) => prev.filter((s) => `${s.agent}:${s.sessionId}` !== key)); setSelectedId(thread.id); setImportingExternal(null); + // Importing a session from outside the project roots adds its directory there: show it. + api.workdirs().then(applyWorkdirs).catch(() => undefined); }) .catch((e) => { setImportingExternal(null);