Merge branch 'main' into camoufox-novnc-browser-use

This commit is contained in:
Simos Mikelatos
2026-07-10 10:00:54 +02:00
committed by GitHub
182 changed files with 4823 additions and 4608 deletions

View File

@@ -318,6 +318,22 @@ export const chatRunRegistry = {
run.writer.sendComplete(opts);
},
/**
* Safety-net variant of `completeRun` scoped to one specific run: a no-op
* unless `run` is still the session's current, running run. A runtime
* promise can resolve after its own `complete` already streamed AND a new
* run has replaced it in the registry (a queued message sends within
* milliseconds of the previous turn ending) — the session-keyed
* `completeRun` would terminate that newer run.
*/
completeRunIfCurrent(run: ChatRun, opts: { exitCode: number; aborted?: boolean }): void {
if (runs.get(run.appSessionId) !== run || run.status !== 'running') {
return;
}
run.writer.sendComplete(opts);
},
/**
* Test-only escape hatch: clears every tracked run.
*/

View File

@@ -1,8 +1,11 @@
import path from 'node:path';
import type { WebSocket } from 'ws';
import { sessionsDb } from '@/modules/database/index.js';
import { chatRunRegistry } from '@/modules/websocket/services/chat-run-registry.service.js';
import { connectedClients, WS_OPEN_STATE } from '@/modules/websocket/services/websocket-state.service.js';
import { getGlobalImageAssetsDir, normalizeImageDescriptors } from '@/shared/image-attachments.js';
import type {
AnyRecord,
AuthenticatedWebSocketRequest,
@@ -10,6 +13,37 @@ import type {
} from '@/shared/types.js';
import { parseIncomingJsonObject } from '@/shared/utils.js';
/**
* Trust boundary for client-supplied image attachments: chat.send options come
* straight from the browser, and the provider runtimes read the referenced
* files off disk (Claude base64-encodes them into the prompt). Only images
* that live directly inside the global upload store (`~/.cloudcli/assets`,
* where POST /api/assets/images puts them) are allowed through — anything
* else (absolute paths elsewhere, traversal, subdirectories) is dropped.
*
* Exported for tests; `assetsRootOverride` exists only for them.
*/
export function filterImagesToUploadStore(images: unknown, assetsRootOverride?: string): AnyRecord[] {
const assetsRoot = path.resolve(assetsRootOverride ?? getGlobalImageAssetsDir());
return normalizeImageDescriptors(images).filter((descriptor) => {
// Relative paths are anchored in the store; absolute ones must already be in it.
const resolved = path.resolve(assetsRoot, descriptor.path);
const relative = path.relative(assetsRoot, resolved);
const isDirectChild =
relative.length > 0 &&
!relative.startsWith('..') &&
!path.isAbsolute(relative) &&
!relative.includes(path.sep) &&
!relative.includes('/');
if (!isDirectChild) {
console.warn(`[Chat] Dropping image outside the upload store: ${descriptor.path}`);
}
return isDirectChild;
});
}
/**
* One provider runtime entry point. All five runtimes share this signature,
* which lets the chat handler dispatch through a provider-keyed map instead
@@ -161,6 +195,9 @@ async function handleChatSend(
// gateway writer captures and maps back to the app session id.
const runtimeOptions: AnyRecord = {
...clientOptions,
// Image attachments are re-validated server-side: only files inside the
// global upload store may reach the provider runtimes' file reads.
images: filterImagesToUploadStore(clientOptions.images),
sessionId: session.provider_session_id ?? undefined,
resume: Boolean(session.provider_session_id),
cwd: clientOptions.cwd ?? session.project_path ?? undefined,
@@ -175,8 +212,10 @@ async function handleChatSend(
} finally {
// Safety net: a runtime that crashed (or resolved) without emitting its
// terminal `complete` would otherwise leave the session stuck in
// "processing" forever on every connected client.
chatRunRegistry.completeRun(sessionId, { exitCode: 1 });
// "processing" forever on every connected client. Scoped to THIS run —
// a queued message can start the session's next run before this promise
// settles, and the session-keyed completeRun would kill that new run.
chatRunRegistry.completeRunIfCurrent(run, { exitCode: 1 });
}
}

View File

@@ -146,14 +146,6 @@ function buildShellCommand(
return 'codex';
}
if (provider === 'gemini') {
const command = initialCommand || 'gemini';
if (resumeSessionId) {
return `${command} --resume "${resumeSessionId}"`;
}
return command;
}
if (provider === 'opencode') {
if (resumeSessionId) {
return `opencode --session "${resumeSessionId}"`;
@@ -477,9 +469,7 @@ export function handleShellConnection(
? 'Cursor'
: provider === 'codex'
? 'Codex'
: provider === 'gemini'
? 'Gemini'
: provider === 'opencode'
: provider === 'opencode'
? 'OpenCode'
: 'Claude';
welcomeMsg = hasSession && resumeSessionId

View File

@@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { filterImagesToUploadStore } from '@/modules/websocket/services/chat-websocket.service.js';
const STORE = path.join(os.tmpdir(), 'cloudcli-assets-store');
test('images inside the upload store pass through', () => {
const inside = path.join(STORE, 'shot.png');
const result = filterImagesToUploadStore(
[{ path: inside, name: 'shot.png', mimeType: 'image/png' }],
STORE,
);
assert.equal(result.length, 1);
assert.equal(result[0].path, inside);
});
test('bare filenames are anchored inside the store', () => {
const result = filterImagesToUploadStore(['shot.png'], STORE);
assert.equal(result.length, 1);
});
test('paths outside the store, traversal, and subdirs are dropped', () => {
const result = filterImagesToUploadStore(
[
{ path: 'C:/Users/victim/.ssh/id_rsa' },
{ path: '/etc/passwd' },
{ path: '../outside.png' },
{ path: path.join(STORE, '..', 'escaped.png') },
{ path: path.join(STORE, 'nested', 'deep.png') },
{ path: STORE }, // the store folder itself is not a file
],
STORE,
);
assert.deepEqual(result, []);
});
test('malformed payloads yield no images', () => {
assert.deepEqual(filterImagesToUploadStore(undefined, STORE), []);
assert.deepEqual(filterImagesToUploadStore('nope', STORE), []);
assert.deepEqual(filterImagesToUploadStore([{ name: 'no-path' }, 42], STORE), []);
});

View File

@@ -129,6 +129,44 @@ test('complete marks the run finished and duplicate completes are dropped', asyn
});
});
test('a finished run\'s safety net cannot complete the session\'s next run', async () => {
await withIsolatedDatabase(() => {
sessionsDb.createAppSession('app-run-9', 'codex', '/workspace/demo');
const connection = new FakeConnection();
const firstRun = chatRunRegistry.startRun({
appSessionId: 'app-run-9',
provider: 'codex',
providerSessionId: null,
connection,
userId: null,
});
assert.ok(firstRun);
firstRun.writer.send({ kind: 'complete', provider: 'codex', sessionId: 'native-9', exitCode: 0 });
// A queued message starts the next run before the first run's runtime
// promise settles (the chat handler's `finally` hasn't executed yet).
const secondRun = chatRunRegistry.startRun({
appSessionId: 'app-run-9',
provider: 'codex',
providerSessionId: null,
connection,
userId: null,
});
assert.ok(secondRun);
// First run's safety net fires late: it must not touch the new run.
chatRunRegistry.completeRunIfCurrent(firstRun, { exitCode: 1 });
assert.equal(chatRunRegistry.isProcessing('app-run-9'), true);
assert.equal(connection.frames.filter((frame) => frame.kind === 'complete').length, 1);
// The second run's own safety net still works while it is current.
chatRunRegistry.completeRunIfCurrent(secondRun, { exitCode: 1 });
assert.equal(chatRunRegistry.isProcessing('app-run-9'), false);
assert.equal(connection.frames.filter((frame) => frame.kind === 'complete').length, 2);
});
});
test('listRunningRuns returns only currently running app sessions', async () => {
await withIsolatedDatabase(() => {
sessionsDb.createAppSession('app-run-7', 'claude', '/workspace/demo');
@@ -186,22 +224,22 @@ test('replayEvents returns only events after the requested seq', async () => {
test('attachConnection reroutes the live stream to a new socket', async () => {
await withIsolatedDatabase(() => {
sessionsDb.createAppSession('app-run-5', 'gemini', '/workspace/demo');
sessionsDb.createAppSession('app-run-5', 'opencode', '/workspace/demo');
const firstConnection = new FakeConnection();
const run = chatRunRegistry.startRun({
appSessionId: 'app-run-5',
provider: 'gemini',
provider: 'opencode',
providerSessionId: null,
connection: firstConnection,
userId: null,
});
assert.ok(run);
run.writer.send({ kind: 'stream_delta', provider: 'gemini', sessionId: 'g', content: 'before' });
run.writer.send({ kind: 'stream_delta', provider: 'opencode', sessionId: 'o', content: 'before' });
const secondConnection = new FakeConnection();
assert.equal(chatRunRegistry.attachConnection('app-run-5', secondConnection), true);
run.writer.send({ kind: 'stream_delta', provider: 'gemini', sessionId: 'g', content: 'after' });
run.writer.send({ kind: 'stream_delta', provider: 'opencode', sessionId: 'o', content: 'after' });
assert.deepEqual(firstConnection.frames.map((frame) => frame.content), ['before']);
assert.deepEqual(secondConnection.frames.map((frame) => frame.content), ['after']);