The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(chat): attach any file, and give each group participant its own persona
purpleb9c5710a8aca
diff --git a/dev-server/__tests__/datei-anhang-im-kaefig.test.ts b/dev-server/__tests__/datei-anhang-im-kaefig.test.tsnew file mode 100644index 00000000..b3d1902c--- /dev/null+++ b/dev-server/__tests__/datei-anhang-im-kaefig.test.ts@@ -0,0 +1,105 @@+/**+ * /local-api/fs-write-bytes: how a file attached in the chat reaches the+ * working folder when the app runs in a browser against `npm run dev`+ * (3.0.5). The parity port of the `fs_write_bytes` Tauri command, held to the+ * same promises: inside the jail, never over an existing file, complete or+ * absent, and capped.+ *+ * Real bytes, a real socket, a real file system, and the handler is the one+ * `registerFsRoutes` mounts for `npm run dev`.+ *+ * Run: npx vitest run dev-server/__tests__/datei-anhang-im-kaefig.test.ts+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { registerFsRoutes } from '../fs-routes'+import { routeHolen } from './echte-anfrage'+import { anfrageImHeim, arbeitsordnerIn, frischesHeim, kulisseAufraeumen } from './kaefig-kulisse'+import { DEV_WRITE_BYTES_CAP } from '../../src/lib/dev-fs-jail'++let heim = ''+let ws = ''++beforeAll(() => {+ heim = frischesHeim()+ ws = arbeitsordnerIn(heim)+ mkdirSync(ws, { recursive: true })+})+afterAll(kulisseAufraeumen)++function put(body: Record<string, unknown>) {+ const handler = routeHolen(registerFsRoutes, '/local-api/fs-write-bytes')+ return anfrageImHeim(handler, heim, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ })+}++const b64 = (bytes: number[]) => Buffer.from(bytes).toString('base64')++describe('a binary lands byte for byte', () => {+ it('one chunk: bytes no text write would survive', async () => {+ const raw = [0x00, 0x0d, 0xff, 0xfe, 0x0a, 0x80, 0x4e, 0x45, 0x53, 0x1a]+ const res = await put({ path: 'game.nes', base64: b64(raw), offset: 0, last: true, workingDirectory: ws })+ expect(res.status).toBe(200)+ expect(res.json()).toMatchObject({ status: 'saved', bytes: raw.length })+ expect([...readFileSync(join(ws, 'game.nes'))]).toEqual(raw)+ expect(existsSync(join(ws, '.game.nes.lu-part'))).toBe(false)+ })++ it('chunks are joined, and the file only appears with the last one', async () => {+ const first = await put({ path: 'rom.bin', base64: b64([1, 1, 1, 1]), offset: 0, last: false, workingDirectory: ws })+ expect(first.json()).toMatchObject({ status: 'partial', bytes: 4 })+ expect(existsSync(join(ws, 'rom.bin'))).toBe(false)+ const second = await put({ path: 'rom.bin', base64: b64([2, 2]), offset: 4, last: true, workingDirectory: ws })+ expect(second.json()).toMatchObject({ status: 'saved', bytes: 6 })+ expect([...readFileSync(join(ws, 'rom.bin'))]).toEqual([1, 1, 1, 1, 2, 2])+ })+})++describe('what it refuses', () => {+ it('a chunk at the wrong offset', async () => {+ await put({ path: 'order.bin', base64: b64([1, 1, 1, 1]), offset: 0, last: false, workingDirectory: ws })+ const res = await put({ path: 'order.bin', base64: b64([2]), offset: 2, last: true, workingDirectory: ws })+ expect(res.status).toBe(400)+ expect(res.text).toContain('out of order')+ expect(existsSync(join(ws, 'order.bin'))).toBe(false)+ })++ it('NEVER OVERWRITES: an existing file stays as it is', async () => {+ writeFileSync(join(ws, 'notes.txt'), 'the user\'s own file', 'utf8')+ const res = await put({ path: 'notes.txt', base64: b64([1, 2, 3]), offset: 0, last: true, workingDirectory: ws })+ expect(res.status).toBe(400)+ expect(res.text).toContain('already exists')+ expect(readFileSync(join(ws, 'notes.txt'), 'utf8')).toBe('the user\'s own file')+ })++ it('a path that climbs out of the workspace: 403, and nothing is written outside', async () => {+ const res = await put({ path: '../eingeschleust.bin', base64: b64([1]), offset: 0, last: true, workingDirectory: ws })+ expect(res.status).toBe(403)+ expect(existsSync(join(ws, '..', 'eingeschleust.bin'))).toBe(false)+ expect(existsSync(join(ws, '..', '.eingeschleust.bin.lu-part'))).toBe(false)+ })++ it('a request that names no file', async () => {+ const res = await put({ base64: b64([1]), offset: 0, last: true, workingDirectory: ws })+ expect(res.status).toBe(400)+ expect(res.text).toContain('Missing path')+ })++ it('broken base64 is an error, not an empty file', async () => {+ const res = await put({ path: 'broken.bin', base64: 'not base64 !!', offset: 0, last: true, workingDirectory: ws })+ expect(res.status).toBe(400)+ expect(res.text).toContain('Invalid base64')+ expect(existsSync(join(ws, 'broken.bin'))).toBe(false)+ })++ it('bytes past the cap', async () => {+ const res = await put({ path: 'huge.bin', base64: b64([1, 2, 3, 4]), offset: DEV_WRITE_BYTES_CAP, last: true, workingDirectory: ws })+ expect(res.status).toBe(400)+ expect(res.text).toContain('too large')+ expect(existsSync(join(ws, 'huge.bin'))).toBe(false)+ })+})diff --git a/dev-server/fs-routes.ts b/dev-server/fs-routes.tsindex 261e0d28..e6664389 100644--- a/dev-server/fs-routes.ts+++ b/dev-server/fs-routes.ts@@ -1,6 +1,6 @@-import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync, type Dirent } from 'fs'+import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, type Dirent } from 'fs'import os from 'os'-import { join, resolve } from 'path'+import { basename, join, resolve } from 'path'import type { RouteMount } from './routes'import { requirePost, withJsonBody } from './http'import { bodyFlag, bodyNumber, bodyString } from '../src/dev/http-body'@@ -8,6 +8,7 @@ import { resolveFsRequestPath } from '../src/dev/fs-request-path'import {devResolveWithinJail,devWorkspaceRoot,+ DEV_WRITE_BYTES_CAP,effectiveByteCap,JailEscapeError,namedDepth,@@ -124,6 +125,84 @@ export function registerFsRoutes(routes: RouteMount): void {})})+ // API: FS write bytes, one base64 chunk of a BINARY file attached in the+ // chat (3.0.5). Parity port of the `fs_write_bytes` Tauri command: the same+ // jail, the same 64 MiB ceiling, never over an existing file, and the bytes+ // grow in a hidden `.name.lu-part` sibling until the last chunk renames it+ // into place.+ routes.use('/local-api/fs-write-bytes', (req, res) => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {+ const fail = (status: number, error: string) => {+ res.writeHead(status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error }))+ }+ try {+ const filePath = bodyString(body, 'path')+ const chatId = bodyString(body, 'chatId')+ const workingDirectory = bodyString(body, 'workingDirectory')+ const offset = bodyNumber(body, 'offset') ?? 0+ const last = bodyFlag(body, 'last')+ const resolved = devResolveWithinJail({+ path: filePath ?? '',+ homeDir: os.homedir(),+ chatId,+ workingDirectory,+ ...devJail,+ })+ // The same check fs-write makes: a request that names no file resolves+ // to the workspace root itself.+ if (namedDepth(resolved) === namedDepth(devWorkspaceRoot(os.homedir(), chatId, workingDirectory))) {+ fail(400, `Missing path: fs-write-bytes writes a FILE inside the workspace, but this request names the workspace root itself (${resolved})`)+ return+ }+ if (existsSync(resolved)) {+ fail(400, `File already exists: ${resolved}`)+ return+ }+ const encoded = bodyString(body, 'base64') ?? ''+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded) || encoded.length % 4 !== 0) {+ fail(400, 'Invalid base64 data')+ return+ }+ const bytes = Buffer.from(encoded, 'base64')+ const total = offset + bytes.length+ if (total > DEV_WRITE_BYTES_CAP) {+ fail(400, `File is too large to attach: more than ${DEV_WRITE_BYTES_CAP} bytes`)+ return+ }+ const parentDir = resolve(resolved, '..')+ const part = join(parentDir, `.${basename(resolved)}.lu-part`)+ if (!existsSync(parentDir)) mkdirSync(parentDir, { recursive: true })+ if (offset === 0) {+ writeFileSync(part, bytes)+ } else {+ const have = existsSync(part) ? statSync(part).size : 0+ if (have !== offset) {+ fail(400, `Upload out of order: expected the chunk at byte ${have}, got the one at byte ${offset}`)+ return+ }+ appendFileSync(part, bytes)+ }+ if (!last) {+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'partial', bytes: total }))+ return+ }+ try {+ renameSync(part, resolved)+ } catch (err) {+ rmSync(part, { force: true })+ throw err+ }+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'saved', path: resolved, bytes: total }))+ } catch (err) {+ fail(err instanceof JailEscapeError ? 403 : 400, String(err instanceof Error ? err.message : err))+ }+ })+ })+// API: FS write — im Käfig (siehe src/dev/fs-request-path.ts)routes.use('/local-api/fs-write', (req, res) => {if (!requirePost(req, res)) returndiff --git a/e2e/chat-file-attachment.spec.ts b/e2e/chat-file-attachment.spec.tsnew file mode 100644index 00000000..8a1bbb82--- /dev/null+++ b/e2e/chat-file-attachment.spec.ts@@ -0,0 +1,165 @@+import { test, expect, type Page } from '@playwright/test'+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME, type TauriMockOptions } from './support/tauri-mock'+import { seedOnboardingDone } from './support/cloud-mock'+import { openNewChat } from './support/ui'++/**+ * Any file attaches to a chat (applejames, Discord: a ROM for a model that+ * helps with ROM hacking).+ *+ * Before this the paperclip took images only, and everything else was turned+ * away with a notice. Now a binary becomes a chip, and the model receives a+ * description of it: name, type from the signature, size, SHA-256, a hex dump+ * of the start and the readable strings. In Agent mode the file is also+ * copied into the working folder, so the file tools can open it.+ *+ * Measured at the payload, not on the screen: the request body is what the+ * model reads.+ *+ * Run: CI=1 npx playwright test e2e/chat-file-attachment.spec.ts+ */++/** An iNES header, sixteen bytes of code, and a title a strings pass finds. */+function nesRom(): Buffer {+ const header = Buffer.from([0x4e, 0x45, 0x53, 0x1a, 0x02, 0x01, 0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0])+ const code = Buffer.from([0xa9, 0x00, 0x8d, 0x00, 0x20, 0xff, 0xfe, 0x80, 0x81, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06])+ const title = Buffer.from('SUPER PLUMBER QUEST\0', 'latin1')+ return Buffer.concat([header, code, title, Buffer.alloc(64, 0xea)])+}++const ROM = { name: 'plumber.nes', mimeType: 'application/octet-stream', buffer: nesRom() }++interface Recorded { cmd: string; path?: string; offset?: number; last?: boolean; base64Length?: number }++async function chatBodies(page: Page): Promise<string[]> {+ return page.evaluate(() => {+ const bodies: unknown = Reflect.get(window, '__E2E_CHAT_BODIES__')+ return Array.isArray(bodies) ? bodies.map(String) : []+ })+}++async function toolCalls(page: Page): Promise<Recorded[]> {+ return page.evaluate(() => {+ const calls: unknown = Reflect.get(window, '__E2E_TOOL_CALLS__')+ return Array.isArray(calls) ? (calls as Recorded[]) : []+ })+}++/** The last user message of the last request, as the model receives it. */+async function lastUserMessage(page: Page): Promise<string> {+ const bodies = await chatBodies(page)+ const body = JSON.parse(bodies[bodies.length - 1]) as { messages: Array<{ role: string; content: unknown }> }+ const users = body.messages.filter((m) => m.role === 'user')+ return String(users[users.length - 1].content)+}++test('a binary file becomes a chip and reaches the model as a description', async ({ page }) => {+ const opts: TauriMockOptions = { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME, platform: 'mac' }+ await page.addInitScript(tauriMockInit, opts)+ await seedOnboardingDone(page)+ await page.goto('/')+ await openNewChat(page)++ await page.getByTestId('composer-file-input').setInputFiles(ROM)+ const composerChip = page.getByTestId('composer-file-chip')+ await expect(composerChip).toBeVisible()+ await expect(composerChip).toContainText('plumber.nes')+ await expect(composerChip).toContainText('NES ROM (iNES)')++ const field = page.locator('textarea').first()+ await field.fill('what is this rom?')+ await page.getByRole('button', { name: /Send message/i }).click()++ await expect(page.getByText(DEFAULT_ASSISTANT_REPLY).first()).toBeVisible({ timeout: 20_000 })++ // The bubble shows what was typed plus the chip, not the hex dump.+ const sentChip = page.getByTestId('chat-file-chip')+ await expect(sentChip).toBeVisible()+ await expect(sentChip).toContainText('plumber.nes')+ await expect(page.getByText('[Attached file: plumber.nes]')).toHaveCount(0)+ await expect(composerChip).toHaveCount(0)++ // The model gets the description.+ const sent = await lastUserMessage(page)+ expect(sent).toContain('what is this rom?')+ expect(sent).toContain('[Attached file: plumber.nes]')+ expect(sent).toContain('Type: NES ROM (iNES)')+ expect(sent).toContain(`(${ROM.buffer.length} bytes)`)+ expect(sent).toMatch(/SHA-256: [0-9a-f]{64}/)+ expect(sent).toContain('4e 45 53 1a')+ expect(sent).toContain('SUPER PLUMBER QUEST')+ expect(sent).toContain('The file itself is not available to you in this chat.')++ // A plain chat has no working folder, so nothing is written to disk.+ expect((await toolCalls(page)).filter((c) => c.cmd === 'fs_write_bytes')).toHaveLength(0)++ // What is stored is the description and the chip, never the bytes. Read+ // after a reload, so this is what really went to disk; the file name is the+ // control that the right record was read.+ await page.reload()+ await expect(page.getByTestId('chat-file-chip')).toContainText('plumber.nes', { timeout: 20_000 })+ const stored = await page.evaluate(async () => {+ const out: string[] = []+ for (const info of await indexedDB.databases()) {+ if (!info.name) continue+ const db = await new Promise<IDBDatabase>((resolve, reject) => {+ const req = indexedDB.open(info.name as string)+ req.onsuccess = () => resolve(req.result)+ req.onerror = () => reject(req.error)+ })+ for (const store of Array.from(db.objectStoreNames)) {+ const rows = await new Promise<unknown[]>((resolve, reject) => {+ const req = db.transaction(store, 'readonly').objectStore(store).getAll()+ req.onsuccess = () => resolve(req.result)+ req.onerror = () => reject(req.error)+ })+ out.push(JSON.stringify(rows))+ }+ db.close()+ }+ return out.join('\n')+ })+ expect(stored).toContain('plumber.nes')+ expect(stored).not.toContain(ROM.buffer.toString('base64').slice(0, 40))+})++test('in Agent mode the file is copied into the working folder and the model is told the path', async ({ page }) => {+ const opts: TauriMockOptions = {+ assistantReply: 'unused in this spec',+ modelName: DEFAULT_MODEL_NAME,+ platform: 'mac',+ agentTurns: [{ text: 'I can see the file.' }],+ }+ await page.addInitScript(tauriMockInit, opts)+ await seedOnboardingDone(page)+ await page.goto('/')+ await openNewChat(page)+ const agentToggle = page.getByRole('main').getByRole('button', { name: 'Agent', exact: true })+ await agentToggle.click()+ const sandbox = page.getByRole('button', { name: /^Sandbox/ })+ await expect(sandbox).toBeVisible({ timeout: 15_000 })+ await sandbox.click()+ await expect(page.getByRole('dialog', { name: /Agent workspace/i })).toHaveCount(0, { timeout: 10_000 })+ await expect(agentToggle).toHaveAttribute('title', /Agent Mode is on/i, { timeout: 10_000 })++ await page.getByTestId('composer-file-input').setInputFiles(ROM)+ await expect(page.getByTestId('composer-file-chip')).toBeVisible()+ await page.locator('textarea').first().fill('patch the title')+ await page.getByRole('button', { name: /Send message/i }).click()++ await expect(page.getByText('I can see the file.').first()).toBeVisible({ timeout: 20_000 })++ const writes = (await toolCalls(page)).filter((c) => c.cmd === 'fs_write_bytes')+ expect(writes).toHaveLength(1)+ expect(writes[0].path).toBe('plumber.nes')+ expect(writes[0].offset).toBe(0)+ expect(writes[0].last).toBe(true)+ expect(writes[0].base64Length).toBe(ROM.buffer.toString('base64').length)++ const bodies = await chatBodies(page)+ const first = JSON.parse(bodies[0]) as { messages: Array<{ role: string; content: unknown }> }+ const user = String(first.messages.filter((m) => m.role === 'user').pop()?.content)+ expect(user).toContain('patch the title')+ expect(user).toContain('Path in your working folder: plumber.nes')+ expect(user).toContain('Type: NES ROM (iNES)')+})diff --git a/e2e/group-chat-personas.spec.ts b/e2e/group-chat-personas.spec.tsnew file mode 100644index 00000000..cc1695da--- /dev/null+++ b/e2e/group-chat-personas.spec.ts@@ -0,0 +1,109 @@+import { test, expect, type Page } from '@playwright/test'+import { tauriMockInit, DEFAULT_MODEL_NAME, type TauriMockOptions } from './support/tauri-mock'+import { seedOnboardingDone } from './support/cloud-mock'+import { openNewChat } from './support/ui'++/**+ * Every participant of a group chat can speak as its own persona (samvenice,+ * Discord).+ *+ * Before this a group had one persona for everyone, the chat's own, so two+ * models could not play two characters. The pick now sits on the participant+ * row in the Plugins menu, is stored on the conversation, and each model gets+ * its own system prompt that names it and the others.+ *+ * Measured at the payload: one request per participant, and the system+ * message of each is what decides who the model believes it is.+ *+ * Run: CI=1 npx playwright test e2e/group-chat-personas.spec.ts+ */++const FIRST = 'qwen3:4b'+const SECOND = 'llama3.1:8b'++interface WireBody { model: string; messages: Array<{ role: string; content: unknown }> }++async function chatBodies(page: Page): Promise<WireBody[]> {+ const raw = await page.evaluate(() => {+ const bodies: unknown = Reflect.get(window, '__E2E_CHAT_BODIES__')+ return Array.isArray(bodies) ? bodies.map(String) : []+ })+ return raw.map((b) => JSON.parse(b) as WireBody)+}++const systemOf = (body: WireBody) =>+ body.messages.filter((m) => m.role === 'system').map((m) => String(m.content)).join('\n')++async function pickPersona(page: Page, model: string, persona: string) {+ const row = page.locator(`[data-testid="group-participant"][data-model="${model}"]`)+ await row.getByTestId('group-persona-trigger').click()+ await row.getByTestId('group-persona-list').getByRole('button', { name: persona, exact: true }).click()+ await expect(row.getByTestId('group-persona-trigger')).toContainText(persona)+}++test('two participants answer as two different personas and know each other by name', async ({ page }) => {+ const opts: TauriMockOptions = {+ assistantReply: 'A short answer.',+ modelName: DEFAULT_MODEL_NAME,+ platform: 'mac',+ ollamaModels: [FIRST, SECOND],+ }+ await page.addInitScript(tauriMockInit, opts)+ await seedOnboardingDone(page)+ await page.goto('/')+ await openNewChat(page)++ await page.getByRole('button', { name: /Plugins/ }).click()+ await page.getByRole('button', { name: /Group chat/ }).click()+ for (const model of [FIRST, SECOND]) {+ const row = page.locator(`[data-testid="group-participant"][data-model="${model}"]`)+ await expect(row).toBeVisible()+ // No pick is offered before the model takes part.+ await expect(row.getByTestId('group-persona-trigger')).toHaveCount(0)+ await row.getByRole('button').first().click()+ await expect(row.getByTestId('group-persona-trigger')).toContainText('Chat persona')+ }++ await pickPersona(page, FIRST, 'Code Expert')+ await pickPersona(page, SECOND, 'Helpful Assistant')+ await page.keyboard.press('Escape')++ await page.evaluate(() => { Reflect.set(window, '__E2E_CHAT_BODIES__', []) })+ await page.locator('textarea').first().fill('introduce yourselves')+ await page.getByRole('button', { name: /Send message/i }).click()++ await expect.poll(async () => (await chatBodies(page)).filter((b) => b.model === FIRST || b.model === SECOND).length, { timeout: 30_000 })+ .toBe(2)+ const bodies = await chatBodies(page)+ const first = bodies.find((b) => b.model === FIRST)+ const second = bodies.find((b) => b.model === SECOND)+ if (!first || !second) throw new Error('one participant never got its turn')++ // Each one gets its own role and is told who the other is.+ expect(systemOf(first)).toContain('expert software engineer')+ expect(systemOf(first)).toContain('you are "Code Expert" and only "Code Expert"')+ expect(systemOf(first)).toContain('The other participants are "Helpful Assistant"')+ expect(systemOf(first)).not.toContain('friendly, helpful, and knowledgeable assistant')++ expect(systemOf(second)).toContain('friendly, helpful, and knowledgeable assistant')+ expect(systemOf(second)).toContain('you are "Helpful Assistant" and only "Helpful Assistant"')+ expect(systemOf(second)).toContain('The other participants are "Code Expert"')+ expect(systemOf(second)).not.toContain('expert software engineer')++ // The second speaker reads the first one's answer under the persona name.+ const heard = second.messages.filter((m) => m.role === 'user').map((m) => String(m.content)).join('\n')+ expect(heard).toContain('[Code Expert]')++ // The bubbles say who spoke, persona first.+ const labels = page.getByTestId('answered-by')+ await expect(labels).toHaveCount(2, { timeout: 20_000 })+ await expect(labels.nth(0)).toContainText('Code Expert')+ await expect(labels.nth(1)).toContainText('Helpful Assistant')++ // The pick lives on the conversation: it is still there after a reload.+ await page.reload()+ await page.getByRole('button', { name: /Plugins/ }).click()+ await page.getByRole('button', { name: /Group chat/ }).click()+ await expect(page.locator(`[data-testid="group-participant"][data-model="${FIRST}"]`).getByTestId('group-persona-trigger')).toContainText('Code Expert')+ await expect(page.locator(`[data-testid="group-participant"][data-model="${SECOND}"]`).getByTestId('group-persona-trigger')).toContainText('Helpful Assistant')+})diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.tsindex 382cac02..a71e7531 100644--- a/e2e/support/tauri-mock.ts+++ b/e2e/support/tauri-mock.ts@@ -612,6 +612,14 @@ export function tauriMockInit(opts: TauriMockOptions) {case 'fs_write':record('__E2E_TOOL_CALLS__', { cmd, path: m?.path, content: m?.content })return Promise.resolve({ ok: true, path: m?.path })+ case 'fs_write_bytes':+ // A chat attachment on its way into the working folder. The bytes+ // themselves are not kept, only how many base64 characters arrived.+ record('__E2E_TOOL_CALLS__', {+ cmd, path: m?.path, offset: m?.offset, last: m?.last,+ base64Length: String(m?.base64 ?? '').length,+ })+ return Promise.resolve({ ok: true, path: m?.path })case 'fs_list':record('__E2E_TOOL_CALLS__', { cmd, path: m?.path })return Promise.resolve({ entries: [] })diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rsindex 765a620f..c5d3a27f 100644--- a/src-tauri/src/commands/filesystem.rs+++ b/src-tauri/src/commands/filesystem.rs@@ -808,6 +808,129 @@ pub fn fs_write(path: String, content: String, chatId: Option<String>, workingDi}))}+/// The largest file a chat attachment may be. The WebView enforces the same+/// number before it reads the file (src/lib/chat-files.ts); this is the side+/// that cannot be talked out of it.+const WRITE_BYTES_CAP: u64 = 64 * 1024 * 1024;++/// The hidden sibling a binary upload grows in until its last chunk arrived.+fn upload_part_path(target: &Path) -> Result<PathBuf, String> {+ let parent = target.parent().ok_or_else(|| "No parent directory".to_string())?;+ let name = target+ .file_name()+ .map(|n| n.to_string_lossy().to_string())+ .ok_or_else(|| "No file name".to_string())?;+ Ok(parent.join(format!(".{name}.lu-part")))+}++/// Put a BINARY file into the workspace, in base64 chunks, through the same+/// jail as every other fs command (`resolve_path` -> `contain_within`).+///+/// This is how a file attached in the chat reaches the agent's working folder+/// (3.0.5, applejames on Discord: a ROM file for the model to look at).+/// `fs_write` cannot carry it: it takes text and rewrites line endings.+///+/// CHUNKED, because the alternative is one IPC message with the whole file in+/// base64: 4/3 of the file as a string in the WebView, again as JSON, again in+/// Rust. The chat has been taken down by exactly that shape of memory use+/// before (see chat_attachments.rs). `offset` is where this chunk starts and+/// must be the number of bytes already received, so a lost or repeated chunk+/// is an error and never a silently damaged file.+///+/// NEVER OVER AN EXISTING FILE. With a folder workspace the root is the+/// user's real project, and an attachment that happens to share a name with a+/// file there must not replace it. The caller picks another name and tries+/// again. For the same reason the bytes grow in a hidden `.name.lu-part` file+/// and only the last chunk renames it into place: the visible file is either+/// absent or complete, also for an agent tool that looks at the folder in the+/// middle of the upload.+#[tauri::command]+#[allow(non_snake_case)]+pub async fn fs_write_bytes(+ path: String,+ base64: String,+ offset: u64,+ last: bool,+ chatId: Option<String>,+ workingDirectory: Option<String>,+) -> Result<serde_json::Value, String> {+ tauri::async_runtime::spawn_blocking(move || {+ fs_write_bytes_sync(path, base64, offset, last, chatId, workingDirectory)+ })+ .await+ .map_err(|e| format!("fs_write_bytes task failed to run: {e}"))?+}++#[allow(non_snake_case)]+pub(crate) fn fs_write_bytes_sync(+ path: String,+ base64: String,+ offset: u64,+ last: bool,+ chatId: Option<String>,+ workingDirectory: Option<String>,+) -> Result<serde_json::Value, String> {+ use std::io::Write;++ let full = resolve_path(&path, chatId.as_deref(), workingDirectory.as_deref())?;+ reject_root_as_write_target(+ &workspace_root(chatId.as_deref(), workingDirectory.as_deref()),+ &full,+ )?;+ if full.exists() {+ return Err(format!("File already exists: {}", full.display()));+ }+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(base64.as_bytes())+ .map_err(|_| "Invalid base64 data".to_string())?;+ let total = offset.saturating_add(bytes.len() as u64);+ if total > WRITE_BYTES_CAP {+ return Err(format!(+ "File is too large to attach: more than {} bytes",+ WRITE_BYTES_CAP+ ));+ }++ let part = upload_part_path(&full)?;+ if let Some(parent) = full.parent() {+ fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", os_error::english(&e)))?;+ }+ let mut file = if offset == 0 {+ // A first chunk starts over, also over the leftover of an upload that+ // was abandoned half way.+ fs::File::create(&part)+ } else {+ let have = fs::metadata(&part).map(|m| m.len()).unwrap_or(0);+ if have != offset {+ return Err(format!(+ "Upload out of order: expected the chunk at byte {}, got the one at byte {}",+ have, offset+ ));+ }+ fs::OpenOptions::new().append(true).open(&part)+ }+ .map_err(|e| format!("Write error: {}", os_error::english(&e)))?;+ if let Err(e) = file.write_all(&bytes) {+ drop(file);+ let _ = fs::remove_file(&part);+ return Err(format!("Write error: {}", os_error::english(&e)));+ }+ drop(file);++ if !last {+ return Ok(serde_json::json!({ "status": "partial", "bytes": total }));+ }+ if let Err(e) = fs::rename(&part, &full) {+ let _ = fs::remove_file(&part);+ return Err(format!("Write error (rename): {}", os_error::english(&e)));+ }+ Ok(serde_json::json!({+ "status": "saved",+ "path": full.to_string_lossy(),+ "bytes": total,+ }))+}+#[tauri::command]#[allow(non_snake_case)]pub fn fs_list(@@ -2090,6 +2213,151 @@ mod explorer_byte_read_tests {}}+/// A file attached in the chat reaches the agent's folder through+/// `fs_write_bytes` (3.0.5). Same jail, never over an existing file, and the+/// visible file is complete or absent.+#[cfg(test)]+mod attachment_byte_write_tests {+ use super::*;+ use std::fs;++ fn ws(tag: &str) -> crate::os_paths::TestDir {+ let d = crate::os_paths::test_dir(&format!("fswritebytes-{tag}"));+ allow_root_for_test(&d);+ d+ }++ fn b64(bytes: &[u8]) -> String {+ base64::engine::general_purpose::STANDARD.encode(bytes)+ }++ fn put(dir: &Path, name: &str, bytes: &[u8], offset: u64, last: bool) -> Result<serde_json::Value, String> {+ fs_write_bytes_sync(+ name.into(),+ b64(bytes),+ offset,+ last,+ None,+ Some(dir.to_string_lossy().to_string()),+ )+ }++ #[test]+ fn one_chunk_lands_byte_for_byte() {+ let dir = ws("one");+ // Bytes no text write would survive: NUL, a lone CR, invalid UTF-8.+ let raw: Vec<u8> = vec![0x00, 0x0d, 0xff, 0xfe, 0x0a, 0x80, 0x4e, 0x45, 0x53, 0x1a];+ let v = put(&dir, "game.nes", &raw, 0, true).expect("write");+ assert_eq!(v["status"], "saved");+ assert_eq!(v["bytes"], raw.len());+ assert_eq!(fs::read(dir.join("game.nes")).unwrap(), raw);+ assert!(!dir.join(".game.nes.lu-part").exists(), "the part file must be gone");+ }++ #[test]+ fn chunks_are_joined_and_the_file_only_appears_with_the_last_one() {+ let dir = ws("chunks");+ let a = vec![1u8; 1000];+ let b = vec![2u8; 500];+ let first = put(&dir, "rom.bin", &a, 0, false).expect("first");+ assert_eq!(first["status"], "partial");+ assert!(!dir.join("rom.bin").exists(), "half a file must not be visible under its name");+ let second = put(&dir, "rom.bin", &b, 1000, true).expect("second");+ assert_eq!(second["status"], "saved");+ assert_eq!(second["bytes"], 1500);+ let mut whole = a.clone();+ whole.extend_from_slice(&b);+ assert_eq!(fs::read(dir.join("rom.bin")).unwrap(), whole);+ }++ #[test]+ fn a_chunk_at_the_wrong_offset_is_refused() {+ let dir = ws("order");+ put(&dir, "rom.bin", &[1u8; 100], 0, false).expect("first");+ let err = put(&dir, "rom.bin", &[2u8; 100], 50, true).expect_err("wrong offset");+ assert!(err.contains("out of order"), "got: {err}");+ assert!(!dir.join("rom.bin").exists());+ // And a chunk for an upload that never started.+ let err = put(&dir, "other.bin", &[2u8; 100], 100, true).expect_err("no first chunk");+ assert!(err.contains("out of order"), "got: {err}");+ }++ #[test]+ fn a_first_chunk_starts_over_after_an_abandoned_upload() {+ let dir = ws("restart");+ put(&dir, "rom.bin", &[9u8; 300], 0, false).expect("abandoned");+ put(&dir, "rom.bin", &[7u8; 10], 0, true).expect("fresh");+ assert_eq!(fs::read(dir.join("rom.bin")).unwrap(), vec![7u8; 10]);+ }++ #[test]+ fn an_existing_file_is_never_replaced() {+ let dir = ws("exists");+ fs::write(dir.join("notes.txt"), b"the user's own file").unwrap();+ let err = put(&dir, "notes.txt", b"attachment", 0, true).expect_err("exists");+ assert!(err.contains("already exists"), "got: {err}");+ assert_eq!(fs::read(dir.join("notes.txt")).unwrap(), b"the user's own file");+ }++ #[test]+ fn a_path_outside_the_workspace_is_refused() {+ let dir = ws("outside");+ let root = dir.join("repo");+ fs::create_dir_all(&root).unwrap();+ let climb = fs_write_bytes_sync(+ "../escaped.bin".into(),+ b64(b"x"),+ 0,+ true,+ None,+ Some(root.to_string_lossy().to_string()),+ );+ assert!(climb.is_err(), "a .. climb must not write");+ assert!(!dir.join("escaped.bin").exists());+ let absolute = fs_write_bytes_sync(+ dir.join("escaped.bin").to_string_lossy().to_string(),+ b64(b"x"),+ 0,+ true,+ None,+ Some(root.to_string_lossy().to_string()),+ );+ assert!(absolute.is_err(), "an outside absolute path must not write");+ assert!(!dir.join("escaped.bin").exists());+ }++ #[test]+ fn the_workspace_root_itself_is_not_a_file() {+ let dir = ws("root");+ let err = put(&dir, ".", b"x", 0, true).expect_err("root as target");+ assert!(err.contains("Not a file"), "got: {err}");+ }++ #[test]+ fn bytes_past_the_cap_are_refused() {+ let dir = ws("cap");+ let err = put(&dir, "huge.bin", &[0u8; 16], WRITE_BYTES_CAP, true).expect_err("over the cap");+ assert!(err.contains("too large"), "got: {err}");+ assert!(!dir.join("huge.bin").exists());+ }++ #[test]+ fn broken_base64_is_an_error_not_an_empty_file() {+ let dir = ws("b64");+ let err = fs_write_bytes_sync(+ "x.bin".into(),+ "not base64 !!".into(),+ 0,+ true,+ None,+ Some(dir.to_string_lossy().to_string()),+ )+ .expect_err("bad base64");+ assert!(err.contains("Invalid base64"), "got: {err}");+ assert!(!dir.join("x.bin").exists());+ }+}+/// KF-15 — `fs_write` and the workspace ROOT itself.////// The dev-server half of this was closed in a50fddef; this is the same hole ondiff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex a1900aad..93296a9f 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -520,6 +520,7 @@ fn main() {commands::filesystem::fs_read,commands::filesystem::fs_read_bytes,commands::filesystem::fs_write,+ commands::filesystem::fs_write_bytes,commands::filesystem::fs_list,commands::filesystem::fs_search,commands::filesystem::fs_info,diff --git a/src/api/backend.ts b/src/api/backend.tsindex 849f0e7b..be7e3346 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -591,6 +591,9 @@ export async function backendCall<T = unknown>(// command" and every preview fell over.fs_read_bytes: { path: "/local-api/fs-read-bytes", method: "POST" },fs_write: { path: "/local-api/fs-write", method: "POST" },+ // One base64 chunk of a file attached in the chat, on its way into the+ // working folder (3.0.5, lib/chat-files.ts).+ fs_write_bytes: { path: "/local-api/fs-write-bytes", method: "POST" },fs_list: { path: "/local-api/fs-list", method: "POST" },fs_search: { path: "/local-api/fs-search", method: "POST" },fs_info: { path: "/local-api/fs-info", method: "POST" },diff --git a/src/components/chat/ChatFileChip.tsx b/src/components/chat/ChatFileChip.tsxnew file mode 100644index 00000000..6b1f1ee8--- /dev/null+++ b/src/components/chat/ChatFileChip.tsx@@ -0,0 +1,41 @@+import { File as FileIcon, X } from 'lucide-react'+import type { FileAttachment } from '../../types/chat'+import { formatBytes } from '../../lib/formatters'++/**+ * One attached file as a chip: name, the type read from its bytes, its size.+ *+ * The same chip stands in the composer (with the x) and in the transcript+ * (without it). It shows a description, never the file: the bytes are not in+ * the chat (lib/chat-files.ts), so there is nothing here to open or save.+ */+export function ChatFileChip({ file, onRemove, testId = 'chat-file-chip' }: {+ file: FileAttachment+ /** Composer only: take the file off the draft again. */+ onRemove?: () => void+ testId?: string+}) {+ const where = file.workspacePath ? `\nIn the working folder: ${file.workspacePath}` : ''+ return (+ <div+ data-testid={testId}+ title={`${file.name}\n${file.kind}, ${formatBytes(file.size)}\nSHA-256 ${file.sha256}${where}`}+ className="flex items-center gap-1.5 max-w-[240px] pl-2 pr-1.5 py-1 rounded-lg border border-gray-200 dark:border-white/10 bg-white dark:bg-white/[0.04] text-left"+ >+ <FileIcon size={13} className="shrink-0 text-gray-400" />+ <span className="min-w-0 flex flex-col leading-tight">+ <span className="truncate t-mono text-gray-800 dark:text-gray-200">{file.name}</span>+ <span className="truncate t-micro text-gray-500 dark:text-gray-400">{file.kind}, {formatBytes(file.size)}</span>+ </span>+ {onRemove && (+ <button+ onClick={onRemove}+ aria-label={`Remove ${file.name}`}+ className="shrink-0 w-4 h-4 rounded-full flex items-center justify-center text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors"+ >+ <X size={9} />+ </button>+ )}+ </div>+ )+}diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex c17922dd..150ec756 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -13,6 +13,9 @@ import { clampEffort, effortChoices, effortLabel, nextEffort, DEFAULT_EFFORT } fimport type { AgentToolCall } from '../../types/agent-mode'import type { ImageAttachment } from '../../types/chat'import { MAX_CHAT_IMAGES, prepareChatImages } from '../../lib/chat-image-input'+import { FILE_ONLY_TEXT, MAX_CHAT_FILES, TOO_MANY_FILES_MESSAGE, prepareChatFile, type ChatFileInput } from '../../lib/chat-files'+import { fileExtension } from '../../lib/file-magic'+import { ChatFileChip } from './ChatFileChip'import { COMPOSER_MAX_W } from './composer-width'import { consumeComposerFocusPending } from '../../hooks/useKeyboardShortcuts'import { useChatNoticeStore, CHAT_NOTICE_MS } from '../../stores/chatNoticeStore'@@ -20,7 +23,7 @@ import { MONOGRAM, MONOGRAM_INVERT } from '../layout/brand'import { fitTextarea } from '../../lib/fit-textarea'interface Props {- onSend: (content: string, images?: ImageAttachment[]) => void+ onSend: (content: string, images?: ImageAttachment[], files?: ChatFileInput[]) => voidonStop: () => void/** THIS conversation is answering: the slot shows Stop. */isGenerating: boolean@@ -63,6 +66,13 @@ interface Props {composerActions?: ReactNode}+/**+ * Files a model cannot read from a summary, but can from the Documents panel+ * (it extracts their text). They still attach; the line above the transcript+ * names the better way.+ */+const DOCUMENT_EXTENSIONS = new Set(['pdf', 'doc', 'docx', 'odt', 'rtf', 'epub', 'pptx', 'xlsx'])+/** How long the synchronous double-fire guard below stays shut. */const SEND_LOCK_MS = 700@@ -90,9 +100,14 @@ function passSendLock(lock: { current: number }): boolean {export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pendingApproval, onApprove, onReject, disabled, slashCommands, composerModel, composerActions, composerAbove }: Props) {const [input, setInput] = useState('')const [images, setImages] = useState<ImageAttachment[]>([])+ // Files of any other kind (3.0.5). Each entry is a description plus the+ // handle to the bytes; nothing of the file itself is held here.+ const [files, setFiles] = useState<ChatFileInput[]>([])const [isDragOver, setIsDragOver] = useState(false)const [preparingImages, setPreparingImages] = useState(false)+ const [preparingFiles, setPreparingFiles] = useState(false)const imageJob = useRef({ busy: false, epoch: 0 })+ const fileJob = useRef({ busy: false })const [isVoiceRecording, setIsVoiceRecording] = useState(false)// Slash-command autocomplete (v2.5.3). When the input is a lone "/token", show// the matching agent commands; ↑/↓ to move, Enter/Tab to pick, Esc to dismiss.@@ -106,8 +121,8 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p* 03.09.2026, mit dem naheliegenden Ausgang: der Satz geht an den falschen* Empfaenger. Ihn beim Wechsel einfach zu leeren waere die andere Haelfte* desselben Fehlers, nur teurer (Arbeit weg), darum wird er beiseitegelegt- * und beim Zurueckkommen wieder hingelegt. Bilder reisen mit dem Text, sonst- * hinge die Anlage am falschen Satz.+ * und beim Zurueckkommen wieder hingelegt. Bilder und Dateien reisen mit dem+ * Text, sonst hinge die Anlage am falschen Satz.** WIE der Wechsel bemerkt wird, ist nicht Geschmack, sondern die Stelle, an* der dieser Block zweimal mit React aneinandergeriet. Er stand bis zum@@ -151,7 +166,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pconst stop = () => { job.epoch++; unsubscribe() }return stop}, [])- const [entwuerfe, setEntwuerfe] = useState<Record<string, { text: string; bilder: ImageAttachment[] }>>({})+ const [entwuerfe, setEntwuerfe] = useState<Record<string, { text: string; bilder: ImageAttachment[]; dateien: ChatFileInput[] }>>({})const [letztesGespraech, setLetztesGespraech] = useState(conversationId)if (letztesGespraech !== conversationId) {const vorher = letztesGespraech@@ -159,12 +174,13 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pif (vorher) {const text = inputconst bilder = images+ const dateien = files// Der Aktualisierer laeuft unter StrictMode zweimal und muss deshalb// beim zweiten Mal dasselbe Ergebnis liefern wie beim ersten. Er// rechnet nur aus `bisher`, haengt also an nichts, was er selbst// veraendert.setEntwuerfe((bisher) => {- if (text || bilder.length) return { ...bisher, [vorher]: { text, bilder } }+ if (text || bilder.length || dateien.length) return { ...bisher, [vorher]: { text, bilder, dateien } }if (!(vorher in bisher)) return bisherconst ohne = { ...bisher }delete ohne[vorher]@@ -177,6 +193,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pconst zurueck = conversationId ? entwuerfe[conversationId] : undefinedsetInput(zurueck?.text ?? '')setImages(zurueck?.bilder ?? [])+ setFiles(zurueck?.dateien ?? [])setCmdMenu([])}const textareaRef = useRef<HTMLTextAreaElement>(null)@@ -251,23 +268,62 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p// bliebe auf einer Zeile stehen statt den Entwurf zu zeigen.}, [input, conversationId])- const addFiles = useCallback(async (files: FileList | File[]) => {- const all = Array.from(files)- const imageFiles = all.filter(f => f.type.startsWith('image/'))- // A non-image file (PDF, Word, text, …) can't ride along as a chat image,- // it belongs in the Documents panel (RAG) so the model can actually read it.- // Silently dropping it made a user think their PDF attached when it didn't,- // and the model then hallucinated that it "couldn't receive attachments"- // (GH #69). Der Satz ist derselbe geblieben, nur sein Platz nicht mehr der- // Composer-Kasten, sondern der Kopf des Verlaufs (`ChatNotices`).- if (imageFiles.length < all.length) {- useChatNoticeStore.getState().show(- 'attachment-is-not-an-image',- 'The clip attaches images. To ask about a PDF, Word, or text file, add it in the Documents panel.',- 'ruhig',- CHAT_NOTICE_MS,- )+ /**+ * Any file that is not an image (3.0.5). The model cannot read bytes, so+ * the file is read once here and turned into a description (lib/chat-files);+ * the chip below shows it, and nothing of the file is kept in the chat.+ */+ const addOtherFiles = useCallback(async (picked: File[]) => {+ const notices = useChatNoticeStore.getState()+ const job = fileJob.current+ if (job.busy) {+ notices.show('file-attach', 'Still reading the previous files. Add these again in a moment.', 'ruhig', CHAT_NOTICE_MS)+ return+ }+ const slots = MAX_CHAT_FILES - files.length+ if (slots <= 0) {+ notices.show('file-attach', TOO_MANY_FILES_MESSAGE, 'ruhig', CHAT_NOTICE_MS)+ return}+ job.busy = true+ const startedIn = conversationId+ setPreparingFiles(true)+ const problems: string[] = picked.length > slots ? [TOO_MANY_FILES_MESSAGE] : []+ const ready: ChatFileInput[] = []+ try {+ for (const file of picked.slice(0, slots)) {+ try {+ ready.push(await prepareChatFile(file))+ } catch (err) {+ problems.push(err instanceof Error ? err.message : 'This file could not be read.')+ }+ }+ // The draft belongs to the conversation it was started in.+ if (useChatStore.getState().activeConversationId !== startedIn) return+ if (ready.length) setFiles((prev) => [...prev, ...ready].slice(0, MAX_CHAT_FILES))+ if (problems.length) notices.show('file-attach', problems[0], 'ruhig', CHAT_NOTICE_MS)+ else notices.dismiss('file-attach')+ // A PDF or Word file attaches like any other, but the model gets far+ // more out of it through the Documents panel (GH #69).+ if (ready.some(({ attachment }) => DOCUMENT_EXTENSIONS.has(fileExtension(attachment.name)))) {+ notices.show(+ 'document-belongs-in-docs',+ 'The model only gets a summary of this document. To ask about its text, add it in the Documents panel.',+ 'ruhig',+ CHAT_NOTICE_MS,+ )+ }+ } finally {+ job.busy = false+ setPreparingFiles(false)+ }+ }, [files.length, conversationId])++ const addFiles = useCallback(async (picked: FileList | File[]) => {+ const all = Array.from(picked)+ const imageFiles = all.filter(f => f.type.startsWith('image/'))+ const otherFiles = all.filter(f => !f.type.startsWith('image/'))+ if (otherFiles.length > 0) void addOtherFiles(otherFiles)if (imageFiles.length === 0) return// Die Zeilen zum Bildanhang stehen oben im Verlauf (`ChatNotices`), nie// im Eingabekasten: „NICHTS im Prompt-Fenster", David 21.09.2026.@@ -303,7 +359,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, puseChatNoticeStore.getState().dismiss('image-attach')}}- }, [images.length, conversationId])+ }, [images.length, conversationId, addOtherFiles])/*** Ein Bild an einem Modell, das keine sieht.@@ -331,6 +387,10 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, psetImages(prev => prev.filter((_, i) => i !== index))}+ const removeFile = (index: number) => {+ setFiles(prev => prev.filter((_, i) => i !== index))+ }+// Write a dictation transcript (interim or final) into the input as// base + transcript; the layout effect above sizes the field. NEVER sends,// because the user reviews and presses Send (David 2026-06-06).@@ -348,11 +408,17 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pconst sendLockRef = useRef(0)const handleSend = () => {const trimmed = input.trim()- if (imageJob.current.busy || (!trimmed && images.length === 0) || isGenerating || waitingForLocalLane || disabled) return+ if (imageJob.current.busy || fileJob.current.busy || (!trimmed && images.length === 0 && files.length === 0) || isGenerating || waitingForLocalLane || disabled) returnif (!passSendLock(sendLockRef)) return- onSend(trimmed || '(image)', images.length > 0 ? images : undefined)+ const text = trimmed || (images.length > 0 ? '(image)' : FILE_ONLY_TEXT)+ const pictures = images.length > 0 ? images : undefined+ // The third argument only exists for a message that carries files, so a+ // send without them reaches its handler exactly as it always did.+ if (files.length > 0) onSend(text, pictures, files)+ else onSend(text, pictures)setInput('')setImages([])+ setFiles([])setCmdMenu([])}@@ -408,15 +474,18 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p}}- // Paste handler for clipboard images (Ctrl+V screenshots)+ // Paste handler for clipboard images (Ctrl+V screenshots) and copied files.+ // Pasted TEXT stays a normal paste: only items of kind "file" are taken.const handlePaste = useCallback((e: React.ClipboardEvent) => {const items = e.clipboardData?.itemsif (!items) return- const imageItems = Array.from(items).filter(item => item.type.startsWith('image/'))- if (imageItems.length === 0) return+ const pasted = Array.from(items)+ .filter(item => item.kind === 'file')+ .map(item => item.getAsFile())+ .filter((file): file is File => file !== null)+ if (pasted.length === 0) returne.preventDefault()- const files = imageItems.map(item => item.getAsFile()).filter(Boolean) as File[]- addFiles(files)+ addFiles(pasted)}, [addFiles])// Drag & Drop handlers@@ -523,15 +592,18 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, pWartezeile der lokalen Spur -> LocalLaneWaitLine, gezeichnetvon ChatView/CodexView als Geschwister UEBER diesem Kasten- Anhang ist kein Bild (GH #69) -> ChatNotices, oben im Verlauf+ Dokument gehoert in die Ablage (GH #69) -> ChatNotices, oben im VerlaufModell sieht keine Bilder -> ChatNotices, oben im VerlaufWas hier bleibt, ist kein Hinweis: die Bildvorschauen sind derAnhang selbst, und die Freigabe ist eine Entscheidung mit zweiKnoepfen. */}- {/* Image previews */}- {images.length > 0 && (+ {/* The attachments of this draft, in one row that may wrap: image+ previews, then a chip per file of any other kind (3.0.5). A chip+ IS the attachment (name, detected type, size), not a hint+ about it. */}+ {(images.length > 0 || files.length > 0) && (<div className="flex gap-1.5 mb-1.5 flex-wrap">{images.map((img, i) => (<div key={i} className="relative group">@@ -551,6 +623,14 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p</span></div>))}+ {files.map(({ attachment }, i) => (+ <ChatFileChip+ key={`${attachment.sha256}-${i}`}+ file={attachment}+ testId="composer-file-chip"+ onRemove={() => removeFile(i)}+ />+ ))}</div>)}@@ -588,7 +668,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, ponKeyDown={handleKeyDown}onBlur={() => setTimeout(() => setCmdMenu([]), 120)}onPaste={handlePaste}- placeholder={disabled ? "Unavailable" : isDragOver ? "Drop images here..." : isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : "Message..."}+ placeholder={disabled ? "Unavailable" : isDragOver ? "Drop files here..." : isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : "Message..."}disabled={disabled}rows={1}className="lu-fokus-am-kasten w-full bg-transparent resize-none text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-600 focus:outline-none text-[12px] leading-relaxed max-h-[200px] disabled:opacity-50 scrollbar-thin"@@ -614,16 +694,16 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p{/* Clip button */}<buttononClick={() => fileInputRef.current?.click()}- disabled={isGenerating || preparingImages}+ disabled={isGenerating || preparingImages || preparingFiles}className="lu-control lu-control--icon"- title="Attach images. For PDFs and documents use the Documents panel"+ title="Attach images or files"><Paperclip size={14} /></button><inputref={fileInputRef}type="file"- accept="image/png,image/jpeg,image/webp,image/gif"+ data-testid="composer-file-input"multipleclassName="hidden"onChange={(e) => { if (e.target.files) addFiles(e.target.files); e.target.value = '' }}@@ -758,7 +838,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p) : (<buttononClick={handleSend}- disabled={preparingImages || (!input.trim() && images.length === 0) || isTranscribing || !!waitingForLocalLane}+ disabled={preparingImages || preparingFiles || (!input.trim() && images.length === 0 && files.length === 0) || isTranscribing || !!waitingForLocalLane}className="lu-control lu-control--icon lu-primary w-full h-full"aria-label="Send message">diff --git a/src/components/chat/ChatNotices.tsx b/src/components/chat/ChatNotices.tsxindex 3bacfc8d..2d2fcb11 100644--- a/src/components/chat/ChatNotices.tsx+++ b/src/components/chat/ChatNotices.tsx@@ -11,24 +11,25 @@* fuer Anmerkungen und Fehler vorschreibt: eine Zeile, kein Kasten, ruhiges* Grau oder Rot, und ein x, das sie wegnimmt.*/-import { Bot, FolderOpen, ImageOff, Images, Paperclip } from 'lucide-react'+import { Bot, FileText, FolderOpen, ImageOff, Images, Paperclip } from 'lucide-react'import { Hinweis } from '../ui/Hinweis'import { useChatNoticeStore, CONVERSATION_BOUND, type ChatNoticeId } from '../../stores/chatNoticeStore'import { COMPOSER_MAX_W } from './composer-width'/** Das Symbol je Zeile. Keine eigene Farbe: die traegt der Ton. */const ICON: Record<ChatNoticeId, typeof Paperclip> = {- 'attachment-is-not-an-image': Paperclip,+ 'document-belongs-in-docs': FileText,'model-cannot-see-images': ImageOff,'image-attach': Images,+ 'file-attach': Paperclip,'agent-outside-workspace': FolderOpen,'agent-for-local-files': Bot,}interface Props {- /** Die Dokumentenablage oeffnen, fuer die Zeile ueber den fehlgegangenen- * Anhang. Fehlt sie, faellt der Knopf weg und der Satz bleibt wahr. */+ /** Die Dokumentenablage oeffnen, fuer die Zeile ueber ein angehaengtes+ * Dokument. Fehlt sie, faellt der Knopf weg und der Satz bleibt wahr. */onAttachDocs?: () => void/** Wo gezeichnet wird. Im Code-Bereich fallen die Chat-Agent-Zeilen weg. */surface?: 'chat' | 'code'@@ -39,7 +40,10 @@ export function ChatNotices({ onAttachDocs, surface = 'chat' }: Props) {const dismiss = useChatNoticeStore((s) => s.dismiss)// Die Zeilen ueber den Agent-Knopf und seinen Ordner gelten im CHAT. Im// Code-Bereich gibt es diesen Knopf nicht (Gegenprobe 01.10.2026).- const notices = surface === 'code' ? all.filter((n) => !CONVERSATION_BOUND.has(n.id)) : all+ // Dasselbe gilt fuer den Weg in die Dokumentenablage: die gibt es nur im Chat.+ const notices = surface === 'code'+ ? all.filter((n) => !CONVERSATION_BOUND.has(n.id) && n.id !== 'document-belongs-in-docs')+ : allif (notices.length === 0) return null@@ -56,7 +60,7 @@ export function ChatNotices({ onAttachDocs, surface = 'chat' }: Props) {onDismiss={() => dismiss(n.id)}>{n.text}- {n.id === 'attachment-is-not-an-image' && onAttachDocs && (+ {n.id === 'document-belongs-in-docs' && onAttachDocs && (<buttononClick={() => { dismiss(n.id); onAttachDocs() }}className="ml-1 underline underline-offset-2 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex 3d210a1c..ab83e5fe 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -437,8 +437,8 @@ export function ChatView() {sind (David, 21.09.2026: „NICHTS im prompt fenster!").Oben im Verlauf, ruhig, mit x, und ausdruecklich NICHT amEingabefeld. `ChatNotices` traegt die beiden Zeilen, die- im Composer entstehen (Anhang ist kein Bild, Modell sieht- keine Bilder), `RetrievalErrorBar` den Fehler, dass die+ im Composer entstehen (ein Dokument gehoert in die Ablage,+ Modell sieht keine Bilder), `RetrievalErrorBar` den Fehler, dass dieDokumente zu einer Antwort nicht durchsucht wurden. */}<ChatNotices onAttachDocs={() => setRagPanelOpen(true)} /><RetrievalErrorBar />diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex 9e85de05..3d2ad93d 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -5,6 +5,8 @@ import { useChatStore } from '../../stores/chatStore'import { useBackgroundAgentWake } from '../../hooks/useBackgroundAgentWake'import { useGenerationStore } from '../../stores/generationStore'import { ChatInput } from './ChatInput'+import { ChatFileChip } from './ChatFileChip'+import { FILE_ONLY_TEXT } from '../../lib/chat-files'import { ToolCallBlock } from './ToolCallBlock'import { ToolCallBand } from './ToolCallBand'import { groupAgentBlocks } from '../../lib/tool-call-groups'@@ -578,7 +580,17 @@ export function CodexView() {// there are no per-iteration answer blocks (interleave// already rendered those). Assistant drops the bubble to// match the regular Chat view; user keeps the right anchor.- const textContent = cleanContent && (msg.role === 'user' || !hasAnswerBlock) ? (+ // Files attached to this instruction: a chip each. The+ // bytes are in the working folder, not in the chat.+ const fileChips = msg.role === 'user' && msg.files?.length ? (+ <div className="flex gap-1 flex-wrap justify-end">+ {msg.files.map((file, i) => (+ <ChatFileChip key={`${file.sha256}-${i}`} file={file} />+ ))}+ </div>+ ) : null+ const onlyFiles = !!fileChips && msg.displayContent === FILE_ONLY_TEXT+ const textContent = cleanContent && !onlyFiles && (msg.role === 'user' || !hasAnswerBlock) ? (<div className={msg.role === 'user'? 'rounded-lg px-2.5 py-1.5 bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'@@ -665,6 +677,7 @@ export function CodexView() {<>{reflection}{transcript}+ {fileChips}{textContent}</>)@@ -718,7 +731,9 @@ export function CodexView() {{/* Input */}<ChatInput- onSend={(content) => sendInstruction(content)}+ // Images have no path into a coding run; attached files do, they+ // are copied into the working folder (lib/chat-files.ts).+ onSend={(content, _images, files) => sendInstruction(content, files ? { files } : undefined)}onStop={stopCodex}// Store flag, not the hook's local isRunning (audit A2): the view// remounts on every tab switch and a fresh hook says "idle" whilediff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsxindex bf099ed4..ca32924c 100644--- a/src/components/chat/MessageBubble.tsx+++ b/src/components/chat/MessageBubble.tsx@@ -1,4 +1,6 @@import { ChatAttachment } from './ChatAttachment'+import { ChatFileChip } from './ChatFileChip'+import { FILE_ONLY_TEXT } from '../../lib/chat-files'import { motion } from 'framer-motion'import { User, Copy, Check, Pencil, RefreshCw, X, Wrench, Trash2, Scissors, Unlink } from 'lucide-react'import { useState, useRef, useEffect, useMemo, memo } from 'react'@@ -49,9 +51,12 @@ interface Props {isLast?: boolean/** This bubble is the one currently streaming — hides its action bar. */isStreaming?: boolean+ /** Group chat: the persona this participant speaks as, when it has one of+ * its own. Shown in front of the model name. */+ speakerName?: string}-function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject, isLast, isStreaming }: Props) {+function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject, isLast, isStreaming, speakerName }: Props) {const [copied, setCopied] = useState(false)const [isEditing, setIsEditing] = useState(false)const [editContent, setEditContent] = useState('')@@ -156,7 +161,9 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o}, [isEditing])const handleCopy = () => {- navigator.clipboard.writeText(message.content)+ // A message with files copies what was typed, not the file summaries the+ // model received along with it.+ navigator.clipboard.writeText(isUser && message.files?.length ? (message.displayContent ?? message.content) : message.content)setCopied(true)setTimeout(() => setCopied(false), 2000)}@@ -312,8 +319,8 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o// der Fehler in einem Wort: der volle Name ist der Modellname, die// Kennung davor ist unsere Adresse. Wer den Zeiger auf der Zeile// ruhen liess, bekam sie zu sehen, obwohl sie ihm nichts sagt.- <div title={displayModelName(message.modelId)} className="t-mono text-gray-500 dark:text-gray-400 pl-1">- {answeredByName}+ <div title={displayModelName(message.modelId)} data-testid="answered-by" className="t-mono text-gray-500 dark:text-gray-400 pl-1">+ {speakerName ? `${speakerName} · ${answeredByName}` : answeredByName}</div>)}{/* Thinking block — auto-expands while this (last) turn is still@@ -407,6 +414,15 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, omessage so a swap shows only in the active turn. */}{!isUser && isLast && <VramSwitchCard />}+ {/* Attached files: a chip each, the bytes are not in the chat. */}+ {message.files && message.files.length > 0 && (+ <div className="flex gap-1 flex-wrap">+ {message.files.map((file, i) => (+ <ChatFileChip key={`${file.sha256}-${i}`} file={file} />+ ))}+ </div>+ )}+{/* Image attachments */}{message.images && message.images.length > 0 && (<div className="flex gap-1 flex-wrap">@@ -451,9 +467,14 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o<button onClick={cancelEdit} className="p-0.5 rounded hover:bg-red-500/20 text-red-400 transition-colors"><X size={11} /></button></div></div>+ ) : isUser && message.files?.length && message.displayContent === FILE_ONLY_TEXT ? (+ // Nothing was typed: the chips below are the whole message.+ null) : isUser ? (// Slash command: show the short "/commit" (displayContent), not the// long expanded instruction held in content (which drives the model).+ // The same holds for a message with files: content carries their+ // summaries for the model, the bubble shows what was typed.<p className="text-[0.78rem] leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{message.displayContent || message.content}</p>) : (// Answer-blocks (when present) already rendered the per-iterationdiff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsxindex 0311db70..fb952592 100644--- a/src/components/chat/MessageList.tsx+++ b/src/components/chat/MessageList.tsx@@ -1,6 +1,8 @@-import { useCallback, useEffect, useRef, useState } from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import type { CSSProperties } from 'react'import { useChatStore } from '../../stores/chatStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { groupSpeakers } from '../../lib/group-chat'import { useAutoScroll } from '../../hooks/useAutoScroll'import { MessageBubble } from './MessageBubble'import { WorkingAnchor } from './WorkingAnchor'@@ -72,6 +74,16 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelreturn s.conversations.find((c) => c.id === s.activeConversationId)})+ // Group chat: who speaks as which persona (3.0.5). Resolved once for the+ // list, so each bubble gets a plain string and stays memoised.+ const personas = useSettingsStore((s) => s.personas)+ const groupModels = conversation?.groupModels+ const groupPersonas = conversation?.groupPersonas+ const speakers = useMemo(+ () => groupSpeakers(groupModels ?? [], groupPersonas, personas),+ [groupModels, groupPersonas, personas],+ )+const lastMessage = conversation?.messages[conversation.messages.length - 1]// The approval id is part of the scroll trigger (G31): a run waiting for a// decision often adds NO content, so the list stood still while the inline@@ -204,6 +216,9 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModelpendingApprovalId={pendingApprovalId}onApprove={onApprove}onReject={onReject}+ speakerName={message.modelId && speakers[message.modelId]?.personaPrompt !== undefined+ ? speakers[message.modelId].name+ : undefined}/>)}{compactAt.get(message.id)?.map((record) => (diff --git a/src/components/chat/PluginsDropdown.tsx b/src/components/chat/PluginsDropdown.tsxindex 3243a78b..1b0e8576 100644--- a/src/components/chat/PluginsDropdown.tsx+++ b/src/components/chat/PluginsDropdown.tsx@@ -35,6 +35,8 @@ export function PluginsDropdown({const [cavemanOpen, setCavemanOpen] = useState(false)const [personaOpen, setPersonaOpen] = useState(false)const [groupOpen, setGroupOpen] = useState(false)+ // Which participant's persona list is open, by model name.+ const [personaFor, setPersonaFor] = useState<string | null>(null)const { getActivePersona, setActivePersona } = useSettingsStore()const activePersona = getActivePersona()const allPersonas = useSettingsStore((s) => s.personas)@@ -68,6 +70,8 @@ export function PluginsDropdown({// Group chat v1 (Nurse KillJoy): the selection lives on the conversation,// exactly like the persona flag, so every chat keeps its own line-up.const setGroupModels = useChatStore((s) => s.setGroupModels)+ const setGroupPersona = useChatStore((s) => s.setGroupPersona)+ const groupPersonas = activeConv?.groupPersonasconst models = useModelStore((s) => s.models)const groupModels = activeConv?.groupModels ?? []const isGroupActive = isGroupChat(activeConv?.groupModels)@@ -293,34 +297,84 @@ export function PluginsDropdown({</button>{groupOpen && (activeConvId ? (- <div className="pb-1.5 space-y-0.5 max-h-[180px] overflow-y-auto scrollbar-thin">+ <div className="pb-1.5 space-y-0.5 max-h-[220px] overflow-y-auto scrollbar-thin"><p className="px-2 pb-0.5 text-[0.5rem] leading-snug text-gray-400">- Pick 2 to {GROUP_CHAT_MAX} models. They answer in turn on every message, and each sees what the others said.+ Pick 2 to {GROUP_CHAT_MAX} models. They answer in turn on every message, and each sees what the others said. Each one can speak as its own persona.</p>{groupChatCandidates(models, groupModels).map((m) => {const on = groupModels.includes(m.name)const full = !on && groupModels.length >= GROUP_CHAT_MAX+ // The persona THIS participant speaks as. None picked (or a+ // persona that was deleted since) means it follows the+ // chat's own persona setting, as every group did before.+ const ownPersona = allPersonas.find((p) => p.id === groupPersonas?.[m.name])+ const listOpen = on && personaFor === m.namereturn (- <button- key={m.name}- disabled={full}- onClick={() =>- setGroupModels(- activeConvId,- on ? groupModels.filter((x) => x !== m.name) : [...groupModels, m.name],- )- }- className={`w-full flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors ${- on- ? 'bg-purple-500/10 text-purple-600 dark:text-purple-400'- : full- ? 'text-gray-400/50 cursor-default'- : 'text-gray-500 hover:bg-gray-50 dark:hover:bg-white/[0.04] hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- {on && <div className="w-1 h-1 rounded-full bg-purple-400 shrink-0" />}- <span className="text-[0.55rem] font-medium truncate" title={displayModelName(m.name)}>{displayModelName(m.name)}</span>- </button>+ <div key={m.name} data-testid="group-participant" data-model={m.name}>+ <div+ className={`flex items-center rounded transition-colors ${+ on ? 'bg-purple-500/10 text-purple-600 dark:text-purple-400' : ''+ }`}+ >+ <button+ disabled={full}+ onClick={() => {+ if (on) setPersonaFor(null)+ setGroupModels(+ activeConvId,+ on ? groupModels.filter((x) => x !== m.name) : [...groupModels, m.name],+ )+ }}+ className={`flex-1 min-w-0 flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors ${+ on+ ? ''+ : full+ ? 'text-gray-400/50 cursor-default'+ : 'text-gray-500 hover:bg-gray-50 dark:hover:bg-white/[0.04] hover:text-gray-700 dark:hover:text-gray-300'+ }`}+ >+ {on && <div className="w-1 h-1 rounded-full bg-purple-400 shrink-0" />}+ <span className="text-[0.55rem] font-medium truncate" title={displayModelName(m.name)}>{displayModelName(m.name)}</span>+ </button>+ {on && (+ <button+ onClick={() => setPersonaFor(listOpen ? null : m.name)}+ aria-expanded={listOpen}+ aria-label={`Persona for ${displayModelName(m.name)}`}+ title="The persona this model speaks as in this chat"+ data-testid="group-persona-trigger"+ className="shrink-0 max-w-[45%] flex items-center gap-0.5 px-1.5 py-1 rounded t-micro hover:bg-purple-500/15 transition-colors"+ >+ <User size={8} className="shrink-0" />+ <span className="truncate">{ownPersona?.name ?? 'Chat persona'}</span>+ <ChevronDown size={8} className={`shrink-0 transition-transform ${listOpen ? 'rotate-180' : ''}`} />+ </button>+ )}+ </div>+ {listOpen && (+ <div data-testid="group-persona-list" className="ml-3 my-0.5 pl-1.5 border-l border-purple-400/30 space-y-0.5">+ {[{ id: null, name: 'Chat persona' }, ...allPersonas].map((p) => {+ const picked = (ownPersona?.id ?? null) === p.id+ return (+ <button+ key={p.id ?? 'chat-persona'}+ onClick={() => { setGroupPersona(activeConvId, m.name, p.id); setPersonaFor(null) }}+ aria-pressed={picked}+ title={p.id === null ? 'Follow the persona setting of this chat' : undefined}+ className={`w-full flex items-center gap-1.5 px-1.5 py-0.5 rounded text-left transition-colors ${+ picked+ ? 'text-purple-600 dark:text-purple-400'+ : 'text-gray-500 hover:bg-gray-50 dark:hover:bg-white/[0.04] hover:text-gray-700 dark:hover:text-gray-300'+ }`}+ >+ {picked && <div className="w-1 h-1 rounded-full bg-purple-400 shrink-0" />}+ <span className="t-micro truncate">{p.name}</span>+ </button>+ )+ })}+ </div>+ )}+ </div>)})}{groupModels.length === 1 && (@@ -328,7 +382,7 @@ export function PluginsDropdown({)}{groupModels.length > 0 && (<button- onClick={() => setGroupModels(activeConvId, [])}+ onClick={() => { setPersonaFor(null); setGroupModels(activeConvId, []) }}className="w-full px-2 py-1 rounded text-left text-[0.55rem] text-gray-500 hover:bg-gray-50 dark:hover:bg-white/[0.04] hover:text-gray-700 dark:hover:text-gray-300 transition-colors">Turn offdiff --git a/src/components/chat/__tests__/any-file-attaches-as-a-chip.test.tsx b/src/components/chat/__tests__/any-file-attaches-as-a-chip.test.tsxnew file mode 100644index 00000000..0646dbde--- /dev/null+++ b/src/components/chat/__tests__/any-file-attaches-as-a-chip.test.tsx@@ -0,0 +1,174 @@+// @vitest-environment jsdom+/**+ * 3.0.5, applejames on Discord: the clip takes any file, not only images.+ *+ * What the composer owes the user: the file shows up as a chip like the image+ * previews do (name, the type read from its bytes, its size), it can be taken+ * off again, it travels with the send, and a file that is too large is+ * refused in plain English at the head of the transcript, never inside the+ * prompt box.+ *+ * The file is read for real here (jsdom File, WebCrypto), nothing of+ * lib/chat-files.ts is mocked.+ *+ * Run: npx vitest run src/components/chat/__tests__/any-file-attaches-as-a-chip.test.tsx+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { ChatInput } from '../ChatInput'+import { MessageBubble } from '../MessageBubble'+import { useChatStore } from '../../../stores/chatStore'+import { useChatNoticeStore } from '../../../stores/chatNoticeStore'+import { MAX_CHAT_FILE_BYTES, MAX_CHAT_FILES, type ChatFileInput } from '../../../lib/chat-files'++function rom(): Uint8Array<ArrayBuffer> {+ const bytes = new Uint8Array(1024)+ bytes.set([0x4e, 0x45, 0x53, 0x1a, 0x02, 0x01], 0)+ bytes.set([...'SUPER MARIO BROS'].map((c) => c.charCodeAt(0)), 0x40)+ return bytes+}++beforeEach(() => {+ useChatStore.setState({ activeConversationId: 'a' })+ useChatNoticeStore.getState().clear()+})+afterEach(cleanup)++function setup() {+ const send = vi.fn()+ const { container } = render(<ChatInput onSend={send} onStop={() => {}} isGenerating={false} />)+ const input = container.querySelector<HTMLInputElement>('input[type=file]')!+ const attach = (...files: File[]) => fireEvent.change(input, { target: { files } })+ return { send, attach, input }+}++const notices = () => useChatNoticeStore.getState().notices.map((n) => n.text)++describe('the clip takes any file', () => {+ it('no longer limits the picker to images', () => {+ const { input } = setup()+ expect(input.getAttribute('accept')).toBeNull()+ expect(screen.getByTitle('Attach images or files')).toBeTruthy()+ })++ it('a ROM becomes a chip with its name, its detected type and its size', async () => {+ const { attach } = setup()+ attach(new File([rom()], 'mario.nes'))+ const chip = await screen.findByTestId('composer-file-chip')+ expect(chip.textContent).toContain('mario.nes')+ expect(chip.textContent).toContain('NES ROM (iNES), 1.0 KB')+ // Nothing is said about it in or above the prompt box.+ expect(notices()).toEqual([])+ })++ it('sends the typed text and the file, and clears the draft', async () => {+ const { send, attach } = setup()+ attach(new File([rom()], 'mario.nes'))+ await screen.findByTestId('composer-file-chip')+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'what game is this?' } })+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }))++ expect(send).toHaveBeenCalledTimes(1)+ const [text, images, files] = send.mock.calls[0] as [string, unknown, ChatFileInput[]]+ expect(text).toBe('what game is this?')+ expect(images).toBeUndefined()+ expect(files).toHaveLength(1)+ expect(files[0].attachment).toMatchObject({ name: 'mario.nes', size: 1024, kind: 'NES ROM (iNES)' })+ expect(files[0].attachment.sha256).toMatch(/^[0-9a-f]{64}$/)+ expect(files[0].attachment.summary).toContain('SUPER MARIO BROS')+ // The handle to the bytes goes along for the working folder copy.+ expect(files[0].file).toBeInstanceOf(File)+ expect(screen.queryByTestId('composer-file-chip')).toBeNull()+ })++ it('a file alone can be sent, with a placeholder as the text', async () => {+ const { send, attach } = setup()+ expect((screen.getByRole('button', { name: 'Send message' }) as HTMLButtonElement).disabled).toBe(true)+ attach(new File([rom()], 'mario.nes'))+ await screen.findByTestId('composer-file-chip')+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }))+ expect(send.mock.calls[0][0]).toBe('(file)')+ })++ it('the x on the chip takes the file off again', async () => {+ const { send, attach } = setup()+ attach(new File([rom()], 'mario.nes'))+ await screen.findByTestId('composer-file-chip')+ fireEvent.click(screen.getByRole('button', { name: 'Remove mario.nes' }))+ expect(screen.queryByTestId('composer-file-chip')).toBeNull()+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'hello' } })+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }))+ // Without files the handler is called exactly as it always was.+ expect(send).toHaveBeenCalledWith('hello', undefined)+ })++ it('a file over the limit is refused in plain English, above the transcript', async () => {+ const { attach } = setup()+ const huge = new File(['x'], 'disc.iso')+ Object.defineProperty(huge, 'size', { value: MAX_CHAT_FILE_BYTES + 1 })+ attach(huge)+ await waitFor(() => expect(notices()).toEqual(['"disc.iso" is too large. You can attach files up to 64.0 MB.']))+ expect(screen.queryByTestId('composer-file-chip')).toBeNull()+ // The sentence is not drawn inside the composer.+ expect(screen.queryByText(/is too large/)).toBeNull()+ })++ it(`takes ${MAX_CHAT_FILES} files per message and says so for the rest`, async () => {+ const { attach } = setup()+ attach(...[1, 2, 3, 4].map((n) => new File([`file ${n}`], `note-${n}.txt`)))+ await waitFor(() => expect(screen.getAllByTestId('composer-file-chip')).toHaveLength(MAX_CHAT_FILES))+ expect(notices()).toEqual([`You can attach up to ${MAX_CHAT_FILES} files per message.`])+ })++ it('a PDF attaches too, and the line points to the Documents panel', async () => {+ const { attach } = setup()+ attach(new File(['%PDF-1.7\n', new Uint8Array([0xff, 0x00, 0xfe])], 'paper.pdf'))+ const chip = await screen.findByTestId('composer-file-chip')+ expect(chip.textContent).toContain('PDF document')+ expect(notices()).toEqual(['The model only gets a summary of this document. To ask about its text, add it in the Documents panel.'])+ })++ it('the draft with its file belongs to the chat it was started in', async () => {+ const { attach } = setup()+ attach(new File([rom()], 'mario.nes'))+ await screen.findByTestId('composer-file-chip')+ act(() => useChatStore.setState({ activeConversationId: 'b' }))+ expect(screen.queryByTestId('composer-file-chip')).toBeNull()+ act(() => useChatStore.setState({ activeConversationId: 'a' }))+ expect(screen.getByTestId('composer-file-chip').textContent).toContain('mario.nes')+ })++ it('an image still goes the image way, not the file way', async () => {+ const { attach } = setup()+ attach(new File(['not really a png'], 'shot.png', { type: 'image/png' }))+ await act(async () => { await new Promise((r) => setTimeout(r, 20)) })+ expect(screen.queryByTestId('composer-file-chip')).toBeNull()+ })+})++describe('the transcript shows the chip, not the summary', () => {+ const message = {+ id: 'u1',+ role: 'user' as const,+ content: 'what game is this?\n\n[Attached file: mario.nes]\nHEXDUMP-MARKER\n[End of attached file: mario.nes]',+ displayContent: 'what game is this?',+ files: [{ name: 'mario.nes', size: 1024, kind: 'NES ROM (iNES)', sha256: 'ab'.repeat(32), summary: 'HEXDUMP-MARKER' }],+ timestamp: 1,+ }++ it('draws what was typed and a chip per file', () => {+ render(<MessageBubble message={message} />)+ expect(screen.getByText('what game is this?')).toBeTruthy()+ expect(screen.getByTestId('chat-file-chip').textContent).toContain('mario.nes')+ expect(screen.getByTestId('chat-file-chip').textContent).toContain('NES ROM (iNES), 1.0 KB')+ expect(screen.queryByText(/HEXDUMP-MARKER/)).toBeNull()+ // In the transcript the chip has no x: the message is sent.+ expect(screen.queryByRole('button', { name: 'Remove mario.nes' })).toBeNull()+ })++ it('a message that was only a file shows the chip alone', () => {+ render(<MessageBubble message={{ ...message, displayContent: '(file)' }} />)+ expect(screen.getByTestId('chat-file-chip')).toBeTruthy()+ expect(screen.queryByText('(file)')).toBeNull()+ })+})diff --git a/src/components/chat/__tests__/group-participants-pick-their-persona.test.tsx b/src/components/chat/__tests__/group-participants-pick-their-persona.test.tsxnew file mode 100644index 00000000..cc412465--- /dev/null+++ b/src/components/chat/__tests__/group-participants-pick-their-persona.test.tsx@@ -0,0 +1,139 @@+// @vitest-environment jsdom+/**+ * 3.0.5, samvenice on Discord: in the group menu each participant gets its own+ * persona, picked next to its name and stored on the conversation. The default+ * is what a group has always done: follow the persona setting of the chat.+ *+ * The picker lives in the Plugins menu, at the participant list. Nothing of+ * it stands in or above the prompt field.+ *+ * Run: npx vitest run src/components/chat/__tests__/group-participants-pick-their-persona.test.tsx+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'+import { PluginsDropdown } from '../PluginsDropdown'+import { MessageList } from '../MessageList'+import { useChatStore } from '../../../stores/chatStore'+import { useModelStore } from '../../../stores/modelStore'+import { useSettingsStore } from '../../../stores/settingsStore'+import { BUILT_IN_PERSONAS, DEFAULT_SETTINGS } from '../../../lib/constants'+import type { AIModel } from '../../../types/models'++const A = 'openai::model-a'+const B = 'openai::model-b'+const C = 'openai::model-c'+const SHERLOCK = { id: 'sherlock', name: 'Sherlock', icon: 'Search', systemPrompt: 'You are Sherlock Holmes.', isBuiltIn: false }+const WATSON = { id: 'watson', name: 'Watson', icon: 'User', systemPrompt: 'You are Doctor Watson.', isBuiltIn: false }++const textModel = (name: string): AIModel => ({ name, type: 'text' } as AIModel)++let convId = ''+beforeEach(() => {+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useModelStore.setState({ models: [textModel(A), textModel(B), textModel(C)], activeModel: A })+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS }, personas: [...BUILT_IN_PERSONAS, SHERLOCK, WATSON] })+ convId = useChatStore.getState().createConversation(A, '')+ useChatStore.getState().setActiveConversation(convId)+})+afterEach(cleanup)++const conversation = () => useChatStore.getState().conversations.find((c) => c.id === convId)!+const participant = (model: string) =>+ screen.getAllByTestId('group-participant').find((row) => row.getAttribute('data-model') === model)!++function openGroupMenu() {+ render(<PluginsDropdown openUpward />)+ fireEvent.click(screen.getByRole('button', { name: /Plugins/ }))+ fireEvent.click(screen.getByRole('button', { name: /Group chat/ }))+}++describe('the group menu', () => {+ it('a model that is not in the group has no persona control', () => {+ openGroupMenu()+ expect(screen.getAllByTestId('group-participant')).toHaveLength(3)+ expect(screen.queryAllByTestId('group-persona-trigger')).toHaveLength(0)+ })++ it('a participant gets one, and it starts on the chat persona', () => {+ useChatStore.getState().setGroupModels(convId, [A, B])+ openGroupMenu()+ expect(screen.getAllByTestId('group-persona-trigger')).toHaveLength(2)+ expect(within(participant(A)).getByTestId('group-persona-trigger').textContent).toBe('Chat persona')+ expect(within(participant(C)).queryByTestId('group-persona-trigger')).toBeNull()+ })++ it('picking a persona for one participant stores it for THAT model in THIS chat', () => {+ useChatStore.getState().setGroupModels(convId, [A, B])+ openGroupMenu()+ fireEvent.click(within(participant(A)).getByTestId('group-persona-trigger'))+ const list = within(participant(A)).getByTestId('group-persona-list')+ // Every existing persona is on offer, plus the way back.+ expect(within(list).getAllByRole('button').map((b) => b.textContent)).toEqual([+ 'Chat persona',+ ...BUILT_IN_PERSONAS.map((p) => p.name),+ 'Sherlock',+ 'Watson',+ ])+ fireEvent.click(within(list).getByRole('button', { name: 'Sherlock' }))++ expect(conversation().groupPersonas).toEqual({ [A]: 'sherlock' })+ expect(within(participant(A)).getByTestId('group-persona-trigger').textContent).toBe('Sherlock')+ expect(within(participant(B)).getByTestId('group-persona-trigger').textContent).toBe('Chat persona')+ // The list closes after the pick.+ expect(screen.queryByTestId('group-persona-list')).toBeNull()+ })++ it('two participants hold two different personas', () => {+ useChatStore.getState().setGroupModels(convId, [A, B])+ openGroupMenu()+ fireEvent.click(within(participant(A)).getByTestId('group-persona-trigger'))+ fireEvent.click(within(participant(A)).getByRole('button', { name: 'Sherlock' }))+ fireEvent.click(within(participant(B)).getByTestId('group-persona-trigger'))+ fireEvent.click(within(participant(B)).getByRole('button', { name: 'Watson' }))+ expect(conversation().groupPersonas).toEqual({ [A]: 'sherlock', [B]: 'watson' })+ })++ it('"Chat persona" takes the pick back', () => {+ useChatStore.getState().setGroupModels(convId, [A, B])+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ openGroupMenu()+ fireEvent.click(within(participant(A)).getByTestId('group-persona-trigger'))+ const list = within(participant(A)).getByTestId('group-persona-list')+ expect(within(list).getByRole('button', { name: 'Sherlock' }).getAttribute('aria-pressed')).toBe('true')+ fireEvent.click(within(list).getByRole('button', { name: 'Chat persona' }))+ expect('groupPersonas' in conversation()).toBe(false)+ })++ it('clicking the model name still takes it out of the group, and its pick with it', () => {+ useChatStore.getState().setGroupModels(convId, [A, B])+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ openGroupMenu()+ fireEvent.click(within(participant(A)).getByRole('button', { name: 'model-a' }))+ expect(conversation().groupModels).toEqual([B])+ expect('groupPersonas' in conversation()).toBe(false)+ })++ it('NEGATIVE CONTROL: picking a participant persona does not touch the chat persona or the global one', () => {+ useChatStore.getState().setGroupModels(convId, [A, B])+ const before = useSettingsStore.getState().activePersonaId+ const chatSwitch = conversation().personaEnabled+ openGroupMenu()+ fireEvent.click(within(participant(A)).getByTestId('group-persona-trigger'))+ fireEvent.click(within(participant(A)).getByRole('button', { name: 'Sherlock' }))+ expect(useSettingsStore.getState().activePersonaId).toBe(before)+ expect(conversation().personaEnabled).toBe(chatSwitch)+ expect(conversation().systemPrompt).toBe('')+ })+})++describe('the transcript names who spoke as whom', () => {+ it('a participant with its own persona is labelled with it, the other only with its model', () => {+ useChatStore.getState().setGroupModels(convId, [A, B])+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ useChatStore.getState().addMessage(convId, { id: 'u', role: 'user', content: 'who did it?', timestamp: 1 })+ useChatStore.getState().addMessage(convId, { id: 'a', role: 'assistant', content: 'The butler.', modelId: A, timestamp: 2 })+ useChatStore.getState().addMessage(convId, { id: 'b', role: 'assistant', content: 'Surely not.', modelId: B, timestamp: 3 })+ render(<MessageList isGenerating={false} />)+ expect(screen.getAllByTestId('answered-by').map((el) => el.textContent)).toEqual(['Sherlock · model-a', 'model-b'])+ })+})diff --git a/src/components/chat/__tests__/nichts-im-promptfenster.test.tsx b/src/components/chat/__tests__/nichts-im-promptfenster.test.tsxindex a96b9a2c..b44769a2 100644--- a/src/components/chat/__tests__/nichts-im-promptfenster.test.tsx+++ b/src/components/chat/__tests__/nichts-im-promptfenster.test.tsx@@ -63,7 +63,7 @@ describe('der Composer haengt keine Hinweis-Bauteile mehr ein', () => {// weiterhin los, nur zeichnet ihn eine Etage hoeher.const jsx = src.slice(src.indexOf('return ('))expect(jsx).not.toContain('Waiting for the local model')- expect(jsx).not.toContain('The clip attaches images')+ expect(jsx).not.toContain('The model only gets a summary')expect(jsx).not.toContain("This model can't read images")})@@ -129,13 +129,13 @@ describe('ChatNotices: der neue Platz, oben im Verlauf', () => {expect(screen.queryByTestId('chat-notices')).toBeNull()})- it('zeigt die Zeile des fehlgegangenen Anhangs, und das x nimmt sie weg', () => {+ it('zeigt die Zeile ueber ein angehaengtes Dokument, und das x nimmt sie weg', () => {useChatNoticeStore.getState().show(- 'attachment-is-not-an-image',- 'The clip attaches images. To ask about a PDF, Word, or text file, add it in the Documents panel.',+ 'document-belongs-in-docs',+ 'The model only gets a summary of this document. To ask about its text, add it in the Documents panel.',)render(<ChatNotices />)- expect(screen.getByTestId('chat-notices').textContent).toContain('The clip attaches images')+ expect(screen.getByTestId('chat-notices').textContent).toContain('The model only gets a summary of this document')fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }))expect(screen.queryByTestId('chat-notices')).toBeNull()@@ -144,7 +144,7 @@ describe('ChatNotices: der neue Platz, oben im Verlauf', () => {it('bietet den Weg in die Dokumentenablage an, wenn es einen gibt', () => {let geoeffnet = 0- useChatNoticeStore.getState().show('attachment-is-not-an-image', 'The clip attaches images.')+ useChatNoticeStore.getState().show('document-belongs-in-docs', 'The model only gets a summary of this document.')render(<ChatNotices onAttachDocs={() => { geoeffnet += 1 }} />)fireEvent.click(screen.getByRole('button', { name: 'Open Documents' }))expect(geoeffnet).toBe(1)@@ -153,10 +153,10 @@ describe('ChatNotices: der neue Platz, oben im Verlauf', () => {})it('GEGENPROBE: ohne den Weg dorthin bleibt der Satz wahr und der Knopf weg', () => {- useChatNoticeStore.getState().show('attachment-is-not-an-image', 'The clip attaches images.')+ useChatNoticeStore.getState().show('document-belongs-in-docs', 'The model only gets a summary of this document.')render(<ChatNotices />)expect(screen.queryByRole('button', { name: 'Open Documents' })).toBeNull()- expect(screen.getByTestId('chat-notices').textContent).toContain('The clip attaches images')+ expect(screen.getByTestId('chat-notices').textContent).toContain('The model only gets a summary of this document')})it('zeigt die Zeile des blinden Modells', () => {diff --git a/src/hooks/__tests__/agent-files-land-in-the-working-folder.test.ts b/src/hooks/__tests__/agent-files-land-in-the-working-folder.test.tsnew file mode 100644index 00000000..292957d1--- /dev/null+++ b/src/hooks/__tests__/agent-files-land-in-the-working-folder.test.ts@@ -0,0 +1,199 @@+/**+ * @vitest-environment jsdom+ *+ * 3.0.5: in Agent mode an attached file is copied into the chat's working+ * folder before the turn starts, so the file and shell tools can work on the+ * real bytes, and the message tells the model where it is. In Chat Tools mode+ * (plain chat that reaches for a tool) nothing is written to disk.+ *+ * Driven through the real `useAgentChat().sendAgentMessage`; only the network+ * is replaced. Outside Tauri the fs commands are HTTP calls to the dev+ * server, so the upload shows up here as requests to /local-api/fs-write-bytes.+ *+ * Run: npx vitest run src/hooks/__tests__/agent-files-land-in-the-working-folder.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { renderHook, act } from '@testing-library/react'++vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))+vi.mock('../../api/rag', () => ({+ retrieveContext: async () => ({ context: { chunks: [], query: '', documentIds: [] }, scoredChunks: [] }),+ generateEmbeddings: async () => [[0.1, 0.2]],+}))+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))+vi.mock('../useMemory', () => ({+ useMemory: () => ({ extractAndSave: async () => {} }),+ extractMemoriesFromPair: async () => {},+}))++import { useAgentChat } from '../useAgentChat'+import { useChatStore } from '../../stores/chatStore'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useProviderStore } from '../../stores/providerStore'+import { useAgentModeStore } from '../../stores/agentModeStore'+import { useAgentTaskStore } from '../../stores/agentTaskStore'+import { useAgentLoopStore } from '../../stores/agentLoopStore'+import { useGenerationStore } from '../../stores/generationStore'+import { useTodoStore } from '../../stores/todoStore'+import { useToolAuditStore } from '../../stores/toolAuditStore'+import { useChatNoticeStore } from '../../stores/chatNoticeStore'+import { DEFAULT_SETTINGS } from '../../lib/constants'+import { __resetRunStopsForTests } from '../../lib/run-stop'+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'+import { CHAT_TOOLS } from '../../lib/chat-tool-intent'+import type { ChatFileInput } from '../../lib/chat-files'++const MODEL = 'lu-cloud::zai-org/GLM-5.3'+const BYTES = new Uint8Array([0x4e, 0x45, 0x53, 0x1a, 0x00, 0xff, 0x80, 0x0a])++function attached(): ChatFileInput {+ return {+ attachment: {+ name: 'mario.nes',+ size: BYTES.length,+ kind: 'NES ROM (iNES)',+ sha256: 'ab'.repeat(32),+ summary: 'This is a binary file. SUMMARY-MARKER',+ },+ file: new File([BYTES], 'mario.nes'),+ }+}++const answer = () =>+ new Response(`data: ${JSON.stringify({ choices: [{ delta: { content: 'It is an NES ROM.' } }] })}\n\ndata: [DONE]\n\n`, {+ status: 200, headers: { 'content-type': 'text/event-stream' },+ })++interface Upload { path: string; base64: string; offset: number; last: boolean; chatId?: string; workingDirectory?: string }+let uploads: Upload[] = []+let modelRequests: string[] = []+/** How the fake backend answers an upload. */+let uploadAnswer: () => Response = () => new Response(JSON.stringify({ status: 'saved' }), { status: 200 })++function seed(): string {+ const convId = useChatStore.getState().createConversation(MODEL, '')+ useChatStore.getState().setActiveConversation(convId)+ useAgentModeStore.getState().setAgentModeActive(convId, true)+ return convId+}++beforeEach(() => {+ uploads = []+ modelRequests = []+ uploadAnswer = () => new Response(JSON.stringify({ status: 'saved' }), { status: 200 })+ registerBuiltinTools(toolRegistry)+ __resetRunStopsForTests()+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useAgentTaskStore.setState({ byConv: {} })+ useAgentLoopStore.setState({ loops: {} })+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useAgentModeStore.setState({ agentModeActive: {}, workspaces: {}, workspaceSlugs: {} })+ useTodoStore.setState({ byConversation: {}, updatedAt: {} })+ useToolAuditStore.setState({ entries: {} })+ useChatNoticeStore.getState().clear()+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud', cavemanMode: 'off' } })+ useProviderStore.setState((s) => ({+ providers: { ...s.providers, 'lu-cloud': { ...s.providers['lu-cloud'], enabled: true } },+ }))+ useModelStore.setState({ models: [], activeModel: MODEL })+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input)+ if (url.includes('/local-api/fs-write-bytes')) {+ uploads.push(JSON.parse(String(init?.body)))+ return uploadAnswer()+ }+ if (url.includes('/chat/completions')) {+ modelRequests.push(String(init?.body))+ return answer()+ }+ return new Response('{}', { status: 200 })+ })+})+afterEach(() => vi.restoreAllMocks())++const userMessage = (convId: string) =>+ useChatStore.getState().conversations.find((c) => c.id === convId)!.messages.find((m) => m.role === 'user')!++describe('Agent mode: the file is in the working folder before the model is asked', () => {+ it('uploads the bytes into this chat\'s folder and names the path to the model', async () => {+ const convId = seed()+ const { result } = renderHook(() => useAgentChat())+ await act(async () => { await result.current.sendAgentMessage('what is this file?', undefined, { files: [attached()] }) })++ expect(uploads).toHaveLength(1)+ expect(uploads[0]).toMatchObject({ path: 'mario.nes', offset: 0, last: true })+ // The same folder the file tools of this run use: the pinned chat slug.+ expect(uploads[0].chatId).toBe(useAgentModeStore.getState().workspaceSlugs[convId])+ expect(uploads[0].chatId).toBeTruthy()+ expect([...atob(uploads[0].base64)].map((c) => c.charCodeAt(0))).toEqual([...BYTES])++ expect(modelRequests.length).toBeGreaterThan(0)+ expect(modelRequests[0]).toContain('[Attached file: mario.nes]')+ expect(modelRequests[0]).toContain('Path in your working folder: mario.nes')+ expect(modelRequests[0]).toContain('SUMMARY-MARKER')++ const stored = userMessage(convId)+ expect(stored.displayContent).toBe('what is this file?')+ expect(stored.files).toEqual([{ ...attached().attachment, workspacePath: 'mario.nes' }])+ expect(useChatNoticeStore.getState().notices).toEqual([])+ })++ it('a picked project folder is where the file goes', async () => {+ const convId = seed()+ useAgentModeStore.setState({ workspaces: { [convId]: { kind: 'folder', path: '/home/me/project' } } })+ const { result } = renderHook(() => useAgentChat())+ await act(async () => { await result.current.sendAgentMessage('look at it', undefined, { files: [attached()] }) })+ expect(uploads[0].workingDirectory).toBe('/home/me/project')+ })++ it('a name that is taken in the folder is never overwritten', async () => {+ const convId = seed()+ let first = true+ uploadAnswer = () => {+ if (!first) return new Response(JSON.stringify({ status: 'saved' }), { status: 200 })+ first = false+ return new Response(JSON.stringify({ error: 'File already exists: /ws/mario.nes' }), { status: 400 })+ }+ const { result } = renderHook(() => useAgentChat())+ await act(async () => { await result.current.sendAgentMessage('look at it', undefined, { files: [attached()] }) })+ expect(uploads.map((u) => u.path)).toEqual(['mario.nes', 'mario (1).nes'])+ expect(userMessage(convId).files![0].workspacePath).toBe('mario (1).nes')+ expect(modelRequests[0]).toContain('Path in your working folder: mario (1).nes')+ })++ it('a copy that fails does not stop the turn, and nobody is told the file is there', async () => {+ const convId = seed()+ uploadAnswer = () => new Response(JSON.stringify({ error: 'Write error: No space left on device' }), { status: 400 })+ const { result } = renderHook(() => useAgentChat())+ await act(async () => { await result.current.sendAgentMessage('look at it', undefined, { files: [attached()] }) })++ expect(modelRequests.length).toBeGreaterThan(0)+ expect(modelRequests[0]).toContain('The file could not be copied into your working folder. Only this summary is available.')+ expect(modelRequests[0]).not.toContain('Path in your working folder')+ expect(userMessage(convId).files![0].workspacePath).toBeUndefined()+ expect(useChatNoticeStore.getState().notices.map((n) => n.text)).toEqual([+ '"mario.nes" could not be copied into the working folder. The model only gets a summary of it.',+ ])+ })+})++describe('Chat Tools mode writes nothing to disk', () => {+ it('the model gets the summary and no path', async () => {+ const convId = seed()+ useAgentModeStore.getState().setAgentModeActive(convId, false)+ const { result } = renderHook(() => useAgentChat())+ await act(async () => {+ await result.current.sendAgentMessage('search the web for this rom', undefined, {+ curatedTools: CHAT_TOOLS,+ chatToolsMode: true,+ files: [attached()],+ })+ })+ expect(uploads).toEqual([])+ expect(modelRequests[0]).toContain('[Attached file: mario.nes]')+ expect(modelRequests[0]).toContain('The file itself is not available to you in this chat.')+ expect(userMessage(convId).files).toEqual([attached().attachment])+ })+})diff --git a/src/hooks/__tests__/chat-files-reach-the-model.test.ts b/src/hooks/__tests__/chat-files-reach-the-model.test.tsnew file mode 100644index 00000000..298032d5--- /dev/null+++ b/src/hooks/__tests__/chat-files-reach-the-model.test.ts@@ -0,0 +1,194 @@+/**+ * @vitest-environment jsdom+ *+ * 3.0.5, applejames on Discord: attach any file in the chat. A model cannot+ * read bytes, so what has to arrive in the request is the description of the+ * file, and what has to be kept in the chat is that description and nothing+ * of the file itself.+ *+ * Driven through the real `useChat().sendMessage`, with only the network+ * replaced, so this is the payload a local model and a cloud model both get:+ * the description is part of the user message, not of any provider.+ *+ * Run: npx vitest run src/hooks/__tests__/chat-files-reach-the-model.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { renderHook, act } from '@testing-library/react'++vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))+vi.mock('../useMemory', () => ({+ useMemory: () => ({ extractAndSave: async () => {} }),+ extractMemoriesFromPair: async () => {},+}))+vi.mock('../../lib/run-lane-of-model', () => ({+ laneOf: () => 'cloud',+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),+}))++import { useChat } from '../useChat'+import { useChatStore } from '../../stores/chatStore'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useProviderStore } from '../../stores/providerStore'+import { useGenerationStore } from '../../stores/generationStore'+import { __resetRunLanesForTests } from '../../lib/run-lanes'+import { DEFAULT_SETTINGS } from '../../lib/constants'+import { describeFileBytes, type ChatFileInput } from '../../lib/chat-files'++const MODEL = 'openai::some-chat-model'++/** A small fake Game Boy Advance cartridge. */+function rom(): Uint8Array {+ const bytes = new Uint8Array(2048)+ for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 37 + 11) & 0xff+ bytes.set([0x2e, 0x00, 0x00, 0xea, 0x24, 0xff, 0xae, 0x51, 0x69, 0x9a, 0xa2, 0x21], 0)+ bytes.set([0x00, ...[...'POKEMON EMER'].map((c) => c.charCodeAt(0)), 0x00], 0xa0)+ return bytes+}++function attachedRom(): ChatFileInput {+ const bytes = rom()+ return {+ attachment: {+ name: 'emerald.gba',+ size: bytes.length,+ sha256: 'c0ffee'.padEnd(64, '0'),+ ...describeFileBytes(bytes, 'emerald.gba'),+ },+ }+}++function sse(text: string): Response {+ const body = `data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\ndata: [DONE]\n\n`+ return new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } })+}++interface WireMessage { role: string; content: string }+let requests: WireMessage[][] = []++beforeEach(() => {+ requests = []+ __resetRunLanesForTests()+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useModelStore.setState({ models: [], activeModel: MODEL })+ useSettingsStore.setState({+ settings: { ...DEFAULT_SETTINGS, appMode: 'local', cavemanMode: 'off', chatToolsEnabled: false },+ })+ useProviderStore.setState((s) => ({+ providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },+ }))+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ if (!String(input).includes('/chat/completions')) return new Response('{}', { status: 200 })+ requests.push(JSON.parse(String((init as RequestInit).body)).messages)+ return sse('It looks like a Pokemon Emerald cartridge.')+ })+})+afterEach(() => vi.restoreAllMocks())++function openChat(): string {+ const convId = useChatStore.getState().createConversation(MODEL, '')+ useChatStore.getState().setActiveConversation(convId)+ return convId+}++const conversation = (id: string) => useChatStore.getState().conversations.find((c) => c.id === id)!+const text = (content: unknown): string => typeof content === 'string' ? content : JSON.stringify(content)++describe('a file attached in plain chat', () => {+ it('reaches the model as name, type, hash, hex dump and strings', async () => {+ const convId = openChat()+ const { result } = renderHook(() => useChat())+ await act(async () => { await result.current.sendMessage('what game is this?', undefined, [attachedRom()]) })++ expect(requests).toHaveLength(1)+ const user = requests[0].filter((m) => m.role === 'user')+ expect(user).toHaveLength(1)+ const sent = text(user[0].content)+ expect(sent.startsWith('what game is this?\n\n[Attached file: emerald.gba]')).toBe(true)+ expect(sent).toContain('Type: Game Boy Advance ROM')+ expect(sent).toContain('Size: 2.0 KB (2048 bytes)')+ expect(sent).toContain(`SHA-256: ${'c0ffee'.padEnd(64, '0')}`)+ expect(sent).toContain('00000000 2e 00 00 ea 24 ff ae 51 69 9a a2 21')+ expect(sent).toContain('POKEMON EMER')+ // Plain chat has no file tools, and the block does not pretend it has.+ expect(sent).toContain('The file itself is not available to you in this chat.')+ expect(sent).not.toContain('working folder')+ expect(conversation(convId).messages.at(-1)!.content).toContain('Pokemon Emerald')+ })++ it('keeps the typed text for the bubble and the description for the chip, and nothing of the file', async () => {+ const convId = openChat()+ const { result } = renderHook(() => useChat())+ await act(async () => { await result.current.sendMessage('what game is this?', undefined, [attachedRom()]) })++ const stored = conversation(convId).messages.find((m) => m.role === 'user')!+ expect(stored.displayContent).toBe('what game is this?')+ expect(stored.files).toHaveLength(1)+ expect(Object.keys(stored.files![0]).sort()).toEqual(['kind', 'name', 'sha256', 'size', 'summary'])+ // The whole stored message stays a few kilobytes for a file of any size.+ expect(JSON.stringify(stored).length).toBeLessThan(12_000)+ // And the chat is named after the question, not after a hex dump.+ expect(conversation(convId).title).toBe('what game is this?')+ })++ it('a chat started with nothing but a file is named after the file', async () => {+ const convId = openChat()+ const { result } = renderHook(() => useChat())+ await act(async () => { await result.current.sendMessage('(file)', undefined, [attachedRom()]) })+ expect(conversation(convId).title).toBe('emerald.gba')+ })++ it('regenerate asks the same question with the same file, once', async () => {+ const convId = openChat()+ const { result } = renderHook(() => useChat())+ await act(async () => { await result.current.sendMessage('what game is this?', undefined, [attachedRom()]) })+ const answerId = conversation(convId).messages.at(-1)!.id+ await act(async () => {+ result.current.regenerateMessage(convId, answerId)+ await new Promise((r) => setTimeout(r, 50))+ })++ expect(requests).toHaveLength(2)+ const again = text(requests[1].filter((m) => m.role === 'user')[0].content)+ expect(again).toBe(text(requests[0].filter((m) => m.role === 'user')[0].content))+ // One block, not two: the resend starts from what was typed.+ expect(again.match(/\[Attached file: emerald\.gba\]/g)).toHaveLength(1)+ const users = conversation(convId).messages.filter((m) => m.role === 'user')+ expect(users).toHaveLength(1)+ expect(users[0].displayContent).toBe('what game is this?')+ expect(users[0].files).toHaveLength(1)+ })++ it('NEGATIVE CONTROL: a message without files is stored and sent exactly as before', async () => {+ const convId = openChat()+ const { result } = renderHook(() => useChat())+ await act(async () => { await result.current.sendMessage('plain question') })+ const stored = conversation(convId).messages.find((m) => m.role === 'user')!+ expect(stored.content).toBe('plain question')+ expect('displayContent' in stored).toBe(false)+ expect('files' in stored).toBe(false)+ expect(text(requests[0].filter((m) => m.role === 'user')[0].content)).toBe('plain question')+ })+})++describe('a file attached in a group chat', () => {+ it('reaches every speaker inside the one user line they share', async () => {+ const convId = openChat()+ useChatStore.getState().setGroupModels(convId, ['openai::model-a', 'openai::model-b'])+ const { result } = renderHook(() => useChat())+ await act(async () => { await result.current.sendMessage('what game is this?', undefined, [attachedRom()]) })++ expect(requests).toHaveLength(2)+ for (const request of requests) {+ const first = text(request.filter((m) => m.role === 'user')[0].content)+ expect(first).toContain('[Attached file: emerald.gba]')+ expect(first).toContain('POKEMON EMER')+ }+ const users = conversation(convId).messages.filter((m) => m.role === 'user')+ expect(users).toHaveLength(1)+ expect(users[0].files).toHaveLength(1)+ })+})diff --git a/src/hooks/__tests__/code-files-land-in-the-working-folder.test.ts b/src/hooks/__tests__/code-files-land-in-the-working-folder.test.tsnew file mode 100644index 00000000..f8924001--- /dev/null+++ b/src/hooks/__tests__/code-files-land-in-the-working-folder.test.ts@@ -0,0 +1,141 @@+/**+ * @vitest-environment jsdom+ *+ * 3.0.5: a file attached in the Code tab is copied into the folder the coding+ * run works in, and the instruction tells the model its path. The folder is+ * the one the run's jail is pinned to, so the file tools can open the file+ * the message names.+ *+ * Driven through the real `useCodex().sendInstruction`; only the network is+ * replaced. Outside Tauri the fs commands are HTTP calls to the dev server.+ *+ * Run: npx vitest run src/hooks/__tests__/code-files-land-in-the-working-folder.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { renderHook, act } from '@testing-library/react'++vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))+vi.mock('../../api/rag', () => ({+ retrieveContext: async () => ({ context: { chunks: [], query: '', documentIds: [] }, scoredChunks: [] }),+ generateEmbeddings: async () => [[0.1, 0.2]],+}))+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))+vi.mock('../useMemory', () => ({+ useMemory: () => ({ extractAndSave: async () => {} }),+ extractMemoriesFromPair: async () => {},+}))++import { useCodex } from '../useCodex'+import { useChatStore } from '../../stores/chatStore'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useProviderStore } from '../../stores/providerStore'+import { useAgentModeStore } from '../../stores/agentModeStore'+import { useCodexStore } from '../../stores/codexStore'+import { useGenerationStore } from '../../stores/generationStore'+import { useChatNoticeStore } from '../../stores/chatNoticeStore'+import { DEFAULT_SETTINGS } from '../../lib/constants'+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'+import type { ChatFileInput } from '../../lib/chat-files'++const MODEL = 'lu-cloud::zai-org/GLM-5.3'+const BYTES = new Uint8Array([0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x00, 0xff])++function attached(): ChatFileInput {+ return {+ attachment: {+ name: 'firmware.bin',+ size: BYTES.length,+ kind: 'ELF executable',+ sha256: 'cd'.repeat(32),+ summary: 'This is a binary file. SUMMARY-MARKER',+ },+ file: new File([BYTES], 'firmware.bin'),+ }+}++interface Upload { path: string; base64: string; offset: number; last: boolean; chatId?: string; workingDirectory?: string }+let uploads: Upload[] = []+let modelRequests: string[] = []++beforeEach(() => {+ uploads = []+ modelRequests = []+ registerBuiltinTools(toolRegistry)+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useCodexStore.setState({ sendsInFlight: 0, threads: {}, workingDirectory: '' })+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useAgentModeStore.setState({ agentModeActive: {}, workspaces: {}, workspaceSlugs: {} })+ useChatNoticeStore.getState().clear()+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS, appMode: 'cloud', cavemanMode: 'off' } })+ useProviderStore.setState((s) => ({+ providers: { ...s.providers, 'lu-cloud': { ...s.providers['lu-cloud'], enabled: true } },+ }))+ useModelStore.setState({ models: [], activeModel: MODEL })+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input)+ if (url.includes('/local-api/fs-write-bytes')) {+ uploads.push(JSON.parse(String(init?.body)))+ return new Response(JSON.stringify({ status: 'saved' }), { status: 200 })+ }+ if (url.includes('/chat/completions')) {+ modelRequests.push(String(init?.body))+ return new Response(`data: ${JSON.stringify({ choices: [{ delta: { content: 'It is an ELF binary.' } }] })}\n\ndata: [DONE]\n\n`, {+ status: 200, headers: { 'content-type': 'text/event-stream' },+ })+ }+ return new Response('{}', { status: 200 })+ })+})+afterEach(() => vi.restoreAllMocks())++function openCodeChat(): string {+ const convId = useChatStore.getState().createConversation(MODEL, '', 'codex')+ useChatStore.getState().setActiveConversation(convId)+ return convId+}++const userMessage = (convId: string) =>+ useChatStore.getState().conversations.find((c) => c.id === convId)!.messages.find((m) => m.role === 'user' && !m.hidden)!++describe('Code: the attached file is in the working folder of the run', () => {+ it('uploads it into the chat sandbox and names the path in the instruction', async () => {+ const convId = openCodeChat()+ const { result } = renderHook(() => useCodex())+ await act(async () => { await result.current.sendInstruction('what does this binary do?', { files: [attached()] }) })++ expect(uploads).toHaveLength(1)+ expect(uploads[0]).toMatchObject({ path: 'firmware.bin', offset: 0, last: true })+ expect(uploads[0].chatId).toBe(useAgentModeStore.getState().workspaceSlugs[convId])+ expect(uploads[0].workingDirectory).toBeUndefined()+ expect([...atob(uploads[0].base64)].map((c) => c.charCodeAt(0))).toEqual([...BYTES])++ expect(modelRequests.length).toBeGreaterThan(0)+ expect(modelRequests[0]).toContain('[Attached file: firmware.bin]')+ expect(modelRequests[0]).toContain('Path in your working folder: firmware.bin')++ const stored = userMessage(convId)+ expect(stored.displayContent).toBe('what does this binary do?')+ expect(stored.files).toEqual([{ ...attached().attachment, workspacePath: 'firmware.bin' }])+ })++ it('with a project folder picked in the Code tab, that folder gets the file', async () => {+ openCodeChat()+ useCodexStore.setState({ workingDirectory: '/home/me/project' })+ const { result } = renderHook(() => useCodex())+ await act(async () => { await result.current.sendInstruction('look at it', { files: [attached()] }) })+ expect(uploads[0].workingDirectory).toBe('/home/me/project')+ })++ it('NEGATIVE CONTROL: an instruction without files uploads nothing and is stored as typed', async () => {+ const convId = openCodeChat()+ const { result } = renderHook(() => useCodex())+ await act(async () => { await result.current.sendInstruction('list the files') })+ expect(uploads).toEqual([])+ const stored = userMessage(convId)+ expect(stored.content).toBe('list the files')+ expect('files' in stored).toBe(false)+ expect('displayContent' in stored).toBe(false)+ })+})diff --git a/src/hooks/__tests__/group-speakers-keep-their-own-persona.test.ts b/src/hooks/__tests__/group-speakers-keep-their-own-persona.test.tsnew file mode 100644index 00000000..a1ff9f01--- /dev/null+++ b/src/hooks/__tests__/group-speakers-keep-their-own-persona.test.ts@@ -0,0 +1,232 @@+/**+ * @vitest-environment jsdom+ *+ * 3.0.5, samvenice on Discord: in a group chat every model answered under the+ * one persona of the chat. Two models were both told they are the same+ * character, and each took over the other's role. Now each participant can+ * have its own persona, stored on the conversation.+ *+ * Driven through the real `useChat().sendMessage` with only the network+ * replaced: what is asserted is the request each model really receives.+ *+ * Run: npx vitest run src/hooks/__tests__/group-speakers-keep-their-own-persona.test.ts+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { renderHook, act } from '@testing-library/react'++vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))+vi.mock('../useMemory', () => ({+ useMemory: () => ({ extractAndSave: async () => {} }),+ extractMemoriesFromPair: async () => {},+}))+vi.mock('../../lib/run-lane-of-model', () => ({+ laneOf: () => 'cloud',+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),+}))++import { useChat } from '../useChat'+import { useChatStore } from '../../stores/chatStore'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import { useProviderStore } from '../../stores/providerStore'+import { useGenerationStore } from '../../stores/generationStore'+import { __resetRunLanesForTests } from '../../lib/run-lanes'+import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../../lib/constants'+import { CHAT_BASE_ROLE, HOUSE_RULES } from '../../lib/system-prompt'++const A = 'openai::model-a'+const B = 'openai::model-b'+const SHERLOCK = { id: 'sherlock', name: 'Sherlock', icon: 'Search', systemPrompt: 'You are Sherlock Holmes, the detective.', isBuiltIn: false }+const WATSON = { id: 'watson', name: 'Watson', icon: 'User', systemPrompt: 'You are Doctor Watson, the physician.', isBuiltIn: false }++interface WireMessage { role: string; content: string }+interface Request { model: string; messages: WireMessage[] }+let requests: Request[] = []+/** What each model answers, by the model name in the request. */+let answers: Record<string, string> = {}++beforeEach(() => {+ requests = []+ answers = { 'model-a': 'The butler did it.', 'model-b': 'I examined the body.' }+ __resetRunLanesForTests()+ useChatStore.setState({ conversations: [], activeConversationId: null })+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })+ useModelStore.setState({ models: [], activeModel: A })+ useSettingsStore.setState({+ settings: { ...DEFAULT_SETTINGS, appMode: 'local', cavemanMode: 'off', chatToolsEnabled: false },+ personas: [...BUILT_IN_PERSONAS, SHERLOCK, WATSON],+ })+ useProviderStore.setState((s) => ({+ providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },+ }))+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ if (!String(input).includes('/chat/completions')) return new Response('{}', { status: 200 })+ const body = JSON.parse(String((init as RequestInit).body)) as Request+ requests.push(body)+ const text = answers[body.model] ?? 'ok'+ return new Response(`data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\ndata: [DONE]\n\n`, {+ status: 200, headers: { 'content-type': 'text/event-stream' },+ })+ })+})+afterEach(() => vi.restoreAllMocks())++function openGroup(systemPrompt = ''): string {+ const convId = useChatStore.getState().createConversation(A, systemPrompt)+ useChatStore.getState().setActiveConversation(convId)+ useChatStore.getState().setGroupModels(convId, [A, B])+ return convId+}++const system = (r: Request) => r.messages.find((m) => m.role === 'system')!.content+const turns = (r: Request) => r.messages.filter((m) => m.role !== 'system').map((m) => [m.role, m.content])+const conversation = (id: string) => useChatStore.getState().conversations.find((c) => c.id === id)!++async function round(text: string) {+ const { result } = renderHook(() => useChat())+ await act(async () => { await result.current.sendMessage(text) })+}++describe('each participant speaks as its own persona', () => {+ it('two models, two personas: each gets its own system prompt and the other by name', async () => {+ const convId = openGroup()+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ useChatStore.getState().setGroupPersona(convId, B, 'watson')+ await round('who did it?')++ expect(requests.map((r) => r.model)).toEqual(['model-a', 'model-b'])+ const [first, second] = requests++ expect(system(first).startsWith('You are Sherlock Holmes, the detective.')).toBe(true)+ expect(system(first)).toContain('you are "Sherlock" and only "Sherlock"')+ expect(system(first)).toContain('The other participants are "Watson".')+ expect(system(first)).not.toContain('Doctor Watson, the physician')++ expect(system(second).startsWith('You are Doctor Watson, the physician.')).toBe(true)+ expect(system(second)).toContain('you are "Watson" and only "Watson"')+ expect(system(second)).toContain('The other participants are "Sherlock".')+ expect(system(second)).not.toContain('Sherlock Holmes, the detective')++ // The house rules ride along with a persona exactly as in a single chat.+ expect(system(first)).toContain(HOUSE_RULES)+ expect(system(second)).toContain(HOUSE_RULES)+ })++ it('the second speaker sees the first as a NAMED speaker, not as itself', async () => {+ const convId = openGroup()+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ useChatStore.getState().setGroupPersona(convId, B, 'watson')+ await round('who did it?')+ // (Two user turns in a row reach the wire as one, joined by a blank line:+ // api/providers/normalize-system.ts, for templates that demand strict+ // alternation.)+ expect(turns(requests[1])).toEqual([+ ['user', 'who did it?\n\n[Sherlock] The butler did it.'],+ ])++ // Round two: each sees its own line as its own, the other's under its name.+ await round('are you sure?')+ expect(turns(requests[2])).toEqual([+ ['user', 'who did it?'],+ ['assistant', 'The butler did it.'],+ ['user', '[Watson] I examined the body.\n\nare you sure?'],+ ])+ expect(conversation(convId).messages.filter((m) => m.role === 'assistant').map((m) => m.modelId)).toEqual([A, B, A, B])+ })++ it('a line a model writes FOR the other participant is cut, under either name', async () => {+ const convId = openGroup()+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ useChatStore.getState().setGroupPersona(convId, B, 'watson')+ answers['model-a'] = 'The butler did it.\n[Watson] Brilliant, Holmes!'+ await round('who did it?')+ const said = conversation(convId).messages.filter((m) => m.role === 'assistant')+ expect(said[0].content).toBe('The butler did it.')+ })++ it('only ONE participant has a persona: the other keeps following the chat', async () => {+ const convId = openGroup()+ useChatStore.getState().setGroupPersona(convId, B, 'watson')+ await round('hello')+ const [first, second] = requests+ // Model A: no persona of its own and none switched on for the chat.+ expect(system(first).startsWith(CHAT_BASE_ROLE)).toBe(true)+ expect(system(first)).toContain(`you are "${A}" and only "${A}"`)+ expect(system(first)).toContain('The other participants are "Watson".')+ expect(system(second).startsWith('You are Doctor Watson, the physician.')).toBe(true)+ })++ it('the pick belongs to the conversation: another group chat is untouched', async () => {+ const first = openGroup()+ useChatStore.getState().setGroupPersona(first, A, 'sherlock')+ const second = openGroup()+ expect(conversation(first).groupPersonas).toEqual({ [A]: 'sherlock' })+ expect(conversation(second).groupPersonas).toBeUndefined()+ await round('hello')+ expect(system(requests[0])).not.toContain('Sherlock')+ })+})++describe('the default is what it was', () => {+ it('no pick: both models get the chat prompt and the v1 group line, tagged by model', async () => {+ openGroup()+ await round('hello')+ const [first, second] = requests+ expect(system(first)).toBe(+ `${CHAT_BASE_ROLE} ${HOUSE_RULES}\n\n` ++ `You are "${A}", one of several AI models answering in the same group conversation with "${B}". ` ++ 'What the other models said arrives as user messages that start with a [model-name] tag; the assistant messages are your own earlier turns. ' ++ 'Answer as yourself in your own voice, add something new, and do not repeat what another model already said.',+ )+ expect(turns(second)).toEqual([+ ['user', `hello\n\n[${A}] The butler did it.`],+ ])+ })++ it('no pick, chat persona switched on: both share it, as before', async () => {+ const convId = openGroup('You are a pirate.')+ useChatStore.getState().setConversationPersonaEnabled(convId, true)+ await round('hello')+ expect(system(requests[0]).startsWith('You are a pirate.')).toBe(true)+ expect(system(requests[1]).startsWith('You are a pirate.')).toBe(true)+ })++ it('a pick works with the Personas switch in Settings at its default, which is off', async () => {+ // A group never asked that switch about the chat persona either. A pick+ // made for one participant in this chat's own menu is explicit enough.+ expect(DEFAULT_SETTINGS.personasEnabled).toBe(false)+ const convId = openGroup()+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ await round('hello')+ expect(system(requests[0]).startsWith('You are Sherlock Holmes, the detective.')).toBe(true)+ })++ it('a persona deleted after it was picked falls back instead of leaving an empty role', async () => {+ const convId = openGroup()+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ useSettingsStore.getState().removePersona('sherlock')+ await round('hello')+ expect(system(requests[0])).toContain(`You are "${A}", one of several AI models`)+ })+})++describe('the store keeps the picks tidy', () => {+ it('a model that leaves the group takes its pick with it', () => {+ const convId = openGroup()+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ useChatStore.getState().setGroupPersona(convId, B, 'watson')+ useChatStore.getState().setGroupModels(convId, [B])+ expect(conversation(convId).groupPersonas).toEqual({ [B]: 'watson' })+ useChatStore.getState().setGroupModels(convId, [])+ expect('groupPersonas' in conversation(convId)).toBe(false)+ })++ it('choosing the chat persona again removes the pick, and the field with the last one', () => {+ const convId = openGroup()+ useChatStore.getState().setGroupPersona(convId, A, 'sherlock')+ useChatStore.getState().setGroupPersona(convId, A, null)+ expect('groupPersonas' in conversation(convId)).toBe(false)+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex e20e661c..685d8b81 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -98,7 +98,8 @@ import { useToolAuditStore } from '../stores/toolAuditStore'import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'import { explainError as explainToolError } from '../api/agents/error-hints'import { hasUnrecoveredOutsideRefusal, OUTSIDE_WORKSPACE_NOTICE } from '../lib/workspace-refusal'-import { useChatNoticeStore } from '../stores/chatNoticeStore'+import { useChatNoticeStore, CHAT_NOTICE_MS } from '../stores/chatNoticeStore'+import { copyFailedMessage, fileMessageFields, filesWithoutWorkspace, placeChatFiles, type ChatFileInput } from '../lib/chat-files'import { settleThinking } from '../lib/thinking-stripper'import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/plan-reconcile'import { planResumeAnchor } from '../lib/plan-resume'@@ -304,6 +305,13 @@ export function useAgentChat() {* einem Lauf zurueckschreibt.*/hiddenUser?: boolean+ /**+ * Files attached to this message (3.0.5). In Agent mode they are copied+ * into the chat's working folder before the turn starts, so the file+ * tools can work on the real bytes; in Chat Tools mode (plain chat) the+ * model gets their summaries only. See lib/chat-files.ts.+ */+ files?: ChatFileInput[]},) => {const { activeModel } = useModelStore.getState()@@ -848,11 +856,38 @@ export function useAgentChat() {remote: providerId === 'ollama' ? !isOllamaLocal() : false,})+ // Attached files. Full Agent mode works in a real folder, so the file goes+ // there first and the message names its path; Chat Tools writes nothing to+ // disk (artifact mode), so there the summary is all the model gets. A copy+ // that fails never stops the turn: the block then says that only the+ // summary is available, and the line above the transcript tells the user.+ let attachedFiles = filesWithoutWorkspace(opts?.files)+ if (opts?.files?.length && opts.chatToolsMode !== true) {+ const placed = await placeChatFiles(opts.files, {+ chatId: slug,+ ...(resolvedWorkspace?.kind === 'folder' && resolvedWorkspace.path+ ? { workingDirectory: resolvedWorkspace.path }+ : {}),+ })+ attachedFiles = placed.files+ if (placed.failed.length) {+ useChatNoticeStore.getState().show('file-attach', copyFailedMessage(placed.failed), 'ruhig', CHAT_NOTICE_MS)+ }+ }+ const fileFields = fileMessageFields(+ userContent,+ attachedFiles,+ opts?.chatToolsMode === true ? 'chat' : 'workspace',+ )+// Add user messageconst userMessage = {id: uuid(),role: 'user' as const,- content: userContent,+ // With files: the typed text plus one summary block per file, and the+ // typed text alone as what the bubble shows. `userContent` itself stays+ // the typed text for retrieval, memory and tool selection below.+ ...fileFields,// Slash command: show "/commit" to the user, keep the expansion in content....(opts?.displayContent ? { displayContent: opts.displayContent } : {}),...(opts?.hiddenUser ? { hidden: true } : {}),diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 282a5968..a4afed7c 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -45,7 +45,8 @@ import { stripNonCanonicalTags, finalStripThinkingTags, settleThinking } from ".import { isLocalModelByName } from "../api/agents/model-locality"import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from "../lib/ollama-errors"import type { ImageAttachment, Message } from "../types/chat"-import { isGroupChat, groupSystemPrompt, groupHistory, stripImpersonatedSpeakers } from "../lib/group-chat"+import { fileMessageFields, filesWithoutWorkspace, type ChatFileInput } from "../lib/chat-files"+import { isGroupChat, groupSystemPrompt, groupHistory, groupSpeakers, stripImpersonatedSpeakers } from "../lib/group-chat"import { explainSendRefusal } from "../lib/template-refusal"import { builtinReloadNeeded, ensureBuiltinEngineAlive } from "../api/builtin-ensure"import { emptyAnswerExplanation } from "../lib/answer-notes"@@ -98,7 +99,22 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],// Der Grundtext gilt unabhaengig vom Personenschalter: der Schalter// entscheidet ueber die PERSON, nicht darueber, ob ueberhaupt ein Systemtext// rausgeht. Siehe lib/system-prompt.ts.- const personaPrompt = buildChatSystemPrompt(conv)+ //+ // 3.0.5 (samvenice, Discord): a participant can have a persona of its own.+ // Then ITS prompt is that persona and the others are named to it, so two+ // models no longer answer as the same character. A participant without one+ // gets the chat's persona setting, exactly as before.+ //+ // Not gated on the Personas switch in Settings, for the same reason the+ // line for the chat's own persona below never was in a group: that switch+ // is off by default, and a persona picked for one participant in this+ // chat's group menu is as explicit as a choice gets. Picking "Chat persona"+ // there takes it back.+ const speakers = groupSpeakers(allModels, conv.groupPersonas, useSettingsStore.getState().personas)+ const ownPersona = speakers[model]?.personaPrompt+ const personaPrompt = ownPersona !== undefined+ ? buildChatSystemPrompt({ systemPrompt: ownPersona, personaEnabled: true })+ : buildChatSystemPrompt(conv)const providerId = getProviderIdFromModel(model)// Same count cap as the plain path: a long group chat must not outgrow the// proxy's message gate either.@@ -115,8 +131,8 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],// the 262k model beside it.const messages = applyChatSendBudget(capMessageCount([- { role: 'system' as const, content: groupSystemPrompt(model, allModels, personaPrompt) },- ...groupHistory(conv.messages, model),+ { role: 'system' as const, content: groupSystemPrompt(model, allModels, personaPrompt, speakers) },+ ...groupHistory(conv.messages, model, speakers),]),{providerId,@@ -145,7 +161,11 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],let groupFinish: string | undefined// A model's own lines are untagged; a "[other-model]" tag in its OWN reply is// it speaking for someone else, which v1 must not show.- const others = allModels.filter((m) => m !== model)+ // The others can show up under their model name or under their persona+ // name, so both spellings of the tag are cut.+ const others = allModels+ .filter((m) => m !== model)+ .flatMap((m) => (speakers[m].name === m ? [m] : [m, speakers[m].name]))try {// Local speakers share ONE engine process. llama-server holds a single@@ -386,7 +406,7 @@ export function useChat() {* a second local conversation could stream from the built-in engine at the* same time, silently, because `localLaneHolder()` never heard about the* group round at all. */- const runGroupRound = useCallback(async (convId: string, content: string, images: ImageAttachment[] | undefined, models: string[]) => {+ const runGroupRound = useCallback(async (convId: string, content: string, images: ImageAttachment[] | undefined, models: string[], files?: ChatFileInput[]) => {// Auflage 3 (Review composer, 19.09.2026): derselbe Wiedereintritts-Riegel// wie sendMessage oben ("Re-entry guard"). Ohne ihn ueberschrieb ein// doppeltes Enter auf einem Gruppenchat den Token der ersten Runde weiter@@ -418,7 +438,9 @@ export function useChat() {useChatStore.getState().addMessage(convId, {id: uuid(),role: 'user',- content,+ // An attached file reaches every speaker as its summary, inside the+ // one user line they all share (lib/chat-files.ts).+ ...fileMessageFields(content, filesWithoutWorkspace(files)),images,timestamp: Date.now(),})@@ -506,7 +528,7 @@ export function useChat() {}}, [])- const sendMessage = useCallback(async (content: string, images?: ImageAttachment[]) => {+ const sendMessage = useCallback(async (content: string, images?: ImageAttachment[], files?: ChatFileInput[]) => {const { activeModel } = useModelStore.getState()const { settings } = useSettingsStore.getState()const store = useChatStore.getState()@@ -673,9 +695,12 @@ export function useChat() {displayContent: content,readOnly: slash.command.readOnly === true,...(loop ? { loop } : {}),+ files,})}- return sendAgentMessage(content, images)+ // Agent mode: an attached file is also copied into this chat's working+ // folder, where the file tools can open it (useAgentChat).+ return sendAgentMessage(content, images, { files })}// Discord 28.09.2026 (xambran): im normalen Chat liest kein Werkzeug die@@ -694,7 +719,7 @@ export function useChat() {{const groupConv = store.conversations.find((c) => c.id === store.activeConversationId)if (groupConv && isGroupChat(groupConv.groupModels)) {- return runGroupRound(groupConv.id, content, images, groupConv.groupModels)+ return runGroupRound(groupConv.id, content, images, groupConv.groupModels, files)}}@@ -730,6 +755,7 @@ export function useChat() {: CHAT_TOOLS,chatToolsMode: true,mediaHint: route.mediaHint,+ files,})}}@@ -772,7 +798,11 @@ export function useChat() {const userMessage = {id: uuid(),role: "user" as const,- content,+ // Plain chat has no file tools, so an attached file is its summary and+ // nothing else: name, type, hash, a hex dump of the start and the+ // readable strings (lib/chat-files.ts). `content` below stays the typed+ // text, which is what retrieval and memory search with.+ ...fileMessageFields(content, filesWithoutWorkspace(files)),images,timestamp: Date.now(),}@@ -1611,7 +1641,7 @@ export function useChat() {const plan = planResend(conv.messages, targetId, override)if (!plan) returnuseChatStore.getState().deleteMessagesAfter(conversationId, plan.deleteFromId)- sendMessage(plan.content, plan.images)+ sendMessage(plan.content, plan.images, plan.files?.map((attachment) => ({ attachment })))}, [sendMessage])const regenerateMessage = useCallback((conversationId: string, assistantMessageId: string) => {diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex a46f30dd..1dafbe87 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -39,6 +39,9 @@ import { resolveChatWorkspaceSlug } from '../api/workspace-slug'import { codexModeKnobs, type CodexMode } from '../lib/codex-mode'import { CODEX_PLAN_SYSTEM_PROMPT } from '../lib/codex-plan-prompt'import { resolveWorkspace } from '../api/agents/workspace-resolve'+import { useChatNoticeStore, CHAT_NOTICE_MS } from '../stores/chatNoticeStore'+import { copyFailedMessage, fileMessageFields, placeChatFiles, type ChatFileInput } from '../lib/chat-files'+import type { FileAttachment } from '../types/chat'import { useAgentModeStore } from '../stores/agentModeStore'import { loadLurules, renderRulesSection } from '../lib/lurules'import {@@ -343,6 +346,12 @@ export function useCodex() {* Verlauf stuende sonst ein Satz, den der Mensch nie geschrieben hat.*/hiddenUser?: boolean+ /**+ * Files attached to this instruction (3.0.5). They are copied into the+ * working folder of the run before the first step, so the file and+ * shell tools can open the real bytes. See lib/chat-files.ts.+ */+ files?: ChatFileInput[]},) => {const { activeModel } = useModelStore.getState()@@ -601,10 +610,29 @@ export function useCodex() {id: uuid(), type: 'instruction', content: instruction, timestamp: Date.now(),})+ // Attached files go into the folder this run works in, the same one the+ // lock above names, and the message tells the model their paths. A copy+ // that fails never stops the run: the model then gets the summary alone+ // and the line above the transcript says so.+ let attachedFiles: FileAttachment[] | undefined+ if (opts?.files?.length) {+ const placed = await placeChatFiles(opts.files, {+ chatId: workspaceSlug,+ ...(runWorkspace?.kind === 'folder' && runWorkspace.path ? { workingDirectory: runWorkspace.path } : {}),+ })+ attachedFiles = placed.files+ if (placed.failed.length) {+ useChatNoticeStore.getState().show('file-attach', copyFailedMessage(placed.failed), 'ruhig', CHAT_NOTICE_MS)+ }+ }+// Add user message to chat store. For a slash command the UI shows the raw// "/cmd args" (displayContent) while the model receives the expansion.useChatStore.getState().addMessage(convId, {- id: uuid(), role: 'user', content: instruction, timestamp: Date.now(),+ id: uuid(), role: 'user', timestamp: Date.now(),+ // With files: the instruction plus one summary block per file, and the+ // typed text as what the transcript shows.+ ...fileMessageFields(instruction, attachedFiles, 'workspace'),...(displayInstruction ? { displayContent: displayInstruction } : {}),...(opts?.hiddenUser ? { hidden: true } : {}),})diff --git a/src/lib/__tests__/chat-files.test.ts b/src/lib/__tests__/chat-files.test.tsnew file mode 100644index 00000000..bf139111--- /dev/null+++ b/src/lib/__tests__/chat-files.test.ts@@ -0,0 +1,323 @@+/**+ * Any file as a chat attachment (3.0.5): what the model gets in place of the+ * bytes, how large that can become, and how the file reaches the working+ * folder in Agent and Code.+ *+ * Run: npx vitest run src/lib/__tests__/chat-files.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++const backendCall = vi.fn()+vi.mock('../../api/backend', () => ({ backendCall: (...args: unknown[]) => backendCall(...args), isTauri: () => true }))++import {+ FILE_ONLY_TEXT,+ HEX_DUMP_BYTES,+ MAX_CHAT_FILE_BYTES,+ STRINGS_BUDGET_CHARS,+ TEXT_EXCERPT_CHARS,+ cleanFileName,+ composeFileMessage,+ copyFailedMessage,+ describeFileBytes,+ fileBlock,+ fileMessageFields,+ filesWithoutWorkspace,+ fileTooLargeMessage,+ hexDump,+ numberedFileName,+ placeChatFiles,+ prepareChatFile,+ readableStrings,+} from '../chat-files'++const ascii = (s: string) => [...s].map((c) => c.charCodeAt(0))++/** A small fake GBA cartridge: branch, logo, title, then noise with strings. */+function fakeRom(size = 4096): Uint8Array<ArrayBuffer> {+ const rom = new Uint8Array(size)+ for (let i = 0; i < size; i++) rom[i] = (i * 31 + 7) & 0xff+ rom.set([0x2e, 0x00, 0x00, 0xea, 0x24, 0xff, 0xae, 0x51, 0x69, 0x9a, 0xa2, 0x21], 0)+ rom.set([0x00, ...ascii('POKEMON EMER'), 0x00, ...ascii('BPEE01'), 0x00], 0xa0)+ rom.set([0x00, ...ascii('Game Freak inc.'), 0x00], 0x400)+ return rom+}++beforeEach(() => backendCall.mockReset())++describe('hexDump', () => {+ it('prints offset, sixteen bytes and the printable column', () => {+ const dump = hexDump(new Uint8Array([...ascii('NES'), 0x1a, 0x02, 0x01]))+ expect(dump).toBe(`00000000 ${'4e 45 53 1a 02 01'.padEnd(23)} ${''.padEnd(23)} |NES...|`)+ })++ it('stops at the limit and counts the offset in hex', () => {+ const dump = hexDump(new Uint8Array(1000), 40)+ const lines = dump.split('\n')+ expect(lines).toHaveLength(3)+ expect(lines[1].startsWith('00000010 ')).toBe(true)+ expect(lines[2].startsWith('00000020 00 00 00 00 00 00 00 00 ')).toBe(true)+ })+})++describe('readableStrings', () => {+ it('finds the strings in file order and drops runs that are too short', () => {+ const bytes = new Uint8Array([0, ...ascii('abc'), 0, ...ascii('HELLO WORLD'), 0xff, ...ascii('second one'), 0])+ expect(readableStrings(bytes)).toEqual({ strings: ['HELLO WORLD', 'second one'], more: false })+ })++ it('lists a repeated string once', () => {+ const bytes = new Uint8Array([...ascii('REPEAT'), 0, ...ascii('REPEAT'), 0, ...ascii('REPEAT')])+ expect(readableStrings(bytes).strings).toEqual(['REPEAT'])+ })++ it('never spends more than its budget and says when it stopped early', () => {+ const chunks: number[] = []+ for (let i = 0; i < 2000; i++) chunks.push(...ascii(`string number ${i}`), 0)+ const { strings, more } = readableStrings(new Uint8Array(chunks), 200)+ expect(more).toBe(true)+ expect(strings.join('\n').length).toBeLessThanOrEqual(200)+ expect(strings[0]).toBe('string number 0')+ })+})++describe('describeFileBytes: what the model reads instead of the bytes', () => {+ it('describes a ROM with its type, a hex dump of the start and its strings', () => {+ const { kind, summary } = describeFileBytes(fakeRom(), 'emerald.gba')+ expect(kind).toBe('Game Boy Advance ROM')+ expect(summary).toContain('This is a binary file.')+ expect(summary).toContain(`Hex dump of the first ${HEX_DUMP_BYTES} bytes:`)+ expect(summary).toContain('00000000 2e 00 00 ea 24 ff ae 51 69 9a a2 21')+ expect(summary).toContain('POKEMON EMER')+ expect(summary).toContain('Game Freak inc.')+ })++ it('THE BUDGET: a 4 MiB file costs no more than a small one', () => {+ const big = new Uint8Array(4 * 1024 * 1024)+ // Worst case for the strings: the whole file is distinct readable ones.+ const encoder = new TextEncoder()+ let at = 8+ for (let i = 0; at + 40 < big.length; i++) {+ const piece = encoder.encode(`distinct string number ${i}`)+ big.set(piece, at)+ at += piece.length + 1+ }+ big.set([0x7f, ...ascii('ELF')], 0)+ const { summary } = describeFileBytes(big, 'huge.bin')+ // Hex dump: 16 lines of at most 78 characters. Strings: the budget. Plus+ // the three fixed sentences.+ expect(summary.length).toBeLessThan(16 * 79 + STRINGS_BUDGET_CHARS + 400)+ expect(summary).toContain('(the first ones, there are more)')+ })++ it('shows a text file as text, whole when it is short', () => {+ const { kind, summary } = describeFileBytes(new TextEncoder().encode('line one\nline two\n'), 'notes.txt')+ expect(kind).toBe('Text file (.txt)')+ expect(summary).toBe('The whole text of the file:\nline one\nline two\n')+ expect(summary).not.toContain('Hex dump')+ })++ it('cuts a long text file at the excerpt and says so', () => {+ const { summary } = describeFileBytes(new TextEncoder().encode('x'.repeat(TEXT_EXCERPT_CHARS * 3)), 'long.log')+ expect(summary.startsWith(`The file is longer than this excerpt. The first ${TEXT_EXCERPT_CHARS} characters:\n`)).toBe(true)+ expect(summary.length).toBeLessThan(TEXT_EXCERPT_CHARS + 100)+ })++ it('says so when a binary holds no readable strings, and when a file is empty', () => {+ expect(describeFileBytes(new Uint8Array([0x7f, 0x45, 0x4c, 0x46, 0, 1, 2, 3]), 'a.out').summary)+ .toContain('No readable strings were found in the file.')+ expect(describeFileBytes(new Uint8Array(0), 'empty.bin')).toEqual({ kind: 'Empty file', summary: 'The file is empty.' })+ })+})++describe('prepareChatFile', () => {+ it('returns name, size, type, the SHA-256 and the summary, and keeps the handle', async () => {+ const file = new File([fakeRom(2048)], 'emerald.gba')+ const { attachment, file: handle } = await prepareChatFile(file)+ expect(handle).toBe(file)+ expect(attachment).toMatchObject({ name: 'emerald.gba', size: 2048, kind: 'Game Boy Advance ROM' })+ expect(attachment.sha256).toMatch(/^[0-9a-f]{64}$/)+ expect(attachment.summary).toContain('POKEMON EMER')+ expect(attachment.workspacePath).toBeUndefined()+ })++ it('hashes the bytes: the known SHA-256 of "abc"', async () => {+ const { attachment } = await prepareChatFile(new File(['abc'], 'abc.txt'))+ expect(attachment.sha256).toBe('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')+ })++ it('refuses a file over the limit BEFORE reading it, in plain English', async () => {+ const tooBig = { name: 'disc.iso', size: MAX_CHAT_FILE_BYTES + 1, arrayBuffer: vi.fn() } as unknown as File+ await expect(prepareChatFile(tooBig)).rejects.toThrow('"disc.iso" is too large. You can attach files up to 64.0 MB.')+ expect(tooBig.arrayBuffer).not.toHaveBeenCalled()+ expect(fileTooLargeMessage('disc.iso')).toBe('"disc.iso" is too large. You can attach files up to 64.0 MB.')+ })++ it('a file at exactly the limit is still accepted', async () => {+ const atLimit = {+ name: 'ok.bin',+ size: MAX_CHAT_FILE_BYTES,+ arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer,+ } as unknown as File+ await expect(prepareChatFile(atLimit)).resolves.toMatchObject({ attachment: { name: 'ok.bin' } })+ })+})++describe('cleanFileName', () => {+ it('drops the path, control characters and brackets that could close the block', () => {+ expect(cleanFileName('C:\\Users\\me\\rom.gba')).toBe('rom.gba')+ expect(cleanFileName('/home/me/rom.gba')).toBe('rom.gba')+ expect(cleanFileName('a\nb\tc.bin')).toBe('a b c.bin')+ expect(cleanFileName('[End of attached file].bin')).toBe('_End of attached file_.bin')+ expect(cleanFileName('')).toBe('file')+ expect(cleanFileName('x'.repeat(300)).length).toBe(120)+ })+})++const attachment = {+ name: 'emerald.gba',+ size: 16777216,+ kind: 'Game Boy Advance ROM',+ sha256: 'ab'.repeat(32),+ summary: 'SUMMARY',+}++describe('the message the model receives', () => {+ it('plain chat: the block says that only the summary is available', () => {+ expect(fileBlock(attachment, 'chat')).toBe([+ '[Attached file: emerald.gba]',+ 'Type: Game Boy Advance ROM',+ 'Size: 16.0 MB (16777216 bytes)',+ `SHA-256: ${'ab'.repeat(32)}`,+ 'The file itself is not available to you in this chat. Only this summary is.',+ '',+ 'SUMMARY',+ '[End of attached file: emerald.gba]',+ ].join('\n'))+ })++ it('Agent and Code: the block names the path in the working folder', () => {+ const block = fileBlock({ ...attachment, workspacePath: 'emerald.gba' }, 'workspace')+ expect(block).toContain('Path in your working folder: emerald.gba')+ expect(block).toContain('Use your file and shell tools on that path')+ expect(block).not.toContain('not available to you')+ })++ it('Agent and Code, copy failed: the block does not promise a path', () => {+ const block = fileBlock(attachment, 'workspace')+ expect(block).toContain('could not be copied into your working folder')+ expect(block).not.toContain('Path in your working folder')+ })++ it('puts the typed text first and one block per file after it', () => {+ const out = composeFileMessage('what game is this?', [attachment, { ...attachment, name: 'b.bin' }])+ expect(out.startsWith('what game is this?\n\n[Attached file: emerald.gba]')).toBe(true)+ expect(out).toContain('[End of attached file: emerald.gba]\n\n[Attached file: b.bin]')+ })++ it('leaves a message without files exactly as typed', () => {+ expect(composeFileMessage('hello', undefined)).toBe('hello')+ expect(composeFileMessage('hello', [])).toBe('hello')+ expect(fileMessageFields('hello', undefined)).toEqual({ content: 'hello' })+ expect(fileMessageFields('hello', [])).toEqual({ content: 'hello' })+ })++ it('with files: content for the model, the typed text for the bubble, the list for the chips', () => {+ const fields = fileMessageFields(FILE_ONLY_TEXT, [attachment])+ expect(fields.displayContent).toBe('(file)')+ expect(fields.files).toEqual([attachment])+ expect(fields.content).toContain('[Attached file: emerald.gba]')+ })++ it('NOTHING OF THE FILE IS STORED: no base64 and no data field in what is kept', () => {+ const fields = fileMessageFields('hi', [attachment])+ expect(Object.keys(fields.files![0]).sort()).toEqual(['kind', 'name', 'sha256', 'size', 'summary'])+ })++ it('a send without a working folder forgets the path of an earlier Agent turn', () => {+ expect(filesWithoutWorkspace([{ attachment: { ...attachment, workspacePath: 'emerald.gba' } }])).toEqual([attachment])+ expect(filesWithoutWorkspace(undefined)).toBeUndefined()+ expect(filesWithoutWorkspace([])).toBeUndefined()+ })+})++describe('placeChatFiles: the file goes into the working folder', () => {+ const workspace = { chatId: 'my-chat-abc123' }++ it('uploads in chunks, in order, and marks only the last one', async () => {+ backendCall.mockResolvedValue({ status: 'partial' })+ const size = 5 * 1024 * 1024+ const file = new File([new Uint8Array(size)], 'big.bin')+ const { files, failed } = await placeChatFiles([{ attachment: { ...attachment, name: 'big.bin' }, file }], workspace)+ expect(failed).toEqual([])+ expect(files[0].workspacePath).toBe('big.bin')+ const calls = backendCall.mock.calls.map(([cmd, args]) => [cmd, args.path, args.offset, args.last, args.chatId])+ expect(calls).toEqual([+ ['fs_write_bytes', 'big.bin', 0, false, 'my-chat-abc123'],+ ['fs_write_bytes', 'big.bin', 2 * 1024 * 1024, false, 'my-chat-abc123'],+ ['fs_write_bytes', 'big.bin', 4 * 1024 * 1024, true, 'my-chat-abc123'],+ ])+ // Byte fidelity of the encoding: the chunks decode back to the file size.+ const sent = backendCall.mock.calls.reduce((sum, [, args]) => sum + atob(args.base64).length, 0)+ expect(sent).toBe(size)+ })++ it('encodes the bytes faithfully', async () => {+ backendCall.mockResolvedValue({ status: 'saved' })+ const bytes = new Uint8Array([0x00, 0xff, 0x80, 0x0d, 0x0a, 0x7f])+ await placeChatFiles([{ attachment, file: new File([bytes], 'emerald.gba') }], workspace)+ const decoded = atob(backendCall.mock.calls[0][1].base64)+ expect([...decoded].map((c) => c.charCodeAt(0))).toEqual([...bytes])+ expect(backendCall.mock.calls[0][1].last).toBe(true)+ })++ it('passes the picked folder through when the chat works in one', async () => {+ backendCall.mockResolvedValue({ status: 'saved' })+ await placeChatFiles([{ attachment, file: new File(['x'], 'emerald.gba') }], { chatId: 'c', workingDirectory: '/home/me/repo' })+ expect(backendCall.mock.calls[0][1]).toMatchObject({ chatId: 'c', workingDirectory: '/home/me/repo' })+ })++ it('NEVER OVERWRITES: a taken name gets the next free one', async () => {+ backendCall+ .mockRejectedValueOnce('File already exists: /ws/emerald.gba')+ .mockRejectedValueOnce(new Error('File already exists: /ws/emerald (1).gba'))+ .mockResolvedValue({ status: 'saved' })+ const { files } = await placeChatFiles([{ attachment, file: new File(['x'], 'emerald.gba') }], workspace)+ expect(backendCall.mock.calls.map(([, args]) => args.path)).toEqual(['emerald.gba', 'emerald (1).gba', 'emerald (2).gba'])+ expect(files[0].workspacePath).toBe('emerald (2).gba')+ })++ it('a failed copy does not throw: the file keeps its summary and is named', async () => {+ // Only the upload fails. The warning this writes goes through the same+ // bridge (the log file), and that call has to keep working.+ backendCall.mockImplementation(async (cmd: string) => {+ if (cmd === 'fs_write_bytes') throw 'Write error: No space left on device'+ return undefined+ })+ const { files, failed } = await placeChatFiles([{ attachment, file: new File(['x'], 'emerald.gba') }], workspace)+ expect(failed).toEqual(['emerald.gba'])+ expect(files).toEqual([attachment])+ expect(backendCall.mock.calls.filter(([cmd]) => cmd === 'fs_write_bytes')).toHaveLength(1)+ expect(copyFailedMessage(failed)).toBe('"emerald.gba" could not be copied into the working folder. The model only gets a summary of it.')+ })++ it('a resend copies nothing: no handle, or already in the folder', async () => {+ const placed = { ...attachment, workspacePath: 'emerald.gba' }+ const { files, failed } = await placeChatFiles(+ [{ attachment }, { attachment: placed, file: new File(['x'], 'emerald.gba') }],+ workspace,+ )+ expect(backendCall).not.toHaveBeenCalled()+ expect(failed).toEqual([])+ expect(files).toEqual([attachment, placed])+ })+})++describe('numberedFileName', () => {+ it('numbers in front of the extension', () => {+ expect(numberedFileName('rom.gba', 0)).toBe('rom.gba')+ expect(numberedFileName('rom.gba', 2)).toBe('rom (2).gba')+ expect(numberedFileName('Makefile', 1)).toBe('Makefile (1)')+ expect(numberedFileName('.env', 1)).toBe('.env (1)')+ })+})diff --git a/src/lib/__tests__/file-magic.test.ts b/src/lib/__tests__/file-magic.test.tsnew file mode 100644index 00000000..942374be--- /dev/null+++ b/src/lib/__tests__/file-magic.test.ts@@ -0,0 +1,126 @@+/**+ * The type line of an attached file comes from its bytes, not from its name.+ *+ * Run: npx vitest run src/lib/__tests__/file-magic.test.ts+ */+import { describe, it, expect } from 'vitest'+import { detectFileKind, fileExtension, looksLikeText } from '../file-magic'++const ascii = (s: string) => [...s].map((c) => c.charCodeAt(0))++/** A buffer of `size` zero bytes with `bytes` written at `at`. */+function withBytes(size: number, at: number, bytes: number[]): Uint8Array {+ const out = new Uint8Array(size)+ out.set(bytes, at)+ return out+}++const GBA_LOGO = [0x24, 0xff, 0xae, 0x51, 0x69, 0x9a, 0xa2, 0x21]++describe('console ROMs, the request that started this', () => {+ it('reads an iNES header', () => {+ expect(detectFileKind(withBytes(64, 0, [...ascii('NES'), 0x1a]), 'whatever.bin').label).toBe('NES ROM (iNES)')+ })++ it('reads a Game Boy Advance cartridge by its logo, whatever the name says', () => {+ const rom = withBytes(512, 0, [0x2e, 0x00, 0x00, 0xea, ...GBA_LOGO])+ expect(detectFileKind(rom, 'game.bin')).toEqual({ label: 'Game Boy Advance ROM', isText: false })+ })++ it('tells a Nintendo DS cartridge from a GBA one: same logo, other place', () => {+ expect(detectFileKind(withBytes(512, 0xc0, GBA_LOGO), 'game.bin').label).toBe('Nintendo DS ROM')+ })++ it('reads a Game Boy cartridge', () => {+ const rom = withBytes(512, 0x104, [0xce, 0xed, 0x66, 0x66, 0xcc, 0x0d, 0x00, 0x0b])+ expect(detectFileKind(rom, 'game.bin').label).toBe('Game Boy ROM')+ })++ it('reads all three byte orders of a Nintendo 64 ROM', () => {+ expect(detectFileKind(withBytes(64, 0, [0x80, 0x37, 0x12, 0x40]), 'a').label).toContain('.z64')+ expect(detectFileKind(withBytes(64, 0, [0x37, 0x80, 0x40, 0x12]), 'a').label).toContain('.v64')+ expect(detectFileKind(withBytes(64, 0, [0x40, 0x12, 0x37, 0x80]), 'a').label).toContain('.n64')+ })++ it('names a SNES ROM by its extension, because it carries no signature', () => {+ const rom = withBytes(1024, 0, [0x78, 0x18, 0xfb, 0xc2, 0x30, 0x00, 0x00, 0x9c])+ expect(detectFileKind(rom, 'zelda.sfc').label).toBe('SNES ROM')+ // Negative control: the same bytes under a name that says nothing.+ expect(detectFileKind(rom, 'zelda.xyz').label).toBe('Binary file (.xyz)')+ expect(detectFileKind(rom, 'zelda').label).toBe('Binary file')+ })+})++describe('everything else a person might drop in', () => {+ it('knows the common signatures', () => {+ const cases: [number[], string][] = [+ [[0x7f, ...ascii('ELF')], 'ELF executable'],+ [[...ascii('MZ'), 0x90, 0x00, 0x03], 'Windows executable (PE)'],+ [[0xcf, 0xfa, 0xed, 0xfe], 'Mach-O executable (64 bit)'],+ [[0x00, ...ascii('asm')], 'WebAssembly module'],+ [[0x1f, 0x8b, 0x08, 0x00], 'gzip archive'],+ [[...ascii('%PDF-1.7'), 0x0a, 0xff], 'PDF document'],+ [[...ascii('SQLite format 3'), 0x00], 'SQLite database'],+ [[0x89, ...ascii('PNG')], 'PNG image'],+ [[...ascii('GGUF'), 0x03, 0x00], 'GGUF model file'],+ ]+ for (const [bytes, label] of cases) {+ expect(detectFileKind(withBytes(64, 0, bytes), 'x.bin').label).toBe(label)+ }+ })++ it('looks inside a ZIP only as far as the name allows', () => {+ const zip = withBytes(64, 0, [...ascii('PK'), 0x03, 0x04])+ expect(detectFileKind(zip, 'report.docx').label).toBe('Word document (.docx)')+ expect(detectFileKind(zip, 'stuff.zip').label).toBe('ZIP archive')+ })++ it('reads what a RIFF container holds', () => {+ expect(detectFileKind(withBytes(64, 0, [...ascii('RIFF'), 0, 0, 0, 0, ...ascii('WAVE')]), 'a').label).toBe('WAV audio')+ expect(detectFileKind(withBytes(64, 0, [...ascii('RIFF'), 0, 0, 0, 0, ...ascii('AVI ')]), 'a').label).toBe('AVI video')+ })++ it('tells a Java class from a universal Mach-O binary, which open alike', () => {+ expect(detectFileKind(withBytes(64, 0, [0xca, 0xfe, 0xba, 0xbe, 0x00, 0x00, 0x00, 0x34]), 'a').label).toBe('Java class file')+ expect(detectFileKind(withBytes(64, 0, [0xca, 0xfe, 0xba, 0xbe, 0x00, 0x00, 0x00, 0x02]), 'a').label).toBe('Mach-O universal binary')+ })+})++describe('text is text, also when it starts like a signature', () => {+ it('recognises plain text and names its extension', () => {+ expect(detectFileKind(new Uint8Array(ascii('{"a": 1}\n')), 'data.json')).toEqual({ label: 'Text file (.json)', isText: true })+ expect(detectFileKind(new Uint8Array(ascii('hello\n')), 'README')).toEqual({ label: 'Text file', isText: true })+ })++ it('does not call a note that starts with "BM" or "MZ" an image or a program', () => {+ expect(detectFileKind(new Uint8Array(ascii('BMW is a car maker.\n')), 'note.txt').isText).toBe(true)+ expect(detectFileKind(new Uint8Array(ascii('MZ was here\n')), 'note.txt').isText).toBe(true)+ })++ it('a Markdown file is text, a binary .md is a Mega Drive ROM', () => {+ expect(detectFileKind(new Uint8Array(ascii('# Title\n')), 'notes.md').label).toBe('Text file (.md)')+ expect(detectFileKind(withBytes(64, 0, [0x00, 0xff, 0x00, 0xfe]), 'sonic.md').label).toBe('Sega Mega Drive / Genesis ROM')+ })++ it('accepts UTF-8 and a window that ends inside a character', () => {+ const utf8 = new TextEncoder().encode('Grüße aus Köln, 東京')+ expect(looksLikeText(utf8)).toBe(true)+ expect(looksLikeText(utf8.subarray(0, utf8.length - 1))).toBe(true)+ })++ it('refuses NUL bytes, invalid UTF-8 and the empty file', () => {+ expect(looksLikeText(new Uint8Array([0x68, 0x00, 0x69]))).toBe(false)+ expect(looksLikeText(new Uint8Array([0xff, 0xfe, 0x41]))).toBe(false)+ expect(looksLikeText(new Uint8Array(0))).toBe(false)+ })+})++describe('fileExtension', () => {+ it('reads the last extension, lowercased, and nothing from a dotfile', () => {+ expect(fileExtension('Game.GBA')).toBe('gba')+ expect(fileExtension('archive.tar.gz')).toBe('gz')+ expect(fileExtension('C:\\roms\\mario.nes')).toBe('nes')+ expect(fileExtension('.gitignore')).toBe('')+ expect(fileExtension('Makefile')).toBe('')+ })+})diff --git a/src/lib/__tests__/group-chat.test.ts b/src/lib/__tests__/group-chat.test.tsindex 89d6d822..fe228805 100644--- a/src/lib/__tests__/group-chat.test.ts+++ b/src/lib/__tests__/group-chat.test.ts@@ -3,7 +3,7 @@import { readFileSync } from 'node:fs'import { join } from 'node:path'import { describe, it, expect, beforeEach } from 'vitest'-import { isGroupChat, groupSystemPrompt, groupHistory, stripImpersonatedSpeakers, GROUP_CHAT_MAX } from '../group-chat'+import { isGroupChat, groupSystemPrompt, groupHistory, groupSpeakers, hasOwnPersonas, stripImpersonatedSpeakers, GROUP_CHAT_MAX } from '../group-chat'import { useChatStore } from '../../stores/chatStore'import type { Message } from '../../types/chat'@@ -157,3 +157,128 @@ describe('wiring (source guards)', () => {expect(pluginsSrc).toContain('GROUP_CHAT_MAX')})})++// ── 3.0.5, samvenice on Discord: a persona per participant ─────────────────+//+// Every model in a group used to answer under the ONE persona of the chat, so+// two models were both told they are the same character and spoke over each+// other. Each participant can now have its own.+describe('groupSpeakers', () => {+ const personas = [+ { id: 'sherlock', name: 'Sherlock', systemPrompt: 'You are Sherlock Holmes.' },+ { id: 'watson', name: 'Watson', systemPrompt: 'You are Doctor Watson.' },+ ]++ it('a participant with its own persona is called by it and speaks as it', () => {+ const speakers = groupSpeakers(['qwen', 'gemma'], { qwen: 'sherlock', gemma: 'watson' }, personas)+ expect(speakers).toEqual({+ qwen: { name: 'Sherlock', personaPrompt: 'You are Sherlock Holmes.' },+ gemma: { name: 'Watson', personaPrompt: 'You are Doctor Watson.' },+ })+ expect(hasOwnPersonas(speakers)).toBe(true)+ })++ it('THE DEFAULT IS WHAT IT WAS: no pick, no persona, the model name', () => {+ const speakers = groupSpeakers(['qwen', 'gemma'], undefined, personas)+ expect(speakers).toEqual({ qwen: { name: 'qwen' }, gemma: { name: 'gemma' } })+ expect(hasOwnPersonas(speakers)).toBe(false)+ expect(hasOwnPersonas(undefined)).toBe(false)+ })++ it('one participant may have a persona while the other follows the chat', () => {+ const speakers = groupSpeakers(['qwen', 'gemma'], { gemma: 'watson' }, personas)+ expect(speakers.qwen).toEqual({ name: 'qwen' })+ expect(speakers.gemma.name).toBe('Watson')+ })++ it('a persona that was deleted since reads as no pick, never as an empty role', () => {+ expect(groupSpeakers(['qwen'], { qwen: 'gone' }, personas)).toEqual({ qwen: { name: 'qwen' } })+ })++ it('two participants on the SAME persona still get two names', () => {+ const speakers = groupSpeakers(['qwen', 'gemma'], { qwen: 'sherlock', gemma: 'sherlock' }, personas)+ expect(speakers.qwen.name).toBe('Sherlock (qwen)')+ expect(speakers.gemma.name).toBe('Sherlock (gemma)')+ })++})++describe('groupSystemPrompt with own personas', () => {+ const speakers = {+ qwen: { name: 'Sherlock', personaPrompt: 'You are Sherlock Holmes.' },+ gemma: { name: 'Watson', personaPrompt: 'You are Doctor Watson.' },+ llama: { name: 'llama' },+ }+ const models = ['qwen', 'gemma', 'llama']++ it('each participant gets ITS persona, its own name and the others by name', () => {+ const sherlock = groupSystemPrompt('qwen', models, 'You are Sherlock Holmes.', speakers)+ expect(sherlock.startsWith('You are Sherlock Holmes.\n\n')).toBe(true)+ expect(sherlock).toContain('you are "Sherlock" and only "Sherlock"')+ expect(sherlock).toContain('The other participants are "Watson", "llama".')+ expect(sherlock).not.toContain('Doctor Watson')++ const watson = groupSystemPrompt('gemma', models, 'You are Doctor Watson.', speakers)+ expect(watson.startsWith('You are Doctor Watson.\n\n')).toBe(true)+ expect(watson).toContain('you are "Watson" and only "Watson"')+ expect(watson).toContain('The other participants are "Sherlock", "llama".')+ expect(watson).not.toContain('Sherlock Holmes')+ })++ it('tells the model not to take over another role', () => {+ const p = groupSystemPrompt('qwen', models, '', speakers)+ expect(p).toContain('never speak as another participant and never write their lines')+ expect(p).toContain('start with a [name] tag')+ })++ it('the participant without a persona is named by its model, and told the same', () => {+ const p = groupSystemPrompt('llama', models, 'BASE', speakers)+ expect(p).toContain('you are "llama" and only "llama"')+ expect(p).toContain('The other participants are "Sherlock", "Watson".')+ })++ it('NEGATIVE CONTROL: without own personas the wording is byte for byte the old one', () => {+ const plain = { qwen: { name: 'qwen' }, gemma: { name: 'gemma' } }+ expect(groupSystemPrompt('qwen', ['qwen', 'gemma'], 'P', plain)).toBe(groupSystemPrompt('qwen', ['qwen', 'gemma'], 'P'))+ expect(groupSystemPrompt('qwen', ['qwen', 'gemma'], 'P')).toBe(+ 'P\n\nYou are "qwen", one of several AI models answering in the same group conversation with "gemma". ' ++ 'What the other models said arrives as user messages that start with a [model-name] tag; the assistant messages are your own earlier turns. ' ++ 'Answer as yourself in your own voice, add something new, and do not repeat what another model already said.',+ )+ })+})++describe('groupHistory with own personas', () => {+ const speakers = {+ qwen: { name: 'Sherlock', personaPrompt: 'S' },+ gemma: { name: 'Watson', personaPrompt: 'W' },+ }+ const history: Message[] = [+ { id: '1', role: 'user', content: 'who did it?', timestamp: 1 },+ { id: '2', role: 'assistant', content: 'The butler.', modelId: 'qwen', timestamp: 2 },+ { id: '3', role: 'assistant', content: 'Surely not.', modelId: 'gemma', timestamp: 3 },+ ]++ it('the other speaker arrives under its persona name, the own turns stay untagged', () => {+ expect(groupHistory(history, 'gemma', speakers).map((m) => [m.role, m.content])).toEqual([+ ['user', 'who did it?'],+ ['user', '[Sherlock] The butler.'],+ ['assistant', 'Surely not.'],+ ])+ expect(groupHistory(history, 'qwen', speakers).map((m) => [m.role, m.content])).toEqual([+ ['user', 'who did it?'],+ ['assistant', 'The butler.'],+ ['user', '[Watson] Surely not.'],+ ])+ })++ it('a turn by a model that has left the group keeps its model name', () => {+ const withGone: Message[] = [...history, { id: '4', role: 'assistant', content: 'Hm.', modelId: 'llama', timestamp: 4 }]+ expect(groupHistory(withGone, 'qwen', speakers).at(-1)!.content).toBe('[llama] Hm.')+ })++ it('a fabricated turn under the persona name is cut like one under the model name', () => {+ expect(stripImpersonatedSpeakers('My view.\n[Watson] I agree entirely.', ['gemma', 'Watson'])).toBe('My view.')+ expect(stripImpersonatedSpeakers('My view.\n[gemma] I agree entirely.', ['gemma', 'Watson'])).toBe('My view.')+ })+})diff --git a/src/lib/__tests__/local-file-intent.test.ts b/src/lib/__tests__/local-file-intent.test.tsindex 07ee6f87..19a578d4 100644--- a/src/lib/__tests__/local-file-intent.test.ts+++ b/src/lib/__tests__/local-file-intent.test.ts@@ -87,7 +87,7 @@ describe('where the line comes and goes', () => {const show = chat.indexOf("show('agent-for-local-files', LOCAL_FILES_NOTICE)")expect(show).toBeGreaterThan(0)expect(chat).toContain('if (asksForLocalFiles(content)) {')- expect(show).toBeGreaterThan(chat.indexOf('return sendAgentMessage(content, images)'))+ expect(show).toBeGreaterThan(chat.indexOf('return sendAgentMessage(content, images, { files })'))expect(show).toBeLessThan(chat.indexOf('resolveChatToolRoute(content'))})@@ -95,7 +95,8 @@ describe('where the line comes and goes', () => {const agentBranch = chat.indexOf('useAgentModeStore.getState().isActive(store.activeConversationId)')const dismiss = chat.indexOf("dismiss('agent-for-local-files')")expect(dismiss).toBeGreaterThan(agentBranch)- expect(dismiss).toBeLessThan(chat.indexOf('return sendAgentMessage(content, images)'))+ expect(chat).toContain('return sendAgentMessage(content, images, { files })')+ expect(dismiss).toBeLessThan(chat.indexOf('return sendAgentMessage(content, images, { files })'))})it('turning Agent on takes it away, in a new agent chat and in this one', () => {diff --git a/src/lib/__tests__/resend-plan.test.ts b/src/lib/__tests__/resend-plan.test.tsindex b285c70e..86eb414d 100644--- a/src/lib/__tests__/resend-plan.test.ts+++ b/src/lib/__tests__/resend-plan.test.ts@@ -167,3 +167,41 @@ describe('nothing to resend', () => {expect(planResend([], 'a1')).toBeNull()})})++describe('a question with attached files (3.0.5)', () => {+ const file = { name: 'emerald.gba', size: 2048, kind: 'Game Boy Advance ROM', sha256: 'ab'.repeat(32), summary: 'SUMMARY' }+ const withFile = [+ {+ id: 'u1',+ role: 'user' as const,+ // What the model received: the typed text plus the summary block.+ content: 'what game is this?\n\n[Attached file: emerald.gba]\nSUMMARY\n[End of attached file: emerald.gba]',+ displayContent: 'what game is this?',+ files: [file],+ },+ { id: 'a1', role: 'assistant' as const, content: 'Pokemon Emerald' },+ ]++ it('regenerate sends back what was TYPED plus the files, not the content with the summaries in it', () => {+ // Sending the content back in would put the summary block into the+ // question, and the send would then append a second copy of it.+ expect(planResend(withFile, 'a1')).toEqual({ deleteFromId: 'u1', content: 'what game is this?', files: [file] })+ })++ it('an edit keeps the files and takes the new text', () => {+ expect(planResend(withFile, 'u1', 'and which region?')).toEqual({+ deleteFromId: 'u1',+ content: 'and which region?',+ files: [file],+ })+ })++ it('NEGATIVE CONTROL: a label in displayContent without files is still not input', () => {+ // The /loop driver writes "pass 3 of 5" there over the instruction.+ const loop = [+ { id: 'u1', role: 'user' as const, content: 'the real instruction', displayContent: 'pass 3 of 5' },+ { id: 'a1', role: 'assistant' as const, content: 'done' },+ ]+ expect(planResend(loop, 'a1')).toEqual({ deleteFromId: 'u1', content: 'the real instruction' })+ })+})diff --git a/src/lib/chat-files.ts b/src/lib/chat-files.tsnew file mode 100644index 00000000..6dfdb895--- /dev/null+++ b/src/lib/chat-files.ts@@ -0,0 +1,335 @@+/**+ * Any file as a chat attachment (3.0.5, applejames on Discord: "let me give+ * the model a ROM file").+ *+ * WHAT A MODEL CAN DO WITH A BINARY. Nothing with the bytes themselves: a+ * language model reads text, and base64 pasted into the prompt is neither+ * readable to it nor affordable (a 16 MB ROM is about 21 million characters).+ * So the chat does two honest things instead:+ *+ * 1. Every chat gets a compact description in place of the bytes: name,+ * size, the type read from the magic bytes, the SHA-256, a hex dump of+ * the first bytes and the readable strings found inside. All of it in a+ * fixed budget, a few kilobytes per file whatever the file weighs.+ * 2. In Agent and Code the file is also copied into the chat's working+ * folder, where the file and shell tools can work on the real thing.+ *+ * WHAT IS STORED. Only the description. The file is not copied into the chat+ * history, not as base64 and not as a reference to a stored blob: the history+ * is serialised as one string on every save, and a few large images in it+ * have taken the renderer down before (chat-attachments.ts, the 127 MiB+ * IndexedDB limit). The description is bounded by the constants below.+ *+ * The same text goes out to a local model and to a cloud model: it is part of+ * the user message, so no provider needs to know about it.+ */+import { backendCall } from '../api/backend'+import type { FileAttachment } from '../types/chat'+import { detectFileKind } from './file-magic'+import { formatBytes } from './formatters'+import { log } from './logger'++/** How many files one message may carry. */+export const MAX_CHAT_FILES = 3+/** The largest file that can be attached. The whole file is read once to hash+ * it, so this is also the most memory an attachment costs for a moment. */+export const MAX_CHAT_FILE_BYTES = 64 * 1024 * 1024+/** How much of the start of a binary is shown as a hex dump. */+export const HEX_DUMP_BYTES = 256+/** The budget for readable strings, in characters. */+export const STRINGS_BUDGET_CHARS = 3000+/** How much of a text file is shown. */+export const TEXT_EXCERPT_CHARS = 4000+/** A run of printable characters counts as a string from this length on. */+const MIN_STRING_LENGTH = 5+/** One string never takes more of the budget than this. */+const MAX_STRING_LENGTH = 120+/** How far into the file the string scan reads at most. */+const STRINGS_SCAN_BYTES = 8 * 1024 * 1024+/** The window the type detection looks at. The ISO 9660 signature sits at+ * 0x8001, everything else far earlier. */+const KIND_WINDOW_BYTES = 64 * 1024+/** Raw bytes per call when a file is copied into the working folder. */+const UPLOAD_CHUNK_BYTES = 2 * 1024 * 1024++export const TOO_MANY_FILES_MESSAGE = `You can attach up to ${MAX_CHAT_FILES} files per message.`++export function fileTooLargeMessage(name: string): string {+ return `"${cleanFileName(name)}" is too large. You can attach files up to ${formatBytes(MAX_CHAT_FILE_BYTES)}.`+}++/** A file waiting in the composer, or on its way through a send. `file` is the+ * handle to the bytes; it is absent on a resend, where the stored+ * description is all that is left and all that is needed. */+export interface ChatFileInput {+ attachment: FileAttachment+ file?: File+}++/**+ * A file name as one harmless line: no path, no control characters, no line+ * break that could end the attachment block early, and not endless.+ */+export function cleanFileName(name: string): string {+ const last = name.split(/[\\/]/).pop() ?? ''+ const base = Array.from(last, (c) => (c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f ? ' ' : c))+ .join('')+ .replace(/[[\]]/g, '_')+ .replace(/\s+/g, ' ')+ .trim()+ if (!base) return 'file'+ return base.length > 120 ? `${base.slice(0, 117)}...` : base+}++const hex2 = (n: number): string => n.toString(16).padStart(2, '0')++/** The classic sixteen-per-line dump: offset, hex bytes, printable column. */+export function hexDump(bytes: Uint8Array, limit = HEX_DUMP_BYTES): string {+ const end = Math.min(bytes.length, limit)+ const lines: string[] = []+ for (let at = 0; at < end; at += 16) {+ const row = bytes.subarray(at, Math.min(at + 16, end))+ const hex = Array.from(row, hex2)+ while (hex.length < 16) hex.push(' ')+ const shown = Array.from(row, (b) => (b >= 0x20 && b < 0x7f ? String.fromCharCode(b) : '.')).join('')+ lines.push(`${at.toString(16).padStart(8, '0')} ${hex.slice(0, 8).join(' ')} ${hex.slice(8).join(' ')} |${shown}|`)+ }+ return lines.join('\n')+}++/**+ * The readable strings in a binary, in file order, each one once, until the+ * budget is spent. `more` says whether the scan stopped before the end of the+ * file, so the description never claims to be complete when it is not.+ */+export function readableStrings(bytes: Uint8Array, budgetChars = STRINGS_BUDGET_CHARS): { strings: string[]; more: boolean } {+ const strings: string[] = []+ const seen = new Set<string>()+ let used = 0+ const end = Math.min(bytes.length, STRINGS_SCAN_BYTES)+ let start = -1+ for (let i = 0; i <= end; i++) {+ const printable = i < end && bytes[i] >= 0x20 && bytes[i] < 0x7f+ if (printable) {+ if (start < 0) start = i+ continue+ }+ if (start >= 0 && i - start >= MIN_STRING_LENGTH) {+ const length = Math.min(i - start, MAX_STRING_LENGTH)+ let value = ''+ for (let j = start; j < start + length; j++) value += String.fromCharCode(bytes[j])+ value = value.trim()+ if (value.length >= MIN_STRING_LENGTH && !seen.has(value)) {+ if (used + value.length + 1 > budgetChars) return { strings, more: true }+ seen.add(value)+ strings.push(value)+ used += value.length + 1+ }+ }+ start = -1+ }+ return { strings, more: end < bytes.length }+}++/** What the model reads in place of the bytes. Pure, so it can be tested on a+ * handful of bytes. */+export function describeFileBytes(bytes: Uint8Array, name: string): { kind: string; summary: string } {+ const kind = detectFileKind(bytes.subarray(0, KIND_WINDOW_BYTES), name)+ if (bytes.length === 0) return { kind: 'Empty file', summary: 'The file is empty.' }+ if (kind.isText) {+ // The window may end inside a multi-byte character; a lenient decoder+ // turns that into one replacement character, which is cut off below.+ const window = bytes.subarray(0, TEXT_EXCERPT_CHARS * 4)+ const decoded = new TextDecoder('utf-8').decode(window).replace(/�+$/, '')+ const excerpt = decoded.slice(0, TEXT_EXCERPT_CHARS)+ const whole = window.length === bytes.length && excerpt.length === decoded.length+ return {+ kind: kind.label,+ summary: whole+ ? `The whole text of the file:\n${excerpt}`+ : `The file is longer than this excerpt. The first ${excerpt.length} characters:\n${excerpt}`,+ }+ }+ const shown = Math.min(bytes.length, HEX_DUMP_BYTES)+ const { strings, more } = readableStrings(bytes)+ const parts = [+ 'This is a binary file. Its bytes cannot be shown to you, so this is a summary of it.',+ `Hex dump of the first ${shown} bytes:\n${hexDump(bytes)}`,+ ]+ if (strings.length > 0) {+ parts.push(+ `Readable strings found in the file${more ? ' (the first ones, there are more)' : ''}:\n${strings.join('\n')}`,+ )+ } else {+ parts.push('No readable strings were found in the file.')+ }+ return { kind: kind.label, summary: parts.join('\n\n') }+}++async function sha256Hex(buffer: ArrayBuffer): Promise<string> {+ const hash = await crypto.subtle.digest('SHA-256', buffer)+ return Array.from(new Uint8Array(hash), hex2).join('')+}++/**+ * Read a picked file once and build its description. Refuses a file over the+ * limit before reading a byte of it.+ */+export async function prepareChatFile(file: File): Promise<ChatFileInput> {+ if (file.size > MAX_CHAT_FILE_BYTES) throw new Error(fileTooLargeMessage(file.name))+ let buffer: ArrayBuffer+ try {+ buffer = await file.arrayBuffer()+ } catch {+ throw new Error(`"${cleanFileName(file.name)}" could not be read.`)+ }+ const name = cleanFileName(file.name)+ const { kind, summary } = describeFileBytes(new Uint8Array(buffer), name)+ return {+ attachment: { name, size: buffer.byteLength, kind, sha256: await sha256Hex(buffer), summary },+ file,+ }+}++/** The block one file contributes to the user message. */+export function fileBlock(file: FileAttachment, surface: 'chat' | 'workspace'): string {+ const where = file.workspacePath+ ? `Path in your working folder: ${file.workspacePath}\nUse your file and shell tools on that path for anything this summary does not answer.`+ : surface === 'workspace'+ ? 'The file could not be copied into your working folder. Only this summary is available.'+ : 'The file itself is not available to you in this chat. Only this summary is.'+ return [+ `[Attached file: ${file.name}]`,+ `Type: ${file.kind}`,+ `Size: ${formatBytes(file.size)} (${file.size} bytes)`,+ `SHA-256: ${file.sha256}`,+ where,+ '',+ file.summary,+ `[End of attached file: ${file.name}]`,+ ].join('\n')+}++/** What the user typed when a message carries nothing but files. */+export const FILE_ONLY_TEXT = '(file)'++/**+ * The user message as the model receives it: what was typed, then one block+ * per file. Without files the text comes back untouched.+ */+export function composeFileMessage(typed: string, files: readonly FileAttachment[] | undefined, surface: 'chat' | 'workspace' = 'chat'): string {+ if (!files?.length) return typed+ return [typed, ...files.map((file) => fileBlock(file, surface))].join('\n\n')+}++/**+ * The three fields a user message gets from its files: `content` is what the+ * model reads (typed text plus one block per file), `displayContent` is what+ * the user typed and what the bubble shows, `files` draws the chips and lets a+ * resend rebuild the message. Without files only `content` comes back, so a+ * message without attachments is stored exactly as before.+ */+export function fileMessageFields(+ typed: string,+ files: readonly FileAttachment[] | undefined,+ surface: 'chat' | 'workspace' = 'chat',+): { content: string; displayContent?: string; files?: FileAttachment[] } {+ if (!files?.length) return { content: typed }+ return { content: composeFileMessage(typed, files, surface), displayContent: typed, files: [...files] }+}++/**+ * The attachments of a send that has no working folder (plain chat, a group+ * round, Chat Tools). A path from an earlier Agent turn is dropped: this+ * surface has no tool that could open it, and the block must not say it has.+ */+export function filesWithoutWorkspace(inputs: readonly ChatFileInput[] | undefined): FileAttachment[] | undefined {+ if (!inputs?.length) return undefined+ return inputs.map(({ attachment }) => {+ const { workspacePath: _dropped, ...rest } = attachment+ return rest+ })+}++function toBase64(bytes: Uint8Array): string {+ let binary = ''+ for (let at = 0; at < bytes.length; at += 0x8000) {+ binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000))+ }+ return btoa(binary)+}++/** `rom.gba` taken: `rom (1).gba`, `rom (2).gba`, and so on. */+export function numberedFileName(name: string, n: number): string {+ if (n === 0) return name+ const dot = name.lastIndexOf('.')+ return dot > 0 ? `${name.slice(0, dot)} (${n})${name.slice(dot)}` : `${name} (${n})`+}++/** Where the working folder of a run is, in the words the fs commands take. */+export interface ChatFileWorkspace {+ chatId: string+ workingDirectory?: string+}++const TAKEN = /already exists/i++async function uploadFile(file: File, workspace: ChatFileWorkspace): Promise<string> {+ const name = cleanFileName(file.name)+ for (let n = 0; n < 50; n++) {+ const path = numberedFileName(name, n)+ try {+ let offset = 0+ do {+ const chunk = new Uint8Array(await file.slice(offset, offset + UPLOAD_CHUNK_BYTES).arrayBuffer())+ const last = offset + chunk.length >= file.size+ await backendCall('fs_write_bytes', { path, base64: toBase64(chunk), offset, last, ...workspace })+ offset += chunk.length+ } while (offset < file.size)+ return path+ } catch (err) {+ // The folder may be the user's real project. A name that is taken there+ // is never overwritten; the attachment gets the next free one.+ if (TAKEN.test(err instanceof Error ? err.message : String(err))) continue+ throw err+ }+ }+ throw new Error('No free file name in the working folder.')+}++/**+ * Copy the attached files into the working folder of an Agent or Code run.+ *+ * Never throws and never blocks the send: a file that cannot be copied (disk+ * full, a browser session without a backend, a resend of a message whose+ * bytes are long gone) keeps its description, and the block the model reads+ * says that only the summary is available. `failed` names those files so the+ * caller can tell the user.+ */+export async function placeChatFiles(+ inputs: readonly ChatFileInput[],+ workspace: ChatFileWorkspace,+): Promise<{ files: FileAttachment[]; failed: string[] }> {+ const files: FileAttachment[] = []+ const failed: string[] = []+ for (const { attachment, file } of inputs) {+ // Already in the folder: a resend, or the same message sent again.+ if (attachment.workspacePath || !file) {+ files.push(attachment)+ continue+ }+ try {+ files.push({ ...attachment, workspacePath: await uploadFile(file, workspace) })+ } catch (err) {+ log.warn('[chat-files] the attachment could not be copied into the working folder', { err: String(err) })+ failed.push(attachment.name)+ files.push(attachment)+ }+ }+ return { files, failed }+}++export function copyFailedMessage(names: readonly string[]): string {+ const list = names.map((name) => `"${name}"`).join(', ')+ return `${list} could not be copied into the working folder. The model only gets a summary of it.`+}diff --git a/src/lib/dev-fs-jail.ts b/src/lib/dev-fs-jail.tsindex 9e0f9d03..aea24646 100644--- a/src/lib/dev-fs-jail.ts+++ b/src/lib/dev-fs-jail.ts@@ -47,6 +47,10 @@ import { AGENT_WORKSPACE_DIR } from './app-identity'/** Read cap for one dev byte-read, mirroring READ_BYTES_CAP in filesystem.rs. */export const DEV_READ_BYTES_CAP = 16 * 1024 * 1024+/** The largest binary a chat attachment may be, the same number as+ * `WRITE_BYTES_CAP` in src-tauri/src/commands/filesystem.rs. */+export const DEV_WRITE_BYTES_CAP = 64 * 1024 * 1024+/*** Strip duplicate drive-letter prefixes (`D:/a/D:/a/f.txt` → `D:/a/f.txt`),* the port of `normalize_duplicate_drive_prefix`. Windows-only in practice;diff --git a/src/lib/file-magic.ts b/src/lib/file-magic.tsnew file mode 100644index 00000000..baeff0ed--- /dev/null+++ b/src/lib/file-magic.ts@@ -0,0 +1,209 @@+/**+ * What kind of file is this, read from its first bytes.+ *+ * A language model cannot open a binary, so the chat hands it a description+ * instead (lib/chat-files.ts). The most useful single line in that+ * description is the type, and the file extension is the weakest witness for+ * it: a `.bin` can be anything. The signature inside the file is checked+ * first, the extension only names what a signature cannot (a SNES ROM has no+ * magic number at all).+ *+ * Pure and synchronous: it looks at a byte window the caller already holds.+ */++interface Signature {+ /** Where the signature starts. */+ at: number+ bytes: readonly number[]+ label: string+ /** Two or three plain letters that an ordinary text can start with as well+ * ("BMW is ...", "MZ ..."). Such a signature only counts in a file that is+ * not text. */+ weak?: true+}++const text = (s: string): number[] => [...s].map((c) => c.charCodeAt(0))++/** The first eight bytes of the Nintendo logo, as a GBA and an NDS cartridge carry it. */+const GBA_LOGO = [0x24, 0xff, 0xae, 0x51, 0x69, 0x9a, 0xa2, 0x21]+/** The first eight bytes of the Nintendo logo in a Game Boy header. */+const GB_LOGO = [0xce, 0xed, 0x66, 0x66, 0xcc, 0x0d, 0x00, 0x0b]++/**+ * Ordered: the first match wins, so a container that shares its opening bytes+ * with a more specific format comes after it.+ */+const SIGNATURES: readonly Signature[] = [+ // Console ROMs first, the request that started this (applejames, Discord).+ { at: 0, bytes: [...text('NES'), 0x1a], label: 'NES ROM (iNES)' },+ { at: 4, bytes: GBA_LOGO, label: 'Game Boy Advance ROM' },+ { at: 0xc0, bytes: GBA_LOGO, label: 'Nintendo DS ROM' },+ { at: 0x104, bytes: GB_LOGO, label: 'Game Boy ROM' },+ { at: 0, bytes: [0x80, 0x37, 0x12, 0x40], label: 'Nintendo 64 ROM (big endian, .z64)' },+ { at: 0, bytes: [0x37, 0x80, 0x40, 0x12], label: 'Nintendo 64 ROM (byte swapped, .v64)' },+ { at: 0, bytes: [0x40, 0x12, 0x37, 0x80], label: 'Nintendo 64 ROM (little endian, .n64)' },+ { at: 0x100, bytes: text('SEGA'), label: 'Sega Mega Drive / Genesis ROM' },+ { at: 0x8001, bytes: text('CD001'), label: 'ISO 9660 disc image' },+ // Executables and bytecode.+ { at: 0, bytes: [0x7f, ...text('ELF')], label: 'ELF executable' },+ { at: 0, bytes: text('MZ'), label: 'Windows executable (PE)', weak: true },+ { at: 0, bytes: [0xcf, 0xfa, 0xed, 0xfe], label: 'Mach-O executable (64 bit)' },+ { at: 0, bytes: [0xce, 0xfa, 0xed, 0xfe], label: 'Mach-O executable (32 bit)' },+ { at: 0, bytes: [0x00, ...text('asm')], label: 'WebAssembly module' },+ { at: 0, bytes: [...text('dex'), 0x0a], label: 'Android DEX bytecode' },+ { at: 0, bytes: [0x1b, ...text('Lua')], label: 'Lua bytecode' },+ // Archives and containers.+ { at: 0, bytes: [...text('PK'), 0x03, 0x04], label: 'ZIP archive' },+ { at: 0, bytes: [0x1f, 0x8b], label: 'gzip archive' },+ { at: 0, bytes: [...text('7z'), 0xbc, 0xaf, 0x27, 0x1c], label: '7-Zip archive' },+ { at: 0, bytes: [...text('Rar!'), 0x1a, 0x07], label: 'RAR archive' },+ { at: 0, bytes: [0xfd, ...text('7zXZ'), 0x00], label: 'XZ archive' },+ { at: 0, bytes: text('BZh'), label: 'bzip2 archive', weak: true },+ { at: 0, bytes: [0x28, 0xb5, 0x2f, 0xfd], label: 'Zstandard archive' },+ { at: 257, bytes: text('ustar'), label: 'tar archive' },+ // Documents and data.+ { at: 0, bytes: text('%PDF'), label: 'PDF document' },+ { at: 0, bytes: [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1], label: 'Microsoft Office document (legacy)' },+ { at: 0, bytes: text('SQLite format 3'), label: 'SQLite database' },+ { at: 0, bytes: text('GGUF'), label: 'GGUF model file' },+ // Media.+ { at: 0, bytes: [0x89, ...text('PNG')], label: 'PNG image' },+ { at: 0, bytes: [0xff, 0xd8, 0xff], label: 'JPEG image' },+ { at: 0, bytes: text('GIF8'), label: 'GIF image' },+ { at: 0, bytes: text('BM'), label: 'BMP image', weak: true },+ { at: 0, bytes: text('ID3'), label: 'MP3 audio', weak: true },+ { at: 0, bytes: text('OggS'), label: 'Ogg media' },+ { at: 0, bytes: text('fLaC'), label: 'FLAC audio' },+ { at: 4, bytes: text('ftyp'), label: 'MP4 / QuickTime media' },+ { at: 0, bytes: [0x1a, 0x45, 0xdf, 0xa3], label: 'Matroska / WebM media' },+ // Fonts.+ { at: 0, bytes: text('wOFF'), label: 'WOFF font' },+ { at: 0, bytes: text('wOF2'), label: 'WOFF2 font' },+ { at: 0, bytes: text('OTTO'), label: 'OpenType font', weak: true },+ { at: 0, bytes: [0x00, 0x01, 0x00, 0x00, 0x00], label: 'TrueType font' },+]++/** What an extension says about a binary whose bytes carry no signature. */+const BY_EXTENSION: Readonly<Record<string, string>> = {+ sfc: 'SNES ROM',+ smc: 'SNES ROM',+ gb: 'Game Boy ROM',+ gbc: 'Game Boy Color ROM',+ gba: 'Game Boy Advance ROM',+ nds: 'Nintendo DS ROM',+ nes: 'NES ROM',+ z64: 'Nintendo 64 ROM',+ n64: 'Nintendo 64 ROM',+ v64: 'Nintendo 64 ROM',+ md: 'Sega Mega Drive / Genesis ROM',+ gen: 'Sega Mega Drive / Genesis ROM',+ sms: 'Sega Master System ROM',+ gg: 'Sega Game Gear ROM',+ pce: 'PC Engine ROM',+ a26: 'Atari 2600 ROM',+ rom: 'ROM image',+ iso: 'Disc image',+ img: 'Disk image',+ safetensors: 'Safetensors model file',+ dll: 'Windows library',+ so: 'Shared library',+ dylib: 'macOS library',+ class: 'Java class file',+ pyc: 'Python bytecode',+ dat: 'Data file',+ sav: 'Save file',+}++function matches(bytes: Uint8Array, sig: Signature): boolean {+ if (bytes.length < sig.at + sig.bytes.length) return false+ for (let i = 0; i < sig.bytes.length; i++) {+ if (bytes[sig.at + i] !== sig.bytes[i]) return false+ }+ return true+}++/** The lowercase extension without the dot, or '' when the name has none. */+export function fileExtension(name: string): string {+ const base = name.split(/[\\/]/).pop() ?? ''+ const dot = base.lastIndexOf('.')+ return dot > 0 ? base.slice(dot + 1).toLowerCase() : ''+}++/** A RIFF file names its content in bytes 8 to 11. */+function riffKind(bytes: Uint8Array): string | null {+ if (!matches(bytes, { at: 0, bytes: text('RIFF'), label: '' }) || bytes.length < 12) return null+ const form = String.fromCharCode(bytes[8], bytes[9], bytes[10], bytes[11])+ if (form === 'WAVE') return 'WAV audio'+ if (form === 'AVI ') return 'AVI video'+ if (form === 'WEBP') return 'WebP image'+ return 'RIFF container'+}++/**+ * 0xCAFEBABE opens both a Java class file and a universal Mach-O binary. The+ * next four bytes tell them apart: a class file carries its version there+ * (45 and up), a universal binary the number of architectures (a handful).+ */+function cafeBabeKind(bytes: Uint8Array): string | null {+ if (!matches(bytes, { at: 0, bytes: [0xca, 0xfe, 0xba, 0xbe], label: '' }) || bytes.length < 8) return null+ const next = (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7]+ return next >= 45 ? 'Java class file' : 'Mach-O universal binary'+}++/** A ZIP is also the shell of every modern Office file and of a few others. */+function zipKind(extension: string): string {+ const inner: Record<string, string> = {+ docx: 'Word document (.docx)',+ xlsx: 'Excel workbook (.xlsx)',+ pptx: 'PowerPoint presentation (.pptx)',+ odt: 'OpenDocument text',+ epub: 'EPUB book',+ jar: 'Java archive (.jar)',+ apk: 'Android package (.apk)',+ }+ return inner[extension] ?? 'ZIP archive'+}++/**+ * True when this window reads as text: valid UTF-8 without control bytes that+ * no text file carries. A window that ends in the middle of a multi-byte+ * character is still text, so the last few bytes may be an open sequence.+ */+export function looksLikeText(bytes: Uint8Array): boolean {+ if (bytes.length === 0) return false+ for (const b of bytes) {+ // Tab, line feed, form feed, carriage return and escape are fine.+ if (b < 0x20 && b !== 0x09 && b !== 0x0a && b !== 0x0c && b !== 0x0d && b !== 0x1b) return false+ }+ try {+ new TextDecoder('utf-8', { fatal: true }).decode(bytes, { stream: true })+ return true+ } catch {+ return false+ }+}++export interface FileKind {+ /** A short name a person recognises, for the chip and for the model. */+ label: string+ /** True when the content can be shown as text instead of as a hex dump. */+ isText: boolean+}++/**+ * The type of a file from the first bytes of it (give it at least the first+ * 33 KiB when the file is that long, the ISO 9660 signature sits at 0x8001)+ * and its name.+ */+export function detectFileKind(head: Uint8Array, name: string): FileKind {+ const extension = fileExtension(name)+ const special = riffKind(head) ?? cafeBabeKind(head)+ if (special) return { label: special, isText: false }+ const isText = looksLikeText(head)+ for (const sig of SIGNATURES) {+ if ((sig.weak && isText) || !matches(head, sig)) continue+ return { label: sig.label === 'ZIP archive' ? zipKind(extension) : sig.label, isText: false }+ }+ if (isText) return { label: extension ? `Text file (.${extension})` : 'Text file', isText: true }+ return { label: BY_EXTENSION[extension] ?? (extension ? `Binary file (.${extension})` : 'Binary file'), isText: false }+}diff --git a/src/lib/group-chat.ts b/src/lib/group-chat.tsindex 27ddd3cc..5999752e 100644--- a/src/lib/group-chat.ts+++ b/src/lib/group-chat.ts@@ -35,12 +35,85 @@ export function isGroupChat(groupModels: string[] | undefined): groupModels is sreturn Array.isArray(groupModels) && groupModels.length >= GROUP_CHAT_MIN}-export function groupSystemPrompt(model: string, allModels: string[], personaPrompt: string): string {- const others = allModels.filter((m) => m !== model).map((m) => `"${m}"`).join(', ')- const line =- `You are "${model}", one of several AI models answering in the same group conversation with ${others}. ` +- `What the other models said arrives as user messages that start with a [model-name] tag; the assistant messages are your own earlier turns. ` +- `Answer as yourself in your own voice, add something new, and do not repeat what another model already said.`+/**+ * Who sits at the table, and as whom (3.0.5, samvenice on Discord).+ *+ * Until now every model in a group answered under the ONE persona of the+ * chat, so two models were both told "You are Sherlock" and promptly spoke+ * over each other. Each participant can now have its own persona, picked next+ * to its name in the group menu and stored on the conversation+ * (`groupPersonas`, model name to persona id).+ *+ * A participant without an entry is exactly what it was before: it follows+ * the chat's own persona setting and is called by its model name. A persona+ * id that no longer exists (the persona was deleted) reads as no entry, so a+ * stale pick never leaves a participant without a role.+ */+export interface GroupSpeaker {+ /** The name the others see this participant under. */+ name: string+ /** Its own persona prompt, absent when it follows the chat's setting. */+ personaPrompt?: string+}++export function groupSpeakers(+ models: readonly string[],+ groupPersonas: Readonly<Record<string, string>> | undefined,+ personas: readonly { id: string; name: string; systemPrompt: string }[],+): Record<string, GroupSpeaker> {+ const picked = models.map((model) => {+ const id = groupPersonas?.[model]+ return { model, persona: id ? personas.find((p) => p.id === id) : undefined }+ })+ const speakers: Record<string, GroupSpeaker> = {}+ for (const { model, persona } of picked) {+ if (!persona) {+ speakers[model] = { name: model }+ continue+ }+ // Two participants on the same persona still need two names, or the tags+ // in the shared history could not tell them apart.+ const shared = picked.filter((other) => other.persona?.name === persona.name).length > 1+ speakers[model] = {+ name: shared ? `${persona.name} (${model})` : persona.name,+ personaPrompt: persona.systemPrompt,+ }+ }+ return speakers+}++/** True when at least one participant speaks as a persona of its own. */+export function hasOwnPersonas(speakers: Readonly<Record<string, GroupSpeaker>> | undefined): speakers is Record<string, GroupSpeaker> {+ return !!speakers && Object.values(speakers).some((s) => s.personaPrompt !== undefined)+}++export function groupSystemPrompt(+ model: string,+ allModels: string[],+ personaPrompt: string,+ /** From `groupSpeakers`. Without own personas the wording stays the one+ * every group has had since v1. */+ speakers?: Readonly<Record<string, GroupSpeaker>>,+): string {+ let line: string+ if (hasOwnPersonas(speakers)) {+ const nameOf = (m: string) => speakers[m]?.name ?? m+ const self = nameOf(model)+ const others = allModels.filter((m) => m !== model).map((m) => `"${nameOf(m)}"`).join(', ')+ // The role belongs to ONE participant. Saying so, and naming the others,+ // is what keeps a model from answering as the character next to it.+ line =+ `In this group conversation you are "${self}" and only "${self}". The other participants are ${others}. ` ++ `What they said arrives as user messages that start with a [name] tag; the assistant messages are your own earlier turns. ` ++ `Stay in your own role: never speak as another participant and never write their lines. ` ++ `Add something new, and do not repeat what another participant already said.`+ } else {+ const others = allModels.filter((m) => m !== model).map((m) => `"${m}"`).join(', ')+ line =+ `You are "${model}", one of several AI models answering in the same group conversation with ${others}. ` ++ `What the other models said arrives as user messages that start with a [model-name] tag; the assistant messages are your own earlier turns. ` ++ `Answer as yourself in your own voice, add something new, and do not repeat what another model already said.`+ }return personaPrompt ? `${personaPrompt}\n\n${line}` : line}@@ -91,14 +164,20 @@ export function stripImpersonatedSpeakers(text: string, otherModels: string[]):* above say who is talking, which is how attribution worked all along. It* also fixes round one for the second speaker, whose prompt used to end on* somebody else's assistant turn and asked it to carry on mid-sentence. */-export function groupHistory(messages: Message[], model: string): GroupWireMessage[] {+export function groupHistory(+ messages: Message[],+ model: string,+ /** From `groupSpeakers`: a participant with its own persona is tagged with+ * that name, everyone else with the model name as before. */+ speakers?: Readonly<Record<string, GroupSpeaker>>,+): GroupWireMessage[] {return messages.filter((m) => m.role !== 'system' && m.content.trim() !== '').map((m) => {const foreign = m.role === 'assistant' && !!m.modelId && m.modelId !== modelreturn {role: (foreign ? 'user' : m.role) as GroupWireMessage['role'],- content: foreign ? `[${m.modelId}] ${m.content}` : m.content,+ content: foreign ? `[${speakers?.[m.modelId!]?.name ?? m.modelId}] ${m.content}` : m.content,...(m.images?.length ? { images: m.images.map((i) => ({ data: i.data, mimeType: i.mimeType })) } : {}),}})diff --git a/src/lib/resend-plan.ts b/src/lib/resend-plan.tsindex a3b90b6a..f4924626 100644--- a/src/lib/resend-plan.ts+++ b/src/lib/resend-plan.ts@@ -1,4 +1,4 @@-import type { ImageAttachment, Message } from '../types/chat'+import type { FileAttachment, ImageAttachment, Message } from '../types/chat'/*** What has to leave the thread before a turn is sent again — Regenerate and@@ -18,9 +18,12 @@ export interface ResendPlan {/** Exactly what sendMessage receives as the user's input. */content: stringimages?: ImageAttachment[]+ /** The files the question carried. Their summaries travel with them, so the+ * resend rebuilds the same message without the bytes. */+ files?: FileAttachment[]}-type ThreadMessage = Pick<Message, 'id' | 'role' | 'content' | 'displayContent' | 'images'>+type ThreadMessage = Pick<Message, 'id' | 'role' | 'content' | 'displayContent' | 'images' | 'files'>export function planResend(messages: ThreadMessage[],@@ -44,11 +47,17 @@ export function planResend(// ("/review"), so that is what goes back in — sendMessage expands it again.// Any other displayContent is a label, not input: the /loop driver writes// "pass 3 of 5" there over the instruction the model actually ran.- const typed = anchor.displayContent?.startsWith('/') ? anchor.displayContent : anchor.content+ // A message with files keeps what the user typed in displayContent as well:+ // its content is that text PLUS the file summaries, and sending the content+ // back in would put the summaries into the question a second time.+ const typed = anchor.displayContent !== undefined && (anchor.files?.length || anchor.displayContent.startsWith('/'))+ ? anchor.displayContent+ : anchor.contentreturn {deleteFromId: anchor.id,content: override ?? typed,...(anchor.images?.length ? { images: anchor.images } : {}),+ ...(anchor.files?.length ? { files: anchor.files } : {}),}}diff --git a/src/stores/chatNoticeStore.ts b/src/stores/chatNoticeStore.tsindex f0bd5f29..5034e6ab 100644--- a/src/stores/chatNoticeStore.ts+++ b/src/stores/chatNoticeStore.ts@@ -34,7 +34,7 @@ import { useChatStore } from './chatStore'/** Die Zeilen, die es gibt. Kein freier Schluessel: eine Aufzaehlung laesst* sich nachzaehlen, ein String-Schluessel waechst unbemerkt. */-export type ChatNoticeId = 'attachment-is-not-an-image' | 'model-cannot-see-images' | 'image-attach' | 'agent-outside-workspace' | 'agent-for-local-files'+export type ChatNoticeId = 'document-belongs-in-docs' | 'model-cannot-see-images' | 'image-attach' | 'file-attach' | 'agent-outside-workspace' | 'agent-for-local-files'export interface ChatNotice {id: ChatNoticeId@@ -51,8 +51,8 @@ interface ChatNoticeState {/*** Zeigen. Derselbe Name zweimal ersetzt die Zeile, statt sie zu stapeln.*- * `ttlMs` ist fuer Zeilen ueber ein EREIGNIS ("der Clip hat dein PDF nicht- * genommen"): die sind nach dem Lesen erledigt. Eine Zeile ueber einen+ * `ttlMs` ist fuer Zeilen ueber ein EREIGNIS ("diese Datei ist zu gross"):+ * die sind nach dem Lesen erledigt. Eine Zeile ueber einen* ZUSTAND ("dieses Modell sieht keine Bilder") bekommt keine Uhr, sonst* ginge sie weg, waehrend sie noch stimmt; sie wird von dem geraeumt, der* sie gesetzt hat, sobald der Zustand endet.diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 107db604..50f4c7c0 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -6,6 +6,7 @@ import type { AgentBlock } from '../types/agent-mode'import { clampSampling, type SamplingOverrides } from '../lib/sampling'import { idbStorage } from '../lib/idbStorage'import { externalizeConversations, hasInlineImages } from '../lib/chat-attachments'+import { FILE_ONLY_TEXT } from '../lib/chat-files'import { holdBackup, releaseBackup } from '../lib/backup-hold'import { coalescedJSONStorage } from '../lib/coalescedStorage'import { migrateBlockInPlace } from '../api/agents/block-helpers'@@ -142,6 +143,9 @@ interface ChatState {resetConversationSampling: (id: string) => void/** Group chat v1: the models that answer in turn (capped at 4). */setGroupModels: (id: string, models: string[]) => void+ /** Group chat: the persona ONE participant speaks as in this chat, or+ * `null` to let it follow the chat's own persona setting again. */+ setGroupPersona: (id: string, model: string, personaId: string | null) => void/** Write the model the open chat is actually running on.** Befund 4 of the abnahme counter-check (2026-08-29): switching the model@@ -295,6 +299,19 @@ const CODEX_DEFAULT_TITLE = 'Coding Agent'* vergessener Fall, und code-sessions-heissen-verschieden.test.ts haelt sie* fest, damit sie es bleibt.*/+/**+ * The name a chat takes from its first user message.+ *+ * A message with attached files carries their summaries in `content`, for the+ * model. The title comes from what the user typed, and when nothing was typed+ * from the name of the first file, never from a hex dump.+ */+function titleFromMessage(message: Message): string {+ if (!message.files?.length) return message.content.slice(0, 50)+ const typed = (message.displayContent ?? '').trim()+ return (typed && typed !== FILE_ONLY_TEXT ? typed : message.files[0].name).slice(0, 50)+}+function isStillDefaultTitle(title: string): boolean {return title === NEW_CHAT_TITLE || title === CODEX_DEFAULT_TITLE}@@ -412,9 +429,34 @@ export const useChatStore = create<ChatState>()(setGroupModels: (id, models) =>set((state) => ({- conversations: state.conversations.map((c) =>- c.id === id ? { ...c, groupModels: models.slice(0, 4), updatedAt: Date.now() } : c- ),+ conversations: state.conversations.map((c) => {+ if (c.id !== id) return c+ const groupModels = models.slice(0, 4)+ const next = { ...c, groupModels, updatedAt: Date.now() }+ // A model that left the group takes its persona pick with it, so+ // the pick does not come back as a surprise when the model is+ // added again weeks later.+ const kept = Object.entries(c.groupPersonas ?? {}).filter(([model]) => groupModels.includes(model))+ if (kept.length > 0) next.groupPersonas = Object.fromEntries(kept)+ else delete next.groupPersonas+ return next+ }),+ })),++ setGroupPersona: (id, model, personaId) =>+ set((state) => ({+ conversations: state.conversations.map((c) => {+ if (c.id !== id) return c+ const personas = { ...(c.groupPersonas ?? {}) }+ if (personaId) personas[model] = personaId+ else delete personas[model]+ const next = { ...c, updatedAt: Date.now() }+ // No pick left: the field goes, so the chat is stored exactly as a+ // group from before this feature.+ if (Object.keys(personas).length > 0) next.groupPersonas = personas+ else delete next.groupPersonas+ return next+ }),})),setActiveConversationModel: (model) =>@@ -452,7 +494,7 @@ export const useChatStore = create<ChatState>()(updatedAt: Date.now(),title:isStillDefaultTitle(c.title) && message.role === 'user'- ? message.content.slice(0, 50)+ ? titleFromMessage(message): c.title,}: cdiff --git a/src/types/chat.ts b/src/types/chat.tsindex 412fa640..c2f878a7 100644--- a/src/types/chat.ts+++ b/src/types/chat.ts@@ -9,6 +9,31 @@ export interface ImageAttachment {name: string // filename}+/**+ * A file of any kind attached to a user message (3.0.5).+ *+ * A language model cannot read bytes, so the file itself is NOT in the chat:+ * no base64, no reference to a stored copy. What is kept is what the model was+ * given in its place (`summary`, a few kilobytes at most) and, in Agent and+ * Code, where the file was put in the chat's working folder so the file tools+ * can work on it. See lib/chat-files.ts.+ */+export interface FileAttachment {+ name: string+ /** Size of the file in bytes. */+ size: number+ /** The type read from the first bytes, e.g. "Game Boy Advance ROM". */+ kind: string+ /** Lowercase hex SHA-256 of the whole file. */+ sha256: string+ /** What the model reads instead of the bytes: a hex dump of the start and+ * the readable strings, or the start of the text for a text file. */+ summary: string+ /** Path inside the chat's working folder, set once the file was put there+ * (Agent and Code only). */+ workspacePath?: string+}+/*** A chat-tools "artifact": a file the model produced in PLAIN chat. In chat* mode `file_write` does NOT touch disk (ChatGPT-style) — the content lands in@@ -46,6 +71,10 @@ export interface Message {modelId?: stringtimestamp: numberimages?: ImageAttachment[]+ /** Files attached to this user message. `content` already carries their+ * summaries for the model, `displayContent` holds what the user typed, and+ * this list draws the chips and lets a resend rebuild the message. */+ files?: FileAttachment[]sources?: { documentName: string; chunkIndex: number; preview: string }[]// Agent Mode fieldsagentBlocks?: AgentBlock[]@@ -142,6 +171,11 @@ export interface Conversation {/** Group chat v1: two to four models that answer in turn on every user* message. Fewer than two entries means a normal single-model chat. */groupModels?: string[]+ /** Group chat: the persona each participant speaks as, model name to+ * persona id (3.0.5, samvenice on Discord). A model without an entry+ * follows the chat's own persona setting, which is how every group worked+ * before this field existed. */+ groupPersonas?: Record<string, string>/*** Compactions that have happened in this chat, oldest first. Only the NEWEST* one shapes the payload — each summary already covers everything before its