Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Per-chat project folder (agent cwd and sandbox), opening files by path in the browser, app or folder

Niko1221ef3902477eed
diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs
index 1910724cf..27fc3f7b1 100644
--- a/apps/host/server/agent/agent-bridge.mjs
+++ b/apps/host/server/agent/agent-bridge.mjs
@@ -15,7 +15,7 @@
* - it never holds a secret outside the environment of the agent process it starts.
*/
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { join, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import { GatewayClient } from './gateway-client.mjs';
import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs';
@@ -203,7 +203,10 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
}
async function sessionFor(c, cwd, runtime) {
- const known = sessionMap[c.id];
+ let known = sessionMap[c.id];
+ // The chat's folder changed: the agent's working folder and sandbox are fixed when its session starts, so the chat gets a new session
+ // in the new folder (the earlier conversation is carried into its first message, as for any fresh session).
+ if (known && cwd && known.cwd && resolve(known.cwd) !== resolve(cwd)) { delete sessionMap[c.id]; persist(); known = null; }
if (known) return { sessionId: known.sessionId, fresh: false };
const created = await runtime.gw.rpc('session/create', { request: { cwd } });
sessionMap[c.id] = { sessionId: created.sessionId, cwd, createdAt: new Date().toISOString() };
diff --git a/apps/host/server/chat-files.mjs b/apps/host/server/chat-files.mjs
new file mode 100644
index 000000000..a610280cf
--- /dev/null
+++ b/apps/host/server/chat-files.mjs
@@ -0,0 +1,107 @@
+/**
+ * The folder a chat works in, and what can be done with a file in it.
+ *
+ * - Each chat can have its own project folder ("Select a folder" above the input). It becomes the agent's working folder and
+ * sandbox for that chat and is remembered per chat.
+ * - A file in that folder is opened by its PATH (file:///...), never through a local web address: in the browser, in its own app,
+ * shown in the folder (Explorer /select), or copied as a path. Only files inside the chat's folder (or one the agent made
+ * there) can be named, so a request cannot reach anywhere else.
+ */
+
+import { spawn } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, realpathSync } from 'node:fs';
+import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+/** A folder no chat may use as its project: the top of a drive, or the system's own folders. */
+export function refusedFolder(dir) {
+ const p = resolve(dir);
+ if (dirname(p) === p) return 'Choose a folder inside a drive, not the whole drive.';
+ if (process.platform === 'win32') {
+ const win = (process.env.SystemRoot ?? 'C:\\Windows').toLowerCase();
+ const q = p.toLowerCase();
+ if (q === win || q.startsWith(win + sep) || /^[a-z]:\\(program files( \(x86\))?|programdata)(\\|$)/.test(q)) return 'That is a system folder. Choose one of your own folders.';
+ } else if (/^\/(bin|boot|dev|etc|lib|lib64|proc|root|run|sbin|sys|usr|var)(\/|$)/.test(p)) return 'That is a system folder. Choose one of your own folders.';
+ return null;
+}
+
+export const isInside = (root, target) => {
+ const rel = relative(resolve(root), resolve(target));
+ return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
+};
+
+/** The chat -> folder table, kept in one small file. */
+export function createChatFolders({ file }) {
+ let table = {};
+ try { const parsed = JSON.parse(readFileSync(file, 'utf8')); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) table = parsed; } catch { /* first run */ }
+ const save = () => {
+ try { mkdirSync(dirname(file), { recursive: true }); const tmp = file + '.tmp'; writeFileSync(tmp, JSON.stringify(table, null, 2)); renameSync(tmp, file); } catch { /* kept in memory */ }
+ };
+ const alive = p => { try { return statSync(p).isDirectory(); } catch { return false; } };
+ return {
+ /** The folder of a chat, or null (none chosen, or it was deleted: then the chat falls back to the default). */
+ get(chatId) { const p = table[chatId]; return typeof p === 'string' && alive(p) ? p : null; },
+ info(chatId) { const p = table[chatId]; return p ? { path: p, name: basename(p) || p, exists: alive(p) } : null; },
+ set(chatId, dir) {
+ const target = resolve(String(dir ?? '').trim());
+ if (!String(dir ?? '').trim() || !isAbsolute(target)) throw Object.assign(new Error('Choose a folder first.'), { code: 'folder-missing' });
+ let st; try { st = statSync(target); } catch { throw Object.assign(new Error("That folder doesn't exist."), { code: 'folder-missing' }); }
+ if (!st.isDirectory()) throw Object.assign(new Error("That's a file, not a folder."), { code: 'folder-missing' });
+ const why = refusedFolder(target);
+ if (why) throw Object.assign(new Error(why), { code: 'folder-refused' });
+ table[chatId] = target; save();
+ return { path: target, name: basename(target) || target, exists: true };
+ },
+ clear(chatId) { delete table[chatId]; save(); },
+ };
+}
+
+/** The real path of a file the chat may touch, or throws a plain sentence. Symbolic links are followed before the check. */
+export function resolveChatFile(root, rawPath) {
+ if (!root) throw Object.assign(new Error('This chat has no folder yet. Choose one first.'), { code: 'no-folder' });
+ const given = String(rawPath ?? '').trim();
+ if (!given) throw Object.assign(new Error('Which file?'), { code: 'file-missing' });
+ const full = isAbsolute(given) ? resolve(given) : resolve(root, given);
+ let real; try { real = realpathSync(full); } catch { throw Object.assign(new Error('That file is no longer there.'), { code: 'file-missing' }); }
+ let realRoot; try { realRoot = realpathSync(root); } catch { realRoot = resolve(root); }
+ if (!isInside(realRoot, real)) throw Object.assign(new Error("That file is outside this chat's folder, so it was not opened."), { code: 'outside' });
+ return real;
+}
+
+/**
+ * Start a program and return at once: detached, no shared output, never waited for.
+ * `STRATA_OPENER=record` (tests) records the command instead of starting anything.
+ */
+export function launch(command, args, { recorder = null } = {}) {
+ if (process.env.STRATA_OPENER === 'record' || recorder) { (recorder ?? launch.recorded).push([command, ...args]); return; }
+ const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: false });
+ child.on('error', () => {});
+ child.unref();
+}
+launch.recorded = [];
+
+/** What "open" means on each system, for the browser, the file's own app, or the folder. */
+export function openCommand(how, file, platform = process.platform) {
+ const url = pathToFileURL(file).href;
+ if (how === 'folder') {
+ if (platform === 'win32') return ['explorer.exe', [`/select,${file}`]];
+ if (platform === 'darwin') return ['open', ['-R', file]];
+ return ['xdg-open', [dirname(file)]];
+ }
+ if (how === 'browser') {
+ if (platform === 'win32') return ['rundll32.exe', ['url.dll,FileProtocolHandler', url]]; // the default browser, handed a file:// address
+ if (platform === 'darwin') return ['open', [url]];
+ return ['xdg-open', [url]];
+ }
+ if (platform === 'win32') return ['rundll32.exe', ['url.dll,FileProtocolHandler', file]];
+ if (platform === 'darwin') return ['open', [file]];
+ return ['xdg-open', [file]];
+}
+
+export function openFile(root, rawPath, how = 'app', { platform = process.platform, recorder = null } = {}) {
+ if (!['browser', 'app', 'folder'].includes(how)) throw Object.assign(new Error('That way of opening is not known.'), { code: 'bad-how' });
+ const file = resolveChatFile(root, rawPath);
+ const [cmd, args] = openCommand(how, file, platform);
+ launch(cmd, args, { recorder });
+ return { ok: true, started: true, path: file, url: pathToFileURL(file).href, how };
+}
diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs
index 412803324..b0f08ca7c 100644
--- a/apps/host/server/index.mjs
+++ b/apps/host/server/index.mjs
@@ -50,6 +50,7 @@ import { EventHub, error, json, readBody, uid } from './util.mjs';
import { RequestQueue } from './request-queue.mjs';
import { selectSkills, skillInstructions } from './skill-selection.mjs';
import { createModelProviders } from './model-providers.mjs';
+import { createChatFolders, openFile, resolveChatFile } from './chat-files.mjs';
import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs';
import { checkUpdates, checkComponentUpdates } from './updates.mjs';
import { createAppUpdater } from './app-updater.mjs';
@@ -423,6 +424,8 @@ function loadWorkspaces() {
}
let workspaces = loadWorkspaces();
+/* The folder each chat works in ("Select a folder"): the agent's working folder and sandbox for that chat. */
+const chatFolders = createChatFolders({ file: join(store.DATA_DIR, 'chat-folders.json') });
function saveWorkspaces() {
try {
@@ -512,7 +515,7 @@ async function runRemoteTurn({ selection, message, history, onFrame, signal, wor
/** One agent turn for a chat, streamed to the caller as the NDJSON frames the chat already renders. */
async function runAgentTurn({ res, controller, chatId, body, message, workspaceId }) {
const write = frame => { if (!res.writableEnded && !res.destroyed) res.write(`${JSON.stringify(frame)}\n`); };
- const cwd = (workspaceId ? workspaces.find(w => w.id === workspaceId)?.path : null) ?? WORKSPACE;
+ const cwd = chatFolders.get(chatId) ?? (workspaceId ? workspaces.find(w => w.id === workspaceId)?.path : null) ?? WORKSPACE;
let choice, instance = null;
if (body.remoteModel) choice = { connectionId: String(body.remoteModel.connectionId), modelId: String(body.remoteModel.modelId) };
else {
@@ -1513,6 +1516,28 @@ async function api(req, res, path, method, url) {
return json(res, 200, { path: rel, text, sizeKb: st.size / 1024, updatedAt: st.mtime.toISOString() });
}
+ // The folder a chat works in, and opening its files by path (notes-split-agent8.md).
+ if (path === '/api/chat/folder' && method === 'GET') {
+ const id = url.searchParams.get('sessionId') ?? '';
+ return json(res, 200, { folder: chatFolders.info(id), default: workspaces[0]?.path ?? WORKSPACE });
+ }
+ if (path === '/api/chat/folder' && method === 'POST') {
+ const body = await readBody(req);
+ const id = String(body.sessionId ?? '');
+ if (!id) return error(res, 400, 'sessionId is required');
+ if (agent.isRunning(id)) return error(res, 409, 'This chat is still working. Stop it or wait for it to finish, then choose the folder.');
+ if (body.path === null || body.path === '') { chatFolders.clear(id); return json(res, 200, { folder: null }); }
+ try { return json(res, 200, { folder: chatFolders.set(id, body.path) }); } catch (e) { return error(res, 400, e.message); }
+ }
+ if (path === '/api/files/open' && method === 'POST') {
+ const body = await readBody(req);
+ try { return json(res, 200, openFile(chatFolders.get(String(body.sessionId ?? '')), body.path, String(body.how ?? 'app'))); }
+ catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
+ }
+ if (path === '/api/files/path' && method === 'GET') {
+ try { const p = resolveChatFile(chatFolders.get(url.searchParams.get('sessionId') ?? ''), url.searchParams.get('path')); return json(res, 200, { path: p }); }
+ catch (e) { return error(res, e.code === 'outside' ? 403 : 400, e.message); }
+ }
if (path === '/api/workspaces' && method === 'GET') {
return json(res, 200, { workspaces });
}
diff --git a/apps/host/tests/chat-files.test.mjs b/apps/host/tests/chat-files.test.mjs
new file mode 100644
index 000000000..c3d9b2dcc
--- /dev/null
+++ b/apps/host/tests/chat-files.test.mjs
@@ -0,0 +1,72 @@
+// The chat's own folder and opening its files by path.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, symlinkSync, existsSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createChatFolders, openFile, openCommand, resolveChatFile, refusedFolder } from '../server/chat-files.mjs';
+import { startScriptedWorker } from './helpers/scripted-worker.mjs';
+import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
+import { resolveHarness } from '../server/agent/harness-runtime.mjs';
+const BS = String.fromCharCode(92);
+const HARNESS =process.env.STRATA_HARNESS_DIR;
+const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
+
+test('a chat folder is remembered per chat, must exist, and is never a system folder or a whole drive', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'strata-cf-'));
+ try {
+ const mine = join(dir, 'pagoda'); mkdirSync(mine);
+ const file = join(dir, 'folders.json');
+ const a = createChatFolders({ file });
+ assert.equal(a.get('c1'), null);
+ assert.equal(a.set('c1', mine).name, 'pagoda');
+ assert.equal(createChatFolders({ file }).get('c1'), mine, 'it survives a restart');
+ assert.equal(createChatFolders({ file }).get('c2'), null, 'per chat');
+ assert.throws(() => a.set('c1', join(dir, 'nope')), /doesn't exist/);
+ writeFileSync(join(dir, 'f.txt'), 'x'); assert.throws(() => a.set('c1', join(dir, 'f.txt')), /not a folder/);
+ assert.throws(() => a.set('c1', ''), /Choose a folder/);
+ assert.throws(() => a.set('c1', process.platform === 'win32' ? 'C:' + BS : '/'), /whole drive/);
+ assert.ok(refusedFolder(process.platform === 'win32' ? 'C:' + BS + 'Windows' + BS + 'System32' : '/etc'));
+ rmSync(mine, { recursive: true }); assert.equal(a.get('c1'), null, 'a deleted folder falls back to the default'); assert.equal(a.info('c1').exists, false);
+ a.clear('c1'); assert.equal(a.info('c1'), null);
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('files open by path from inside the folder only; the browser gets a file:// address', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'strata-cf2-'));
+ try {
+ const root = join(dir, 'proj'); mkdirSync(root); writeFileSync(join(root, 'pagoda.html'), '<p>hi</p>'); writeFileSync(join(dir, 'secret.txt'), 's');
+ const rec = [];
+ const r = openFile(root, 'pagoda.html', 'browser', { recorder: rec, platform: 'win32' });
+ assert.match(r.url, /^file:\/\/\/.*pagoda\.html$/); assert.deepEqual(rec[0].slice(0, 2), ['rundll32.exe', 'url.dll,FileProtocolHandler']); assert.match(rec[0][2], /^file:\/\//);
+ assert.ok(!/127\.0\.0\.1|localhost/.test(rec[0].join(' ')));
+ const WIN = 'C:' + BS + 'a' + BS + 'b.html';
+ assert.deepEqual(openCommand('folder', WIN, 'win32'), ['explorer.exe', ['/select,' + WIN]]);
+ assert.equal(openCommand('folder', '/a/b.html', 'darwin')[1][0], '-R');
+ assert.equal(rec.length, 1);
+ assert.throws(() => openFile(root, '../secret.txt', 'app', { recorder: rec }), /outside this chat's folder/);
+ assert.throws(() => openFile(root, join(dir, 'secret.txt'), 'app', { recorder: rec }), /outside/);
+ assert.throws(() => openFile(root, 'missing.html', 'app', { recorder: rec }), /no longer there/);
+ assert.throws(() => openFile(null, 'pagoda.html', 'app', { recorder: rec }), /no folder/);
+ assert.throws(() => openFile(root, 'pagoda.html', 'weird', { recorder: rec }), /not known/);
+ try { symlinkSync(join(dir, 'secret.txt'), join(root, 'link.txt')); assert.throws(() => resolveChatFile(root, 'link.txt'), /outside/, 'a link out of the folder is followed and refused'); } catch { /* no symlink right on this system */ }
+ assert.equal(rec.length, 1, 'nothing was started for a refused request');
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('a chat that moves to another folder gets a session there: the agent writes into the new folder', { skip }, async (t) => {
+ const worker = await startScriptedWorker({});
+ const dir = mkdtempSync(join(tmpdir(), 'strata-cf3-')); const a = join(dir, 'a'), b = join(dir, 'b'); mkdirSync(a); mkdirSync(b);
+ const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2 }], connections: () => [], env: process.env, startTimeoutMs: 90_000 });
+ t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } });
+ const fwd = p => p.replaceAll(BS, '/');
+ const run = (ws, name) => bridge.runTurn({ chatId: 'one', message: `SCRIPT:call write ${JSON.stringify({ file_path: fwd(join(ws, name)), content: name })}`, workspacePath: ws, mode: 'manual', onFrame: f => { if (f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId: 'one', callId: f.tool.id, decision: 'approve' }); } });
+ await run(a, 'in-a.txt');
+ const first = bridge.sessionOf('one');
+ await run(b, 'in-b.txt');
+ assert.notEqual(bridge.sessionOf('one'), first, 'a new session for the new folder');
+ assert.ok(existsSync(join(a, 'in-a.txt')) && existsSync(join(b, 'in-b.txt')));
+ // the sandbox follows the folder: Plan mode shows the old folder is not the working folder any more
+ await run(b, 'again.txt');
+ assert.equal(readFileSync(join(b, 'again.txt'), 'utf8').trim(), 'again.txt');
+});