Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Add local project task attachments and safe conversation moves
BlueSkyID666b0d5f82f8a5b
diff --git a/src/core-agent/src/tools/project-tasks-tool.ts b/src/core-agent/src/tools/project-tasks-tool.tsindex 92d8f39c..cb8df062 100644--- a/src/core-agent/src/tools/project-tasks-tool.ts+++ b/src/core-agent/src/tools/project-tasks-tool.ts@@ -28,6 +28,7 @@ export interface ProjectTaskView {is_current_run?: boolean;owner_agent?: string;depends_on?: string[];+ attachments?: string[];result_ref?: string;origin_cid?: string;created_by?: string;@@ -40,15 +41,24 @@ export interface ProjectTasksProgress { total: number; done: number; open: numbeexport interface ProjectTasksQuery { offset?: number; limit?: number; status?: ProjectTaskStatus; }+export interface ProjectTaskMutationReceipt {+ ok: boolean;+ error?: string;+ task?: ProjectTaskView;+ ignored_fields?: string[];+}+export interface ProjectTasksToolHandler {+ delete?(taskId: string): Promise<{ ok: boolean; error?: string; task_id?: string; deleted?: boolean }>;+ addAttachment?(taskId: string, sourcePath: string): Promise<ProjectTaskMutationReceipt>;list(query?: ProjectTasksQuery): Promise<{ ok: boolean; tasks: ProjectTaskView[]; progress: ProjectTasksProgress; total: number; next_offset: number | null }>;get(taskId: string): Promise<{ ok: boolean; error?: string; task?: ProjectTaskView }>;create(input: {content?: string; title?: string; detail?: string; owner?: string; status?: ProjectTaskStatus;- }): Promise<{ ok: boolean; error?: string; task?: ProjectTaskView; alreadyExists?: boolean }>;+ }): Promise<ProjectTaskMutationReceipt & { alreadyExists?: boolean }>;update(taskId: string, patch: {content?: string; title?: string; detail?: string; status?: ProjectTaskStatus; owner?: string; result_ref?: string;- }): Promise<{ ok: boolean; error?: string; task?: ProjectTaskView }>;+ }): Promise<ProjectTaskMutationReceipt>;complete(taskId: string, resultRef?: string): Promise<{ ok: boolean; error?: string; task?: ProjectTaskView }>;}@@ -76,7 +86,7 @@ export interface CreateProjectTasksToolOptions {const READONLY_NOTE = `\n\nNOTE: this backlog is READ-ONLY for you. You can list/get tasks; deliver your result to the dispatching agent for a status update.`;-type ProjectTaskAction = 'list_projects' | 'list' | 'get' | 'create' | 'update' | 'complete';+type ProjectTaskAction = 'list_projects' | 'list' | 'get' | 'create' | 'update' | 'complete' | 'add_attachment' | 'delete';// Legacy text keys remain input-only compatibility; new schemas advertise content.const PROJECT_TASK_ACTION_FIELDS: Readonly<Record<ProjectTaskAction, ReadonlySet<string>>> = {@@ -86,6 +96,8 @@ const PROJECT_TASK_ACTION_FIELDS: Readonly<Record<ProjectTaskAction, ReadonlySetcreate: new Set(['action', 'content', 'title', 'detail', 'status', 'owner']),update: new Set(['action', 'task_id', 'content', 'title', 'detail', 'status', 'owner', 'result_ref']),complete: new Set(['action', 'task_id', 'result_ref']),+ add_attachment: new Set(['action', 'task_id', 'source_path']),+ delete: new Set(['action', 'task_id']),};export function createProjectTasksTool(source: ProjectTasksToolHandler | ProjectTasksProjectSelector, opts: CreateProjectTasksToolOptions = {}): AgentTool {@@ -93,7 +105,7 @@ export function createProjectTasksTool(source: ProjectTasksToolHandler | Projectconst selector = 'resolveProject' in source ? source : undefined;if (readOnly && selector) throw new Error('Restricted project tasks require a bound project handler');const actions = readOnly ? ['list', 'get'] : [- ...(selector ? ['list_projects'] : []), 'list', 'get', 'create', 'update', 'complete',+ ...(selector ? ['list_projects'] : []), 'list', 'get', 'create', 'update', 'complete', 'add_attachment', 'delete',];return {name: 'todo_tasks',@@ -107,7 +119,7 @@ export function createProjectTasksTool(source: ProjectTasksToolHandler | Projectaction: {type: 'string',enum: actions,- description: 'list: tasks with content, matching total, next_offset, project-wide progress; get: full record. complete requires verified delivery. Omit unrelated fields.'+ description: 'list: tasks with content, paging and progress; get: full task. complete needs verified delivery. Known unused fields appear in ignored_fields; scope/status conflicts fail.'+ (selector? ' Task actions need project; list_projects takes no extras.': ''),@@ -116,13 +128,14 @@ export function createProjectTasksTool(source: ProjectTasksToolHandler | Projectproject: { type: 'string', minLength: 1, description: 'Exact project name or project_id from list_projects. Required for task actions; ambiguous names need an explicit id.' },} : {}),...(opts.globalScope ? { project: { type: 'string', enum: ['__global__'] } } : {}),- task_id: { type: 'string', minLength: 1, description: 'Target task id (required for get, update and complete).' },+ task_id: { type: 'string', minLength: 1, description: 'Required for get/update/complete/add_attachment/delete. Omit for list/create; ignored if supplied, reported in ignored_fields. Created task ids come from the result. delete also removes attachments.' },offset: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: 'List only; default 0. Continue with next_offset until null, keeping the same filters.' },limit: { type: 'integer', minimum: 1, maximum: 50, description: 'List only; default 20. Pages may be smaller to bound result size.' },content: { type: 'string', minLength: 1, maxLength: 4000, description: 'Complete work to be done, including requirements. Required for create; replaces the entire content on update.' },owner: { type: 'string', description: "Owner agent DISPLAY NAME (as shown in the agents list), not an id." },status: { type: 'string', enum: [...TASK_STATUSES], description: "List: filter by state; omitted includes all. Create/update: follow the run's target status. done requires verified delivery; review awaits required human approval. Keep failed or unverified work open." },result_ref: { type: 'string', description: "Delivering conversation, artifact, or file reference. In a Project conversation, save produced project files with library_save and use its returned path; outside one, use the file path." },+ ...(!readOnly ? { source_path: { type: 'string', minLength: 1, description: 'For add_attachment, supply task_id and the absolute path of a file in the current workspace or conversation attachments. Copies into the task using its filename; existing names are rejected. Maximum 200 MiB.' } } : {}),},required: ['action'],},@@ -141,10 +154,10 @@ export function createProjectTasksTool(source: ProjectTasksToolHandler | Projectif (opts.globalScope && input.project !== undefined && input.project !== '__global__') return fail('project_scope_mismatch');if (action === 'list_projects' && input.project !== undefined) return fail('list_projects does not accept a project filter');if (!selector && !opts.globalScope && input.project !== undefined) return fail('project_scope_mismatch');- if (action === 'complete' && input.status !== undefined && input.status !== 'done') return fail('complete conflicts with status; omit status or use done');- if (action === 'create' && input.task_id !== undefined) return fail('create cannot target an existing task; use update');- // A task selector on a list is a meaningful filter, not harmless metadata.- if (action === 'list' && input.task_id !== undefined) return fail('list does not accept task_id; use get');+ if (action === 'complete' && input.status !== undefined && input.status !== 'done') return fail('complete conflicts with status; only done is valid');+ // The selected action owns the effective fields; report every known+ // unused key so the model never mistakes a dropped argument for a filter.+ const ignoredFields = Object.keys(input).filter((key) => !allowedFields.has(key)).sort();const knownFields = new Set(Object.values(PROJECT_TASK_ACTION_FIELDS).flatMap((fields) => [...fields]));if (selector || opts.globalScope) knownFields.add('project');const unrelated = Object.keys(input).filter((key) => !knownFields.has(key));@@ -157,6 +170,7 @@ export function createProjectTasksTool(source: ProjectTasksToolHandler | Projectconst status = typeof input.status === 'string' ? input.status as ProjectTaskStatus : undefined;const owner = typeof input.owner === 'string' ? input.owner : undefined;const resultRef = typeof input.result_ref === 'string' ? input.result_ref : undefined;+ if (action === 'add_attachment' && (typeof input.source_path !== 'string' || !input.source_path.trim())) return fail('source_path is required for add_attachment');for (const field of ['content', 'title', 'detail', 'owner', 'result_ref']) {if (input[field] !== undefined && typeof input[field] !== 'string') return fail(`${field} must be a string`);@@ -170,19 +184,21 @@ export function createProjectTasksTool(source: ProjectTasksToolHandler | Projecttry {if (selector && action === 'list_projects') {- return { content: JSON.stringify({ ok: true, projects: await selector.listProjects() }) };+ return { content: JSON.stringify({ ok: true, projects: await selector.listProjects(),+ ...(ignoredFields.length ? { ignored_fields: ignoredFields } : {}),+ }) };}// Validate call prerequisites before project lookup or any mutation.const text = content !== undefined ? content : [title, detail].filter(Boolean).join('\n');if (action === 'create' && !text.trim()) return fail('"content" is required for create');if (content !== undefined && !content.trim()) return fail('content must not be empty');if (text.trim().length > 4000) return fail('content must be at most 4000 characters');- if (['get', 'update', 'complete'].includes(action) && !taskId.trim()) return fail('"task_id" is required for get, update and complete');+ if (['get', 'update', 'complete', 'add_attachment', 'delete'].includes(action) && !taskId.trim()) return fail(`"task_id" is required for ${action}`);let handler: ProjectTasksToolHandler;let project: ProjectTaskProject | undefined;if (selector) {const reference = typeof input.project === 'string' ? input.project.trim() : '';- if (!reference) return fail('"project" is required; use an exact name or list_projects to find its id');+ if (!reference) return fail('"project" is required and must be an exact project name or id');const selected = await selector.resolveProject(reference);if (!selected.ok) return { content: JSON.stringify(selected), isError: true };handler = selected.handler;@@ -190,18 +206,28 @@ export function createProjectTasksTool(source: ProjectTasksToolHandler | Project} else {handler = source as ProjectTasksToolHandler;}- const result = (r: { ok: boolean }): ToolResult => ({- content: JSON.stringify({ ...r, ...(project ? { project } : {}) }),- isError: !r.ok,- });+ const result = (r: { ok: boolean; ignored_fields?: string[] }): ToolResult => {+ const allIgnoredFields = [...new Set([...ignoredFields, ...(r.ignored_fields || [])])].sort();+ return {+ content: JSON.stringify({ ...r, ...(project ? { project } : {}), ...(allIgnoredFields.length ? { ignored_fields: allIgnoredFields } : {}) }),+ isError: !r.ok,+ };+ };switch (action) {+ case 'delete': return handler.delete+ ? result(await handler.delete(taskId))+ : fail('task deletion is unavailable in this host');+ case 'add_attachment': return handler.addAttachment+ ? result(await handler.addAttachment(taskId, input.source_path as string))+ : fail('task attachments are unavailable in this host');case 'list': {const r = await handler.list({ offset: input.offset as number | undefined, limit: input.limit as number | undefined, status });return result(r);}case 'get': return result(await handler.get(taskId));case 'create': {- const r = await handler.create({ ...(content !== undefined ? { content } : { title, detail }), owner, status });+ const r = await handler.create({ ...(content !== undefined ? { content } : { title, detail }), owner,+ status });const receipt = r.ok? {...r,@@ -211,7 +237,8 @@ export function createProjectTasksTool(source: ProjectTasksToolHandler | Projectreturn result(receipt);}case 'update': {- const r = await handler.update(taskId, { ...(content !== undefined ? { content } : { title, detail }), status, owner, result_ref: resultRef });+ const r = await handler.update(taskId, { ...(content !== undefined ? { content } : { title, detail }), status, owner,+ result_ref: resultRef });return result(r);}case 'complete': {diff --git a/src/core-agent/test/project-tasks-tool.test.ts b/src/core-agent/test/project-tasks-tool.test.tsindex bd12e741..a4dbbae5 100644--- a/src/core-agent/test/project-tasks-tool.test.ts+++ b/src/core-agent/test/project-tasks-tool.test.ts@@ -17,6 +17,43 @@ function stubHandler(): { handler: ProjectTasksToolHandler; calls: any[] } {}describe('todo_tasks tool', () => {+ it('deletes only an explicitly identified task in the writable scope', async () => {+ const { handler } = stubHandler();+ const deleted: string[] = [];+ handler.delete = async (id) => { deleted.push(id); return { ok: true, task_id: id, deleted: true }; };+ const tool = createProjectTasksTool(handler);+ for (const input of [{ action: 'delete' }, { action: 'delete', task_id: '' },+ { action: 'delete', task_id: 't_a', project: 'foreign' }]) {+ expect((await tool.execute(input, ctx)).isError).toBe(true);+ }+ expect((await createProjectTasksTool(handler, { readOnly: true }).execute({ action: 'delete', task_id: 't_a' }, ctx)).isError).toBe(true);+ expect(deleted).toEqual([]);+ const result = await tool.execute({ action: 'delete', task_id: 't_a' }, ctx);+ expect(result.isError).toBe(false);+ expect(JSON.parse(result.content)).toEqual({ ok: true, task_id: 't_a', deleted: true });+ expect(deleted).toEqual(['t_a']);+ });++ it('adds a file to an existing task and rejects missing operands, foreign scope and read-only writes', async () => {+ const { handler } = stubHandler();+ const calls: unknown[] = [];+ Object.assign(handler, { addAttachment: async (id: string, source: string) => {+ calls.push([id, source]);+ return { ok: true, task: { id, content: 'Review document', status: 'todo', attachments: ['brief.txt'] } };+ } });+ const tool = createProjectTasksTool(handler);+ const args = { action: 'add_attachment', task_id: 't_a', source_path: '/workspace/brief.txt' };+ const added = await tool.execute(args, ctx);+ expect(added.isError).toBeFalsy();+ expect(JSON.parse(added.content).task.attachments).toEqual(['brief.txt']);+ expect(calls).toEqual([['t_a', '/workspace/brief.txt']]);+ for (const bad of [{ ...args, task_id: '' }, { ...args, source_path: '' },+ { ...args, source_path: 42 }, { ...args, project: 'foreign' }]) {+ expect((await tool.execute(bad, ctx)).isError).toBe(true);+ }+ expect((await createProjectTasksTool(handler, { readOnly: true }).execute(args, ctx)).isError).toBe(true);+ expect(calls).toHaveLength(1);+ });it('accepts paged status queries and read-only detail retrieval, rejecting invalid query fields before IO', async () => {const { handler, calls } = stubHandler();const tool = createProjectTasksTool(handler, { readOnly: true });@@ -30,7 +67,6 @@ describe('todo_tasks tool', () => {{ action: 'list', limit: 0 }, { action: 'list', limit: 51 },{ action: 'list', limit: '20' }, { action: 'list', status: 'blocked' },{ action: 'get' }, { action: 'get', task_id: ' ' },- { action: 'list', task_id: 't_a' },]) expect((await tool.execute(args, ctx)).isError).toBe(true);expect(calls).toEqual([]);});@@ -41,6 +77,51 @@ describe('todo_tasks tool', () => {expect(res.isError).toBeFalsy();expect(calls[0][0]).toBe('list');expect(res.content).toContain('t_a');+ expect(JSON.parse(res.content)).not.toHaveProperty('ignored_fields');+ });++ it('reports other known fields omitted by the selected action without changing its effective inputs', async () => {+ const { handler, calls } = stubHandler();+ const tool = createProjectTasksTool(handler);+ const result = await tool.execute({ action: 'list', status: 'review', content: 'private unused work', owner: 'Writer' }, ctx);+ expect(result.isError).toBeFalsy();+ expect(JSON.parse(result.content).ignored_fields).toEqual(['content', 'owner']);+ expect(result.content).not.toContain('private unused work');+ expect(calls).toEqual([['list', { offset: undefined, limit: undefined, status: 'review' }]]);+ });++ it('ignores task_id on list/create, reports only its name, and preserves effective arguments', async () => {+ for (const task_id of ['x', '.', 't_a', '', ' ', null, 123, { private: 'unused' }]) {+ const { handler, calls } = stubHandler();+ const tool = createProjectTasksTool(handler);+ const listed = await tool.execute({ action: 'list', task_id, status: 'review', offset: 2, limit: 3 }, ctx);+ expect(listed.isError).toBeFalsy();+ expect(JSON.parse(listed.content)).toMatchObject({ ok: true, ignored_fields: ['task_id'], tasks: [{ id: 't_a' }] });+ const created = await tool.execute({ action: 'create', task_id, content: 'New work', owner: 'Writer', status: 'progress' }, ctx);+ expect(created.isError).toBeFalsy();+ expect(JSON.parse(created.content)).toMatchObject({+ ok: true, ignored_fields: ['task_id'], outcome: 'task_created', task: { id: 't_new' },+ });+ expect(calls).toEqual([+ ['list', { status: 'review', offset: 2, limit: 3 }],+ ['create', { content: 'New work', owner: 'Writer', status: 'progress' }],+ ]);+ }+ });++ it('does not let an ignored task_id bypass scope, input validation or handler failures', async () => {+ const { handler, calls } = stubHandler();+ const tool = createProjectTasksTool(handler, { globalScope: true });+ for (const input of [+ { action: 'list', project: 'foreign' }, { action: 'create', project: 'foreign', content: 'Work' },+ { action: 'list', status: 'invalid' }, { action: 'list', offset: -1 },+ { action: 'create' }, { action: 'create', content: 'Work', unknown: true },+ ]) expect((await tool.execute({ ...input, task_id: 'x' }, ctx)).isError).toBe(true);+ expect(calls).toEqual([]);+ handler.create = async () => ({ ok: false, error: 'owner_not_bound' });+ const failed = await tool.execute({ action: 'create', task_id: 'x', content: 'Work' }, ctx);+ expect(failed.isError).toBe(true);+ expect(JSON.parse(failed.content)).toEqual({ ok: false, error: 'owner_not_bound', ignored_fields: ['task_id'] });});it('keeps backlog selection and untrusted-data safety visible without assuming a preloaded list', () => {@@ -61,7 +142,7 @@ describe('todo_tasks tool', () => {const schema = tool.inputSchema as any;expect(schema.additionalProperties).toBe(false);expect(schema.oneOf).toBeUndefined();- expect(schema.properties.action.description).toContain('Omit unrelated fields');+ expect(schema.properties.action.description).toContain('ignored_fields');const result = await tool.execute({ action: 'complete', task_id: 't_9', status: 'done' }, ctx);expect(result.isError).toBeFalsy();@@ -95,12 +176,13 @@ describe('todo_tasks tool', () => {alreadyExists: true,});const res = await createProjectTasksTool(handler).execute(- { action: 'create', content: 'do X' }, ctx);+ { action: 'create', content: 'do X', task_id: 'x' }, ctx);expect(res.isError).toBeFalsy();expect(JSON.parse(res.content)).toMatchObject({ok: true,alreadyExists: true,outcome: 'existing_task_reused',+ ignored_fields: ['task_id'],task: { id: 't_existing' },});});@@ -116,11 +198,17 @@ describe('todo_tasks tool', () => {});});- it('update and complete require task_id', async () => {- const { handler } = stubHandler();+ it('reports the failing action and constraint without prescribing another action', async () => {+ const { handler, calls } = stubHandler();const tool = createProjectTasksTool(handler);- expect((await tool.execute({ action: 'update', status: 'done' }, ctx)).isError).toBe(true);- expect((await tool.execute({ action: 'complete' }, ctx)).isError).toBe(true);+ for (const action of ['get', 'update', 'complete']) {+ const result = await tool.execute({ action, ...(action === 'update' ? { status: 'done' } : {}) }, ctx);+ expect(result.isError).toBe(true);+ expect(JSON.parse(result.content).error).toBe(`"task_id" is required for ${action}`);+ }+ const conflict = await tool.execute({ action: 'complete', task_id: 't_a', status: 'progress' }, ctx);+ expect(JSON.parse(conflict.content).error).toBe('complete conflicts with status; only done is valid');+ expect(calls).toEqual([]);});it('complete forwards task_id + result_ref', async () => {@@ -167,7 +255,7 @@ describe('todo_tasks tool › task management by named Agents and CLI executors'const { handler, calls } = stubHandler();const tool = createProjectTasksTool(handler);const schema = tool.inputSchema as any;- expect(schema.properties.action.enum).toEqual(['list', 'get', 'create', 'update', 'complete']);+ expect(schema.properties.action.enum).toEqual(['list', 'get', 'create', 'update', 'complete', 'add_attachment', 'delete']);expect(schema.properties).not.toHaveProperty('project');for (const field of ['content', 'owner']) expect(schema.properties).toHaveProperty(field);expect((await tool.execute({ action: 'update', task_id: 't_1', status: 'review', result_ref: 'artifact-1' }, ctx)).isError).toBeFalsy();@@ -228,7 +316,7 @@ describe('todo_tasks tool › read-only workers', () => {it('commander (default, readOnly omitted) keeps full write access', async () => {const { handler, calls } = stubHandler();const tool = createProjectTasksTool(handler);- expect((tool.inputSchema as any).properties.action.enum).toEqual(['list', 'get', 'create', 'update', 'complete']);+ expect((tool.inputSchema as any).properties.action.enum).toEqual(['list', 'get', 'create', 'update', 'complete', 'add_attachment', 'delete']);const res = await tool.execute({ action: 'create', content: 'do X' }, ctx);expect(res.isError).toBeFalsy();expect(calls[0][0]).toBe('create');@@ -251,11 +339,15 @@ describe('todo_tasks tool › explicit project selection', () => {expect((tool.inputSchema as any).properties.action.description).not.toMatch(/already injected/i);const discovery = await tool.execute({ action: 'list_projects' }, ctx);expect(JSON.parse(discovery.content)).toEqual({ ok: true, projects: [project] });+ const redundantDiscovery = await tool.execute({ action: 'list_projects', content: 'unused' }, ctx);+ expect(JSON.parse(redundantDiscovery.content)).toEqual({+ ok: true, projects: [project], ignored_fields: ['content'],+ });expect(references).toEqual([]);- const created = await tool.execute({ action: 'create', project: 'Launch', content: 'Ship it' }, ctx);+ const created = await tool.execute({ action: 'create', project: 'Launch', content: 'Ship it', task_id: 'x' }, ctx);expect(references).toEqual(['Launch']);expect(JSON.parse(created.content)).toMatchObject({- ok: true, project, outcome: 'task_created', task: { content: 'Ship it' },+ ok: true, project, outcome: 'task_created', task: { content: 'Ship it' }, ignored_fields: ['task_id'],});expect(calls).toHaveLength(1);});@@ -349,7 +441,6 @@ it('validates only effective task parameters, preserving the bound target', asynconst tool = createProjectTasksTool(handler);expect((await tool.execute({ action: 'get', task_id: 't_a', limit: 'unused', content: {} }, ctx)).isError).toBeFalsy();expect(calls).toEqual([['get', 't_a']]);- expect((await tool.execute({ action: 'create', task_id: 't_a', content: 'new' }, ctx)).isError).toBe(true);expect((await tool.execute({ action: 'complete', task_id: 't_a', project: 'foreign' }, ctx)).isError).toBe(true);expect(calls).toHaveLength(1);});diff --git a/src/main/features/agents.ts b/src/main/features/agents.tsindex 63906983..4c3c60d3 100644--- a/src/main/features/agents.ts+++ b/src/main/features/agents.ts@@ -1583,14 +1583,14 @@ async function _listAgentSpecs(): Promise<Agent[]> {* Agents-tab contract. */export type AgentSummary = Pick<Agent,- 'agent_id' | 'name' | 'source' | 'icon' | 'color' | 'category' | 'runtime'+ 'agent_id' | 'name' | 'source' | 'seed_source' | 'icon' | 'color' | 'category' | 'runtime'> & { enabled: boolean };/** Minimal data needed for global agent search. This deliberately avoids the* full-list enrichments (workflow display skills, memory and runtime stats). */export type AgentSearchListing = Pick<Agent,- 'agent_id' | 'name' | 'source' | 'description_zh' | 'description_en'+ 'agent_id' | 'name' | 'source' | 'seed_source' | 'runtime' | 'description_zh' | 'description_en'> & { enabled: boolean };export async function listAgentSummaries(): Promise<AgentSummary[]> {@@ -1600,6 +1600,7 @@ export async function listAgentSummaries(): Promise<AgentSummary[]> {agent_id: agent.agent_id,name: agent.name,source: agent.source,+ seed_source: agent.seed_source,icon: agent.icon,color: agent.color,category: agent.category,@@ -1615,6 +1616,8 @@ export async function listAgentSearchListings(): Promise<AgentSearchListing[]> {agent_id: agent.agent_id,name: agent.name,source: agent.source,+ seed_source: agent.seed_source,+ runtime: agent.runtime,description_zh: agent.description_zh,description_en: agent.description_en,enabled: !disabledAgentIds.has(agent.agent_id),diff --git a/src/main/features/project_task_attachment_tool.ts b/src/main/features/project_task_attachment_tool.tsnew file mode 100644index 00000000..88e04353--- /dev/null+++ b/src/main/features/project_task_attachment_tool.ts@@ -0,0 +1,60 @@+/** Copy one explicitly selected, conversation-scoped file into a todo. */+import * as fs from 'node:fs/promises';+import * as path from 'node:path';+import { isPathAllowed } from '../util/path-sandbox';+import { chatAttachmentDirForConversation } from '../util/project-layout';+import { getWorkspacePath } from './user_workspace';+import { getActiveUserId } from './users';+import { ALLOWED_EXTENSIONS } from './chat_attachments';+import { sanitiseTaskAttachmentName } from './project_task_record';+import { getTask, uploadTaskAttachment, TASK_ATTACHMENT_MAX_BYTES, type ProjectTask } from './project_tasks';++export async function addTaskAttachmentFromPath(+ uid: string, pid: string, cid: string, taskId: string, sourcePath: string,+ context: { sourceProjectId?: string; workingDir?: string } = {},+): Promise<{ ok: true; task: ProjectTask } | { ok: false; error: string }> {+ const fail = (error: string) => ({ ok: false as const, error });+ if (getActiveUserId() !== uid) return fail('account_changed');+ const task = await getTask(uid, pid, taskId);+ if (!task) return fail('task_not_found');+ const roots = [context.workingDir || getWorkspacePath(uid, context.sourceProjectId ?? pid),+ ...(cid ? [chatAttachmentDirForConversation(uid, cid)] : [])];+ if (!isPathAllowed(sourcePath, roots)) return fail('source_path must be inside the current workspace or conversation attachments');+ const name = path.basename(sourcePath);+ if (sanitiseTaskAttachmentName(name) !== name) return fail('invalid_attachment_name');+ if (!ALLOWED_EXTENSIONS.has(path.extname(name).toLowerCase())) return fail('unsupported_attachment_type');+ // Preserve existing attachments even when their cached names outlive the file.+ if (task.attachments?.includes(name)) return fail('attachment_already_exists');++ let body: Buffer;+ try {+ const resolved = await fs.realpath(sourcePath);+ if (!isPathAllowed(resolved, roots)) return fail('attachment_source_out_of_scope');+ if (!(await fs.stat(resolved)).isFile()) return fail('attachment_source_must_be_file');+ const handle = await fs.open(resolved, 'r');+ try {+ const stat = await handle.stat();+ if (!stat.isFile()) return fail('attachment_source_must_be_file');+ if (stat.size > TASK_ATTACHMENT_MAX_BYTES) return fail('attachment_exceeds_200_MiB');+ // Read a fixed-size buffer so a concurrently growing file cannot exceed the cap.+ body = Buffer.alloc(stat.size);+ let offset = 0;+ while (offset < body.length) {+ const { bytesRead } = await handle.read(body, offset, body.length - offset, offset);+ if (!bytesRead) return fail('attachment_source_changed');+ offset += bytesRead;+ }+ const after = await handle.stat();+ if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) return fail('attachment_source_changed');+ } finally { await handle.close(); }+ } catch { return fail('attachment_source_read_failed'); }++ if (getActiveUserId() !== uid) return fail('account_changed');+ if (!await getTask(uid, pid, taskId)) return fail('task_not_found');+ try {+ const saved = await uploadTaskAttachment(uid, pid, taskId, name, body, { overwrite: false });+ if (saved.ok === false) return saved;+ const updated = await getTask(uid, pid, taskId);+ return updated ? { ok: true, task: updated } : fail('task_not_found');+ } catch { return fail('attachment_save_failed'); }+}diff --git a/src/main/features/project_task_record.ts b/src/main/features/project_task_record.tsnew file mode 100644index 00000000..ebfb67a2--- /dev/null+++ b/src/main/features/project_task_record.ts@@ -0,0 +1,71 @@+/** Shared compatibility reader for private task imports and local task reads. */+import * as path from 'node:path';+import { nowIso } from '../storage';+import { taskContent } from '../util/project-task-content';+import type { ProjectTask, TaskStatus } from './project_tasks';++export const TASK_RESULT_REF_MAX = 400;+export const TASK_STATUSES: readonly TaskStatus[] = ['todo', 'progress', 'review', 'done'];+const TASK_ID_RE = /^t_[a-f0-9]{12}$/;++export function clampStr(v: unknown, max: number): string | undefined {+ if (typeof v !== 'string') return undefined;+ const s = v.trim();+ if (!s) return undefined;+ return s.length > max ? s.slice(0, max) : s;+}++/** Coerce a persisted (possibly hand-edited / synced / older-shape) record into+ * a valid ProjectTask, or null if unusable. Never throws on bad input. */+export function normaliseTask(raw: any): ProjectTask | null {+ if (!raw || typeof raw !== 'object') return null;+ const id = typeof raw.id === 'string' ? raw.id : '';+ if (!TASK_ID_RE.test(id)) return null;+ const content = taskContent(raw);+ if (!content) return null;+ // Older names retain their stage; retired blocked/cancelled tasks reopen as+ // todo. Reads preserve the source file; an ordinary edit persists the mapping.+ const storedStatus = raw.status === 'in_progress' ? 'progress'+ : raw.status === 'in_review' ? 'review' : raw.status;+ const status: TaskStatus = TASK_STATUSES.includes(storedStatus) ? storedStatus : 'todo';+ const now = nowIso();+ const t: ProjectTask = {+ id,+ content,+ status,+ created_by: typeof raw.created_by === 'string' && raw.created_by ? raw.created_by : 'user',+ created_at: typeof raw.created_at === 'string' ? raw.created_at : now,+ updated_at: typeof raw.updated_at === 'string' ? raw.updated_at : now,+ };+ const owner = clampStr(raw.owner_agent, 200);+ if (owner) t.owner_agent = owner;+ if (typeof raw.owner_agent_id === 'string' && raw.owner_agent_id) t.owner_agent_id = raw.owner_agent_id;+ if (Array.isArray(raw.depends_on)) {+ const depCandidates: string[] = raw.depends_on.filter(+ (d: unknown): d is string => typeof d === 'string' && TASK_ID_RE.test(d),+ );+ const deps = [...new Set(depCandidates)];+ if (deps.length) t.depends_on = deps;+ }+ const resultRef = clampStr(raw.result_ref, TASK_RESULT_REF_MAX);+ if (resultRef) t.result_ref = resultRef;+ if (typeof raw.origin_cid === 'string' && raw.origin_cid) t.origin_cid = raw.origin_cid;+ if (Array.isArray(raw.attachments)) {+ const names = [...new Set(+ raw.attachments.map((n: unknown) => sanitiseTaskAttachmentName(n)).filter((n: string): n is string => !!n),+ )] as string[];+ if (names.length) t.attachments = names;+ }+ if (status === 'done' && typeof raw.done_at === 'string' && raw.done_at) t.done_at = raw.done_at;+ return t;+}++// Attachment names cross OS boundaries via IPC and cloud-synced task JSON. Treat+// both separator styles as directory boundaries, take the basename, and reject+// traversal / dotfiles — host-independent, mirroring auto_tasks._sanitiseFilename.+export function sanitiseTaskAttachmentName(name: unknown): string {+ if (typeof name !== 'string') return '';+ const base = path.posix.basename(name.replace(/\\/g, '/')).trim();+ if (!base || base === '.' || base === '..' || base.startsWith('.')) return '';+ return base.length > 200 ? base.slice(0, 200) : base;+}diff --git a/src/main/features/project_tasks.ts b/src/main/features/project_tasks.tsindex 2b324d06..ed0c12a6 100644--- a/src/main/features/project_tasks.ts+++ b/src/main/features/project_tasks.ts@@ -38,10 +38,14 @@ import {userTasksDir,userTaskFile,userTaskAttachmentsDir,+ userCloudRoot,} from '../paths';import { nowIso, readJson, writeJson } from '../storage';import { createLogger } from '../logger';import { logErrorSummary, logPathRef, maskId } from '../util/log-redact';+import { taskContent } from '../util/project-task-content';+import { clampStr, normaliseTask as _normaliseTask, sanitiseTaskAttachmentName as _sanitiseAttachmentName,+ TASK_RESULT_REF_MAX, TASK_STATUSES as STATUSES } from './project_task_record';import { ALLOWED_EXTENSIONS } from './chat_attachments';import * as projects from './projects';import * as agents from './agents';@@ -50,12 +54,11 @@ import { getActiveUserId } from './users';const log = createLogger('project-tasks');export type TaskStatus = 'todo' | 'progress' | 'review' | 'done';-const STATUSES: readonly TaskStatus[] = ['todo', 'progress', 'review', 'done'];// Review is unfinished work awaiting confirmation, so it counts as open.const OPEN_STATUSES: ReadonlySet<TaskStatus> = new Set<TaskStatus>(['todo', 'progress', 'review']);export const TASK_CONTENT_MAX = 4000;-export const TASK_RESULT_REF_MAX = 400;+export { TASK_RESULT_REF_MAX } from './project_task_record';export interface ProjectTask {id: string;@@ -121,13 +124,6 @@ function genTaskId(): string {return 't_' + crypto.randomBytes(6).toString('hex');}-function clampStr(v: unknown, max: number): string | undefined {- if (typeof v !== 'string') return undefined;- const s = v.trim();- if (!s) return undefined;- return s.length > max ? s.slice(0, max) : s;-}-function canonicalOpenTaskContent(content: string): string {let normalized = content.normalize('NFKC').trim();const wrappingQuotes: ReadonlyArray<readonly [string, string]> = [@@ -142,13 +138,6 @@ function canonicalOpenTaskContent(content: string): string {return normalized.replace(/\s+/g, ' ').toLowerCase();}-/** Legacy fields are read-only aliases; canonical content always wins. */-function taskContent(input: { content?: unknown; title?: unknown; detail?: unknown }): string | undefined {- if (input.content !== undefined) return typeof input.content === 'string' ? input.content.trim() : undefined;- return [input.title, input.detail].filter((value): value is string => typeof value === 'string')- .map((value) => value.trim()).filter(Boolean).join('\n');-}-/** Input-only compatibility for older clients; never persisted or returned. */export interface TaskContentInput {content?: string;@@ -186,61 +175,6 @@ async function withTaskUpdateLock<T>(uid: string, pid: string, tid: string, fn:}}-/** Coerce a persisted (possibly hand-edited / synced / older-shape) record into- * a valid ProjectTask, or null if unusable. Never throws on bad input. */-function _normaliseTask(raw: any): ProjectTask | null {- if (!raw || typeof raw !== 'object') return null;- const id = typeof raw.id === 'string' ? raw.id : '';- if (!TASK_ID_RE.test(id)) return null;- const content = taskContent(raw);- if (!content) return null;- // Older names retain their stage; retired blocked/cancelled tasks reopen as- // todo. Reads preserve the source file; an ordinary edit persists the mapping.- const storedStatus = raw.status === 'in_progress' ? 'progress'- : raw.status === 'in_review' ? 'review' : raw.status;- const status: TaskStatus = STATUSES.includes(storedStatus) ? storedStatus : 'todo';- const now = nowIso();- const t: ProjectTask = {- id,- content,- status,- created_by: typeof raw.created_by === 'string' && raw.created_by ? raw.created_by : 'user',- created_at: typeof raw.created_at === 'string' ? raw.created_at : now,- updated_at: typeof raw.updated_at === 'string' ? raw.updated_at : now,- };- const owner = clampStr(raw.owner_agent, 200);- if (owner) t.owner_agent = owner;- if (typeof raw.owner_agent_id === 'string' && raw.owner_agent_id) t.owner_agent_id = raw.owner_agent_id;- if (Array.isArray(raw.depends_on)) {- const depCandidates: string[] = raw.depends_on.filter(- (d: unknown): d is string => typeof d === 'string' && TASK_ID_RE.test(d),- );- const deps = [...new Set(depCandidates)];- if (deps.length) t.depends_on = deps;- }- const resultRef = clampStr(raw.result_ref, TASK_RESULT_REF_MAX);- if (resultRef) t.result_ref = resultRef;- if (typeof raw.origin_cid === 'string' && raw.origin_cid) t.origin_cid = raw.origin_cid;- if (Array.isArray(raw.attachments)) {- const names = [...new Set(- raw.attachments.map((n: unknown) => _sanitiseAttachmentName(n)).filter((n: string): n is string => !!n),- )] as string[];- if (names.length) t.attachments = names;- }- if (status === 'done' && typeof raw.done_at === 'string' && raw.done_at) t.done_at = raw.done_at;- return t;-}--// Attachment names cross OS boundaries via IPC and cloud-synced task JSON. Treat-// both separator styles as directory boundaries, take the basename, and reject-// traversal / dotfiles — host-independent, mirroring auto_tasks._sanitiseFilename.-function _sanitiseAttachmentName(name: unknown): string {- if (typeof name !== 'string') return '';- const base = path.posix.basename(name.replace(/\\/g, '/')).trim();- if (!base || base === '.' || base === '..' || base.startsWith('.')) return '';- return base.length > 200 ? base.slice(0, 200) : base;-}-function _attachmentExtOk(name: string): boolean {const i = name.lastIndexOf('.');const ext = i >= 0 ? name.slice(i).toLowerCase() : '';@@ -383,6 +317,7 @@ export interface ProjectTaskView {status: TaskStatus;owner_agent?: string;depends_on?: string[];+ attachments?: string[];result_ref?: string;origin_cid?: string;created_by: string;@@ -397,6 +332,7 @@ export function taskView(t: ProjectTask): ProjectTaskView {status: t.status,...(t.owner_agent ? { owner_agent: t.owner_agent } : {}),...(t.depends_on?.length ? { depends_on: [...t.depends_on] } : {}),+ ...(t.attachments?.length ? { attachments: [...t.attachments] } : {}),...(t.result_ref ? { result_ref: t.result_ref } : {}),...(t.origin_cid ? { origin_cid: t.origin_cid } : {}),created_by: t.created_by,@@ -654,10 +590,24 @@ export async function listTaskAttachments(uid: string, pid: string, tid: string)return _scanAttachmentsDir(uid, pid, tid);}+/** Resolve an existing local file for preview, including unsaved task drafts.+ * No copy/download is needed; reject redirects outside its exact account scope. */+export async function resolveTaskAttachmentPath(uid: string, pid: string, tid: string, name: string): Promise<string | null> {+ if (!TASK_ID_RE.test(tid) || !name || _sanitiseAttachmentName(name) !== name || !(await _scopeExists(uid, pid))) return null;+ const file = path.join(_taskAttachmentsDir(uid, pid, tid), name);+ try {+ const cloud = userCloudRoot(uid);+ const expected = path.join(await fsp.realpath(cloud), path.relative(cloud, file));+ if (await fsp.realpath(file) !== expected || !(await fsp.lstat(file)).isFile()) return null;+ return file;+ } catch { return null; }+}+/** Stage one attachment under the task (draft-safe: the task JSON need not exist* yet). Validates the name + type against the composer's whitelist. */export async function uploadTaskAttachment(uid: string, pid: string, tid: string, name: string, buf: Buffer,+ options: { overwrite?: boolean } = {},): Promise<{ ok: true; name: string } | { ok: false; error: string }> {if (!TASK_ID_RE.test(tid)) return { ok: false, error: 'invalid_task_id' };if (!(await _scopeExists(uid, pid))) return { ok: false, error: 'project_not_found' };@@ -668,8 +618,15 @@ export async function uploadTaskAttachment(const dir = _taskAttachmentsDir(uid, pid, tid);try {fs.mkdirSync(dir, { recursive: true });- fs.writeFileSync(path.join(dir, safe), buf);+ if (options.overwrite === false) {+ const temp = path.join(dir, `.pending-${crypto.randomBytes(16).toString('hex')}`);+ try {+ await fsp.writeFile(temp, buf, { flag: 'wx' });+ await fsp.link(temp, path.join(dir, safe));+ } finally { await fsp.rm(temp, { force: true }); }+ } else fs.writeFileSync(path.join(dir, safe), buf);} catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'EEXIST') return { ok: false, error: 'attachment_already_exists' };log.warn('attachment upload', { user: maskId(uid), scope: _scopeLog(pid), tid: maskId(tid), attachment: logPathRef(safe), error: logErrorSummary(err) });return { ok: false, error: 'write_failed' };}diff --git a/src/main/features/project_tasks_tool_handler.ts b/src/main/features/project_tasks_tool_handler.tsindex 4e12830b..d8f1f138 100644--- a/src/main/features/project_tasks_tool_handler.ts+++ b/src/main/features/project_tasks_tool_handler.ts@@ -8,6 +8,7 @@ import { getActiveUserId } from './users';export function createProjectTasksHandler(uid: string, pid: string, cid: string, agentDisplayNameById: ReadonlyMap<string, string>,execution: BacklogRunIdentity = {},+ files: { sourceProjectId?: string; workingDir?: string } = {},): ProjectTasksToolHandler {const toView = (task: projectTasks.ProjectTask) => ({...projectTasks.taskView(task),@@ -34,7 +35,7 @@ export function createProjectTasksHandler(|| normalizeOwnerKey(agent.name) === key);return owner? { fields: { owner_agent: owner.name, owner_agent_id: owner.agent_id } }- : { error: `unknown owner "${ownerRaw}" — assign an enabled agent in this account` };+ : { error: `unknown owner "${ownerRaw}" — no matching enabled agent in this account` };}const { getBindings } = await import('./projects');let bound: string[];@@ -58,7 +59,7 @@ export function createProjectTasksHandler(const validOwners = bound.map((id) => names.get(id) || id);return {error: validOwners.length- ? `unknown owner "${ownerRaw}" — assign one of the scope's available agents by display name: ${validOwners.join(', ')}`+ ? `unknown owner "${ownerRaw}" — available agent display names in this scope: ${validOwners.join(', ')}`: `unknown owner "${ownerRaw}" — this scope has no available agents to own tasks`,};}@@ -67,6 +68,16 @@ export function createProjectTasksHandler(};};return {+ delete: async (taskId) => {+ if (getActiveUserId() !== uid) return { ok: false, error: 'account_changed' };+ const result = await projectTasks.deleteTask(uid, pid, taskId);+ return result.ok ? { ok: true, task_id: taskId, deleted: true } : result;+ },+ addAttachment: async (taskId, sourcePath) => {+ const { addTaskAttachmentFromPath } = await import('./project_task_attachment_tool');+ const result = await addTaskAttachmentFromPath(uid, pid, cid, taskId, sourcePath, files);+ return result.ok ? { ok: true, task: toView(result.task) } : result;+ },list: async (query = {}) => {const tasks = await projectTasks.listTasks(uid, pid);const executions = backlogExecutionSnapshot(uid, pid, cid, execution);@@ -126,7 +137,7 @@ export function createProjectTasksHandler(return r.ok === true ? { ok: true, task: toView(r.task) } : {ok: false,error: r.error === 'content_required_for_update'- ? 'This task uses content; read it with get and send the complete replacement in content.'+ ? 'This task uses content; title/detail updates are not supported. The content field requires the complete replacement.': r.error,};},diff --git a/src/main/util/conversation-relocate.ts b/src/main/util/conversation-relocate.tsnew file mode 100644index 00000000..f4a22524--- /dev/null+++ b/src/main/util/conversation-relocate.ts@@ -0,0 +1,424 @@+/**+ * Relocate one conversation's bytes from the unprojected root into a project.+ *+ * Project membership is a storage location, not a field: messages, the group+ * companion dir, the commander and per-agent sessions, attachments and+ * artifacts all live under `cloud/projects/<pid>/` once a conversation belongs+ * to a project. The set moved here is the same set the boot migration moves+ * (`migrate-project-layout-v4.ts::migrateConversation`), which is the only+ * other code in the app that relocates a conversation.+ *+ * A local write-ahead record precedes every runtime move. An explicit commit+ * marker follows the index/meta writes; activation rolls back uncommitted+ * records before layout repair or ghost cleanup can interpret partial state.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++import {+ projectChatArtifactCidDir,+ projectChatAttachmentDir,+ projectChatJsonlFile,+ projectGroupChatDir,+ projectSessionCloudToolResultsDir,+ projectSessionFile,+ userChatArtifactsDir,+ userChatAttachmentsDir,+ userChatsDir,+ userRoot,+ userConversationMovesDir,+ projectChatIndexFile,+ userSessionsDir,+} from '../paths';+import { createLogger } from '../logger';+import { safeId, writeJsonSync } from '../storage';+import { logErrorSummary, maskId } from './log-redact';+import { cloudRelForAbs, invalidateConversationProjectCache, setConversationRelocationBlocked } from './project-layout';++const log = createLogger('conversation-relocate');++/** A sync domain plus the paths that changed inside it. */+export interface RelocatedPaths {+ domain: 'chats' | 'sessions' | 'chat_attachments' | 'chat_artifacts';+ /** Cloud-relative path the bytes left. */+ from: string;+ /** Cloud-relative path the bytes now occupy. */+ to: string;+ /** File-level old paths: sync manifests do not contain directory entries. */+ files: string[];+}++interface Pair {+ domain: RelocatedPaths['domain'];+ src: string;+ dst: string;+}++/** Session sidecars share a stem, so each is matched by its own suffix. */+const SESSION_SUFFIXES = ['.jsonl', '.jsonl.context.json', '.tool-results'] as const;++function sessionDestination(uid: string, pid: string, name: string): string | null {+ for (const suffix of SESSION_SUFFIXES) {+ if (!name.endsWith(suffix)) continue;+ const sid = name.slice(0, -suffix.length);+ if (suffix === '.tool-results') return projectSessionCloudToolResultsDir(uid, pid, sid);+ if (suffix === '.jsonl.context.json') return `${projectSessionFile(uid, pid, sid)}.context.json`;+ return projectSessionFile(uid, pid, sid);+ }+ return null;+}++/**+ * Every source/destination pair for `cid`, whether or not the source exists.+ * Enumerating the session directory is the truth source: `members.json` can+ * already be gone or stale, which is what leaked orphan member sessions in the+ * delete path before it started globbing too.+ */+function relocationPairs(uid: string, cid: string, pid: string): Pair[] {+ const chatRoot = userChatsDir(uid);+ const pairs: Pair[] = [+ { domain: 'chats', src: path.join(chatRoot, `${cid}.jsonl`), dst: projectChatJsonlFile(uid, pid, cid) },+ { domain: 'chats', src: path.join(chatRoot, cid), dst: projectGroupChatDir(uid, pid, cid) },+ ];++ const sessionsRoot = userSessionsDir(uid);+ let names: string[] = [];+ try { names = fs.readdirSync(sessionsRoot); } catch { names = []; }+ const commanderStem = `gconv-${cid}`;+ const memberPrefix = `gmember-${cid}-`;+ for (const name of names) {+ const owned = name === `${commanderStem}.jsonl`+ || name === `${commanderStem}.jsonl.context.json`+ || name === `${commanderStem}.tool-results`+ || (name.startsWith(memberPrefix) && SESSION_SUFFIXES.some((suffix) => name.endsWith(suffix)));+ if (!owned) continue;+ const dst = sessionDestination(uid, pid, name);+ if (dst) pairs.push({ domain: 'sessions', src: path.join(sessionsRoot, name), dst });+ }++ pairs.push({+ domain: 'chat_attachments',+ src: path.join(userChatAttachmentsDir(uid), cid),+ dst: projectChatAttachmentDir(uid, pid, cid),+ });+ pairs.push({+ domain: 'chat_artifacts',+ src: path.join(userChatArtifactsDir(uid), cid),+ dst: projectChatArtifactCidDir(uid, pid, cid),+ });+ return pairs;+}++function moveOne(pair: Pair): boolean {+ if (!fs.existsSync(pair.src)) return false;+ // A destination that already exists means an earlier interrupted move, or a+ // cid collision inside the project. Either way the caller must not silently+ // merge two conversations' bytes.+ if (fs.existsSync(pair.dst)) {+ throw new Error(`conversation relocate: destination already exists (${path.basename(pair.dst)})`);+ }+ fs.mkdirSync(path.dirname(pair.dst), { recursive: true });+ fs.renameSync(pair.src, pair.dst);+ return true;+}++/**+ * Move every byte of `cid` into `pid` and report what changed, so the caller+ * can tell sync which paths were retired and which appeared. Throws with the+ * filesystem left as it was found.+ */+export function relocateConversationIntoProject(+ uid: string,+ cid: string,+ pid: string,+ original?: Record<string, unknown>,+): RelocatedPaths[] {+ const pairs = relocationPairs(uid, cid, pid);+ const files = new Map<Pair, string[]>();+ const collect = (file: string, out: string[]): void => {+ let stat: fs.Stats;+ try { stat = fs.lstatSync(file); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;+ throw error;+ }+ if (stat.isDirectory()) {+ for (const entry of fs.readdirSync(file, { withFileTypes: true })) {+ const child = path.join(file, entry.name);+ if (entry.isDirectory()) collect(child, out);+ else if (entry.isFile()) out.push(cloudRelForAbs(uid, child));+ }+ } else if (stat.isFile()) out.push(cloudRelForAbs(uid, file));+ };+ // Keep discovery and rename in one non-yielding section after the idle check.+ // Read directory names only, without per-file stats, symlinks or payload hashes.+ for (const pair of pairs) {+ const leaves: string[] = [];+ collect(pair.src, leaves);+ files.set(pair, leaves);+ }+ // Check every destination before publishing a journal: a pre-existing+ // destination is not ours to roll back, even if a later source is absent.+ const planned = pairs.filter(pair => fs.existsSync(pair.src));+ for (const pair of pairs) {+ if (fs.existsSync(pair.dst)) throw new Error('Conversation move destination conflict');+ }+ if (original) {+ const file = journalPath(uid, cid);+ if (fs.existsSync(file)) throw new Error('Conversation move recovery is pending');+ persistJournal(uid, {+ version: 1, cid, pid, phase: 'prepared', original,+ moved: planned.map(pair => ({ domain: pair.domain, from: cloudRelForAbs(uid, pair.src),+ to: cloudRelForAbs(uid, pair.dst), files: files.get(pair)! })),+ });+ }+ const done: Pair[] = [];+ try {+ for (const pair of pairs) {+ if (moveOne(pair)) done.push(pair);+ }+ } catch (err) {+ for (const pair of done.reverse()) {+ // Best effort: the throw below reports the original failure, and a+ // rollback that cannot complete leaves evidence in the log rather than+ // masking why the move was refused.+ try {+ fs.mkdirSync(path.dirname(pair.src), { recursive: true });+ fs.renameSync(pair.dst, pair.src);+ } catch { /* reported by the caller's error path */ }+ }+ throw err;+ }+ return done.map((pair) => ({+ domain: pair.domain,+ from: cloudRelForAbs(uid, pair.src),+ to: cloudRelForAbs(uid, pair.dst),+ files: files.get(pair)!,+ }));+}++interface MoveJournal {+ version: 1;+ cid: string;+ pid: string;+ phase: 'prepared' | 'committed';+ original: Record<string, unknown>;+ moved: RelocatedPaths[];+}++function journalPath(uid: string, cid: string): string {+ return path.join(userConversationMovesDir(uid), `${cid}.json`);+}++function persistJournal(uid: string, journal: MoveJournal): void {+ const file = journalPath(uid, journal.cid);+ writeJsonSync(file, journal);+ const fd = fs.openSync(file, 'r+');+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }+}++function readJournal(uid: string, cid: string): MoveJournal {+ const journal = JSON.parse(fs.readFileSync(journalPath(uid, cid), 'utf8')) as MoveJournal;+ if (journal.version !== 1 || journal.cid !== cid || !safeId(cid) || !safeId(journal.pid)+ || !['prepared', 'committed'].includes(journal.phase)+ || journal.original?.conversation_id !== cid || journal.original.project_id+ || !Array.isArray(journal.moved)) throw new Error('Invalid conversation move recovery record');+ const roots: Record<RelocatedPaths['domain'], string[]> = {+ chats: [`cloud/chats/${cid}`, `cloud/chats/${cid}.jsonl`],+ sessions: [],+ chat_attachments: [`cloud/chat_attachments/${cid}`],+ chat_artifacts: [`cloud/chat_artifacts/${cid}`],+ };+ const seen = new Set<string>();+ for (const item of journal.moved) {+ if (!item || typeof item.from !== 'string') throw new Error('Invalid conversation move recovery paths');+ const from = item.from;+ const name = typeof from === 'string' ? from.slice('cloud/sessions/'.length) : '';+ const session = item.domain === 'sessions' && from.startsWith('cloud/sessions/')+ && !name.includes('/') && !name.includes('\\') && !name.includes('..')+ && SESSION_SUFFIXES.some(suffix => name === `gconv-${cid}${suffix}`+ || (name.startsWith(`gmember-${cid}-`) && name.endsWith(suffix)));+ if ((!session && !roots[item.domain]?.includes(from)) || seen.has(from)+ || item.to !== from.replace('cloud/', `cloud/projects/${journal.pid}/`)+ || !Array.isArray(item.files) || !item.files.every(file => typeof file === 'string'+ && (file === from || file.startsWith(`${from}/`))+ && !file.split('/').some(part => part === '..' || part === '.' || !part)+ && !file.includes('\\'))) throw new Error('Invalid conversation move recovery paths');+ seen.add(from);+ }+ return journal;+}++function journalIds(uid: string): string[] {+ try {+ return fs.readdirSync(userConversationMovesDir(uid))+ .filter(name => name.endsWith('.json') && safeId(name.slice(0, -5)))+ .map(name => name.slice(0, -5));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];+ throw error;+ }+}++/** The commit marker is the transaction boundary, independent of sync availability. */+export function commitConversationRelocation(uid: string, cid: string): void {+ const journal = readJournal(uid, cid);+ persistJournal(uid, { ...journal, phase: 'committed' });+}++function readIndexStrict(file: string): Record<string, unknown>[] {+ let raw: unknown;+ try { raw = JSON.parse(fs.readFileSync(file, 'utf8')); }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];+ throw error;+ }+ const rows = Array.isArray(raw) ? raw : (raw as { items?: unknown })?.items;+ if (!Array.isArray(rows)) throw new Error('Invalid conversation index during recovery');+ return rows;+}++/** Idempotent rollback, including partial index commits. Never replace an+ * existing source with destination bytes or discard an unreadable index. */+export function recoverConversationRelocation(uid: string, cid: string): void {+ if (!fs.existsSync(journalPath(uid, cid))) { setConversationRelocationBlocked(uid, cid, false); return; }+ setConversationRelocationBlocked(uid, cid, true);+ const journal = readJournal(uid, cid);+ if (journal.phase === 'committed') { setConversationRelocationBlocked(uid, cid, false); return; }+ const root = userRoot(uid);+ for (const item of journal.moved) {+ const source = fs.existsSync(path.join(root, item.from));+ const target = fs.existsSync(path.join(root, item.to));+ if (source === target) throw new Error('Conversation recovery needs attention; both copies were preserved');+ }+ const globalIndex = path.join(userChatsDir(uid), '_index.json');+ const projectIndex = projectChatIndexFile(uid, journal.pid);+ const globalRows = readIndexStrict(globalIndex).filter(row => row.conversation_id !== cid);+ const projectRows = readIndexStrict(projectIndex).filter(row => row.conversation_id !== cid);+ for (const item of [...journal.moved].reverse()) {+ const from = path.join(root, item.from);+ const to = path.join(root, item.to);+ if (!fs.existsSync(to)) continue;+ fs.mkdirSync(path.dirname(from), { recursive: true });+ fs.renameSync(to, from);+ }+ writeJsonSync(path.join(userChatsDir(uid), cid, 'meta.json'), journal.original);+ writeJsonSync(globalIndex, [journal.original, ...globalRows]);+ writeJsonSync(projectIndex, projectRows);+ invalidateConversationProjectCache(uid, cid);+ fs.unlinkSync(journalPath(uid, cid));+ setConversationRelocationBlocked(uid, cid, false);+}++/** Run before any activation migration or consumer sees the partial indexes. */+export function recoverConversationRelocations(uid: string): number {+ let failed = 0;+ for (const cid of journalIds(uid)) {+ try { recoverConversationRelocation(uid, cid); }+ catch (err) {+ failed++;+ log.warn('conversation move recovery failed', { cid: maskId(cid), ...logErrorSummary(err) });+ }+ }+ return failed;+}++/** A move whose recovery could not settle: a both-copies conflict left the+ * journal `prepared`, or the record cannot be read by this version. Both its+ * source and target trees stay out of sync until the conversation is resolved+ * locally; every other path of the account keeps syncing. */+export interface UnresolvedRelocation {+ cid: string;+ /** Exact cloud-relative file paths. */+ exact: string[];+ /** Cloud-relative prefixes; a path is covered when it starts with one. */+ prefixes: string[];+}++function _unresolvedFromJournal(journal: MoveJournal): UnresolvedRelocation {+ const exact: string[] = [];+ const prefixes: string[] = [];+ for (const item of journal.moved) {+ exact.push(item.from, item.to);+ prefixes.push(`${item.from}/`, `${item.to}/`);+ }+ return { cid: journal.cid, exact, prefixes };+}++/** An unreadable record still names its conversation in the file name; the+ * target project is used only when the record exposes a well-formed id. */+function _unresolvedByCid(uid: string, cid: string): UnresolvedRelocation {+ let pid = '';+ try {+ const raw = JSON.parse(fs.readFileSync(journalPath(uid, cid), 'utf8')) as { pid?: unknown };+ if (safeId(raw?.pid)) pid = raw.pid as string;+ } catch { /* unreadable record: exclude the global roots only */ }+ const exact: string[] = [];+ const prefixes: string[] = [];+ for (const root of pid ? ['cloud', `cloud/projects/${pid}`] : ['cloud']) {+ exact.push(`${root}/chats/${cid}.jsonl`);+ for (const suffix of SESSION_SUFFIXES) exact.push(`${root}/sessions/gconv-${cid}${suffix}`);+ prefixes.push(`${root}/chats/${cid}/`, `${root}/chat_attachments/${cid}/`, `${root}/chat_artifacts/${cid}/`,+ `${root}/sessions/gconv-${cid}.tool-results/`, `${root}/sessions/gmember-${cid}-`);+ }+ return { cid, exact, prefixes };+}++export function matchesUnresolvedRelocation(unresolved: UnresolvedRelocation[], relPath: string): boolean {+ return unresolved.some(item => item.exact.includes(relPath) || item.prefixes.some(prefix => relPath.startsWith(prefix)));+}++/** Durable sync intents survive disabled sync and repeated process restarts.+ * Reading these never unlinks a source that another device may have restored,+ * and never throws: an unresolved journal is reported, not raised, so one+ * conflicted conversation cannot stop the account's sync. */+export function readConversationRelocationJournals(uid: string): {+ committed: RelocatedPaths[];+ unresolved: UnresolvedRelocation[];+} {+ const committed: RelocatedPaths[] = [];+ const unresolved: UnresolvedRelocation[] = [];+ let ids: string[];+ try { ids = journalIds(uid); }+ catch (err) {+ log.warn('conversation move journals unreadable', logErrorSummary(err));+ return { committed, unresolved };+ }+ for (const cid of ids) {+ let journal: MoveJournal;+ try { journal = readJournal(uid, cid); }+ catch (err) {+ log.warn('conversation move journal invalid; excluded from sync', { cid: maskId(cid), ...logErrorSummary(err) });+ unresolved.push(_unresolvedByCid(uid, cid));+ continue;+ }+ if (journal.phase === 'committed') committed.push(...journal.moved);+ else unresolved.push(_unresolvedFromJournal(journal));+ }+ return { committed, unresolved };+}++export function committedConversationRelocations(uid: string): RelocatedPaths[] {+ return readConversationRelocationJournals(uid).committed;+}++/** Called only for old paths whose remote deletion/absence was confirmed. */+export function consumeConversationRelocationPaths(uid: string, settled: Set<string>): void {+ if (!settled.size) return;+ for (const cid of journalIds(uid)) {+ let journal: MoveJournal;+ try { journal = readJournal(uid, cid); }+ catch { continue; /* reported by readConversationRelocationJournals */ }+ if (journal.phase !== 'committed') continue;+ let changed = false;+ for (const item of journal.moved) {+ const files = item.files.filter(file => !settled.has(file));+ if (files.length !== item.files.length) changed = true;+ item.files = files;+ }+ if (!changed) continue;+ if (journal.moved.every(item => !item.files.length)) fs.unlinkSync(journalPath(uid, cid));+ else persistJournal(uid, journal);+ }+}diff --git a/src/main/util/project-task-content.ts b/src/main/util/project-task-content.tsnew file mode 100644index 00000000..c8cf39e5--- /dev/null+++ b/src/main/util/project-task-content.ts@@ -0,0 +1,6 @@+/** Legacy fields are read-only aliases; canonical content always wins. */+export function taskContent(input: { content?: unknown; title?: unknown; detail?: unknown }): string | undefined {+ if (input.content !== undefined) return typeof input.content === 'string' ? input.content.trim() : undefined;+ return [input.title, input.detail].filter((value): value is string => typeof value === 'string')+ .map((value) => value.trim()).filter(Boolean).join('\n');+}diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.jsindex 31fb15b4..f53b2aa1 100644--- a/src/renderer/modules/agents.js+++ b/src/renderer/modules/agents.js@@ -552,6 +552,7 @@ async function loadAgents(forceRefresh, opts = {}) {return ka < kb ? -1 : ka > kb ? 1 : 0;});_agentsCache = sortedAgents;+ if (typeof refreshAllChatComposers === 'function') refreshAllChatComposers();_agentsCacheIsSummary = summary;if (typeof _renderRecipientChip === 'function') {_renderRecipientChip();@@ -3852,7 +3853,11 @@ async function _openAgentPicker(anchorBtn, entryPoint = 'unknown') {// own their script/data loads and cannot delay this first frame._setAgentPickerTab('agents', { focusSearch: false });_positionPopoverAboveOrBelow(picker, anchorBtn);- setTimeout(() => document.getElementById('agent-picker-search')?.focus(), 30);+ setTimeout(() => {+ if (openSeq === _agentPickerOpenSeq && picker.style.display !== 'none') {+ document.getElementById('agent-picker-search')?.focus();+ }+ }, 30);// Project bindings affect Agent visibility, so refresh them independently// and repaint only if this picker session is still current.projectContextPromise.then(() => {@@ -4233,7 +4238,9 @@ function _renderLibraryPickerList(listEl, filterText, anchorId) {const picker = document.getElementById('agent-picker');if (!picker || picker.style.display === 'none' || _agentPickerTab !== 'library') return;const search = document.getElementById('agent-picker-search');- _renderLibraryPickerList(listEl, search ? search.value : filterText, anchorId);+ // Use the shared repaint boundary so placement measures the loaded rows,+ // not the shorter loading shell that was visible before this response.+ _renderAgentPickerList(search ? search.value : filterText);});return;}@@ -4570,39 +4577,46 @@ let _atKeyMark = null; // { inputId, posAfter } | nullfunction _insertInlineMention(name) {const m = _atKeyMark;_atKeyMark = null;- if (!m || !name) return;+ if (!m || !name || (m.snapshot && !m.snapshot.matches())) return;const ta = document.getElementById(m.inputId);if (!ta) return;const atIdx = m.posAfter - 1;- if (atIdx < 0 || ta.value.charAt(atIdx) !== '@') return;+ if (atIdx < 0 || composerText(ta).charAt(atIdx) !== '@') return;const insert = `${name} `;- ta.value = ta.value.slice(0, m.posAfter) + insert + ta.value.slice(m.posAfter);+ composerSetText(ta, composerText(ta).slice(0, m.posAfter) + insert + composerText(ta).slice(m.posAfter));const caret = m.posAfter + insert.length;- try { ta.setSelectionRange(caret, caret); } catch (_) {}+ try { composerSetSelection(ta, caret, caret); } catch (_) {}if (typeof autoGrow === 'function') autoGrow(ta, 200);- ta.dispatchEvent(new Event('input', { bubbles: true }));+ composerNotify(ta);_focusInput(ta);}function _consumeAtKeyChar() {const m = _atKeyMark;_atKeyMark = null;- if (!m) return null;+ if (!m || (m.snapshot && !m.snapshot.matches())) return null;const ta = document.getElementById(m.inputId);if (!ta) return null;const atIdx = m.posAfter - 1;- if (atIdx < 0 || ta.value.charAt(atIdx) !== '@') return null;- ta.value = ta.value.slice(0, atIdx) + ta.value.slice(atIdx + 1);- try { ta.setSelectionRange(atIdx, atIdx); } catch (_) {}+ if (atIdx < 0 || composerText(ta).charAt(atIdx) !== '@') return null;+ composerSetText(ta, composerText(ta).slice(0, atIdx) + composerText(ta).slice(atIdx + 1));+ try { composerSetSelection(ta, atIdx, atIdx); } catch (_) {}if (typeof autoGrow === 'function') autoGrow(ta, 200);- ta.dispatchEvent(new Event('input', { bubbles: true }));+ composerNotify(ta);return ta;}function _focusInput(input) {// Defer to the next tick so the picker's outside-click handler can finish// closing first; otherwise focus jumps back to the picker on some browsers.+ const active = document.activeElement;+ const owner = _composerApi(input), epoch = owner?.epoch;setTimeout(() => {+ // A native key/click may already have focused the editor and moved its+ // caret before selectionchange reaches the model. Re-focusing would write+ // the older model selection over that newer native selection.+ if (document.activeElement === input || owner && owner.epoch !== epoch) return;+ if (document.activeElement && document.activeElement !== active && document.activeElement !== document.body) return;try {if (typeof focusChatRichComposer === 'function' && focusChatRichComposer(input)) return;input.focus();@@ -4632,18 +4646,22 @@ function _recipientTextareaFromEventTarget(target) {function _atKeyOpener(chipId) {return (e) => {- if (e.key !== '@') return;+ if (e.key !== '@' || e.isComposing || e.keyCode === 229) return;const btn = document.getElementById(chipId);if (!btn) return;const ta = _recipientTextareaFromEventTarget(e.currentTarget);if (!ta) return;+ const owner = _composerApi(ta);+ const epoch = owner?.epoch;setTimeout(() => {+ if (owner && owner.epoch !== epoch) return;try {if (typeof getChatRichComposerSelection === 'function') getChatRichComposerSelection(ta);} catch (_) {}_atKeyMark = {inputId: ta.id || '',- posAfter: typeof ta.selectionStart === 'number' ? ta.selectionStart : 0,+ snapshot: composerSnapshot(ta),+ posAfter: typeof composerSelection(ta).start === 'number' ? composerSelection(ta).start : 0,};_openAgentPicker(btn, 'at_key');}, 0);diff --git a/src/renderer/modules/contexts.js b/src/renderer/modules/contexts.jsindex e2db1919..b81df34a 100644--- a/src/renderer/modules/contexts.js+++ b/src/renderer/modules/contexts.js@@ -1786,7 +1786,7 @@ async function handleCtxNativeUpload(targetDir = '') {}let data;try {- data = await window.orkas.invoke('contexts.pickAndUpload', { targetDir });+ data = await window.orkas.invoke(_ctxProjectId ? 'projects.files.pickAndUpload' : 'contexts.pickAndUpload', { targetDir, ...(_ctxProjectId ? { projectId: _ctxProjectId } : {}) });} catch (err) {_ctxLogUploadFailure({source_type: 'native',diff --git a/src/renderer/modules/conversation-to-project.js b/src/renderer/modules/conversation-to-project.jsnew file mode 100644index 00000000..f810afaf--- /dev/null+++ b/src/renderer/modules/conversation-to-project.js@@ -0,0 +1,308 @@+/* Orkas Frontend — file a loose task under a project+ *+ * Reachable from the `⋯` menu of a conversation that has no project. One picker offers two+ * flows, both ending in the same `conversations.move` call:+ *+ * New project — ask for a name, create it through the same channel the+ * sidebar's inline create uses, move the conversation in,+ * then add the agents selected in the picker.+ * Add to project — pick an existing project, move, and add the selected agents.+ *+ * The move is never optimistic: it relocates the conversation's messages,+ * sessions, attachments and artifacts on disk and can legitimately refuse (a+ * running turn), so the sidebar is only updated once the backend confirms.+ *+ * Loaded as a top-level renderer module, so these are globals for+ * `conversation.js::_conversationActionItems`. Renderer rules (PC/CLAUDE.md+ * §8) forbid `import`/`export` here.+ */++/** Backend refusal codes → the copy that tells the user what to do next. */+const _CONV_MOVE_ERROR_KEYS = {+ has_running_conv: 'chat.conv_move_running',+ already_in_project: 'chat.conv_move_already',+ project_not_found: 'chat.conv_move_no_project',+};++function _convMoveErrorText(code) {+ const key = _CONV_MOVE_ERROR_KEYS[String(code || '')] || 'chat.conv_move_failed';+ return t(key);+}++function _convMoveRow(cid) {+ return Array.isArray(conversations)+ ? conversations.find((c) => c && c.conversation_id === cid)+ : null;+}++/**+ * Agents that took part in the conversation.+ *+ * The row's `agent_ids` is a denormalized sidebar summary that can lag behind+ * the roster, and the starting agent may never have been @-mentioned, so the+ * three sources are unioned: the summary, the starting agent, and the actor+ * list the turns actually used.+ */+async function _convMoveAgentIds(cid, conv, names = new Map()) {+ const ids = new Set();+ if (Array.isArray(conv && conv.agent_ids)) {+ for (const id of conv.agent_ids) if (id) ids.add(String(id));+ }+ if (conv && conv.agent_id) ids.add(String(conv.agent_id));+ try {+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/members`);+ const data = await res.json();+ for (const actor of (data && data.actors) || []) {+ if (actor && actor.kind === 'agent' && actor.id) {+ ids.add(String(actor.id));+ if (actor.name) names.set(String(actor.id), actor.name);+ }+ }+ } catch (_) { /* the denormalized summary is the fallback */ }+ return [...ids].filter((id) => !_isCommanderAgent(id));+}++/** Read lightweight names once; roster names remain useful for deleted agents. */+async function _convMoveAgents(cid, conv) {+ const names = new Map();+ const [ids, summaries] = await Promise.all([+ _convMoveAgentIds(cid, conv, names),+ apiFetch('/api/agents/list?summary=1').then((res) => res.json()).catch(() => null),+ ]);+ const details = new Map();+ for (const agent of (summaries && summaries.agents) || []) {+ if (agent.agent_id) details.set(agent.agent_id, agent);+ if (agent.agent_id && agent.name) names.set(agent.agent_id, agent.name);+ }+ return ids.map((id) => ({+ id, name: names.get(id) || id, icon: details.get(id)?.icon, color: details.get(id)?.color,+ }))+ .sort((a, b) => a.name.localeCompare(b.name));+}++async function _requestConversationMove(cid, projectId) {+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/move`, {+ method: 'POST',+ body: JSON.stringify({ projectId }),+ });+ const data = await res.json();+ if (!data || data.ok === false || !data.conversation) {+ throw new Error((data && data.error) || 'move_failed');+ }+ return data.conversation;+}++/** Re-home the cached row so the sidebar nests it under the project, then let+ * the authoritative loaders correct counts and pagination. */+async function _applyConversationMoved(cid, moved) {+ if (Array.isArray(conversations)) {+ const idx = conversations.findIndex((c) => c && c.conversation_id === cid);+ if (idx >= 0) conversations[idx] = { ...conversations[idx], ...moved };+ }+ if (typeof _sortConversationCacheForSidebar === 'function') _sortConversationCacheForSidebar();+ if (typeof renderConversationList === 'function') renderConversationList();+ if (typeof _refreshChatHeader === 'function') _refreshChatHeader();+ if (typeof loadProjects === 'function') {+ try { await loadProjects(true); } catch (_) { /* sidebar counts refresh on the next load */ }+ }+}++/** Bind the conversation's agents to the project. Failures are per agent and+ * never undo the move: `projects.bindings.add` rejects a disabled agent, and+ * losing one binding is not a reason to leave the task where it was. */+async function _bindConversationAgentsToProject(projectId, agentIds) {+ let bound = 0;+ for (const agentId of agentIds) {+ try {+ const res = await window.orkas.invoke('projects.bindings.add', { projectId, kind: 'agent', id: agentId });+ if (res && res.ok !== false) bound++;+ } catch (_) { /* reported in aggregate by the caller's toast */ }+ }+ return bound;+}++async function _moveConversationToNewProject(cid, agentIds) {+ const conv = _convMoveRow(cid);+ if (!conv || conv.project_id) return;+ if (isConvPending(cid)) { uiToast(t('chat.conv_move_running')); return; }+ const raw = await uiPrompt(t('chat.conv_new_project_prompt'), '', { nameLimit: true });+ if (raw === null) return;+ const name = typeof _normaliseProjectNameFinal === 'function'+ ? _normaliseProjectNameFinal(raw)+ : String(raw || '').trim();+ if (!name) { uiToast(t('project.name_empty')); return; }++ let projectId = '';+ try {+ const res = await window.orkas.invoke('projects.create', { name });+ if (!res || !res.ok || !res.project) {+ uiToast(typeof _projectInlineErrorText === 'function'+ ? _projectInlineErrorText(res && res.error)+ : t('project.error.generic'));+ return;+ }+ projectId = res.project.project_id;+ } catch (_) {+ uiToast(t('project.error.generic'));+ return;+ }++ // The project exists from here on. A refused move leaves the user with an+ // empty project rather than a silent no-op, which is recoverable and+ // visible; deleting it behind their back is not.+ try {+ const moved = await _requestConversationMove(cid, projectId);+ await _applyConversationMoved(cid, moved);+ } catch (err) {+ uiToast(_convMoveErrorText(err && err.message));+ if (typeof loadProjects === 'function') { try { await loadProjects(true); } catch (_) { /* ignore */ } }+ return;+ }+ await _finishConversationProjectMove(projectId, name, agentIds);+}++async function _finishConversationProjectMove(projectId, name, agentIds) {+ const bound = await _bindConversationAgentsToProject(projectId, agentIds);+ if (typeof loadProjects === 'function') { try { await loadProjects(true); } catch (_) { /* refreshed on next load */ } }+ const failed = agentIds.length - bound;+ uiToast(failed > 0+ ? t('chat.conv_moved_agents_failed', { name, count: failed })+ : t('chat.conv_moved', { name }));+}++function _convProjectIcon() {+ if (typeof window !== 'undefined' && typeof window.uiIconHtml === 'function') {+ return window.uiIconHtml('folder', 'conv-project-pick-icon');+ }+ return '';+}++/**+ * Pick one project from a list, then confirm.+ *+ * A row per project rather than a row of buttons: the list reads as the thing+ * being chosen from, Cancel stays visibly secondary next to a real primary+ * action, and one stray click can no longer move a task. Resolves to the+ * chosen project and agent ids, or null.+ */+let _closeConversationProjectPicker = null;++function _openConversationProjectPicker(projects, agents = []) {+ if (_closeConversationProjectPicker) _closeConversationProjectPicker(null);+ return new Promise((resolve) => {+ const previousFocus = document.activeElement;+ const overlay = document.createElement('div');+ overlay.id = 'conv-project-picker-overlay';+ overlay.className = 'modal-overlay ui-dialog-overlay conv-project-picker-overlay open';+ const rows = projects.map((project) => `+ <button type="button" class="conv-project-pick-row" role="option" aria-selected="false"+ data-project-id="${escapeHtml(project.project_id)}">+ ${_convProjectIcon()}+ <span class="conv-project-pick-name">${escapeHtml(project.name || project.project_id)}</span>+ </button>+ `).join('');+ overlay.innerHTML = `+ <div class="modal modal-standard conv-project-picker" role="dialog" aria-modal="true"+ aria-labelledby="conv-project-picker-title" aria-describedby="conv-project-picker-hint">+ <div class="modal-title conv-project-picker-title" id="conv-project-picker-title" data-i18n="chat.conv_to_project">${escapeHtml(t('chat.conv_to_project'))}</div>+ <div class="conv-project-picker-hint" id="conv-project-picker-hint" data-i18n="chat.conv_pick_project_message">${escapeHtml(t('chat.conv_pick_project_message'))}</div>+ <div class="conv-project-pick-list" role="listbox" aria-labelledby="conv-project-picker-title">${rows}</div>+ <button type="button" class="btn" data-act="new" data-i18n="chat.conv_to_new_project">${escapeHtml(t('chat.conv_to_new_project'))}</button>+ ${agents.length ? `<fieldset class="conv-project-agents">+ <legend data-i18n="chat.conv_project_agents">${escapeHtml(t('chat.conv_project_agents'))}</legend>+ <div class="conv-project-agent-list">${agents.map((agent) => `+ <label class="ui-dialog-checkbox-row">+ <input type="checkbox" data-agent-id="${escapeHtml(agent.id)}" checked>+ <span aria-hidden="true">${renderAvatarHtml(agent.icon, agent.color, { size: 24, seed: agent.id })}</span>+ <span class="conv-project-agent-name">${escapeHtml(agent.name)}</span>+ </label>`).join('')}</div>+ </fieldset>` : ''}+ <div class="modal-actions">+ <button type="button" class="btn" data-act="cancel" data-i18n="common.cancel">${escapeHtml(t('common.cancel'))}</button>+ <button type="button" class="btn btn-primary" data-act="ok" data-i18n="chat.conv_move_submit" disabled>${escapeHtml(t('chat.conv_move_submit'))}</button>+ </div>+ </div>+ `;+ document.body.appendChild(overlay);++ const okBtn = overlay.querySelector('[data-act="ok"]');+ const cancelBtn = overlay.querySelector('[data-act="cancel"]');+ // Initial focus and the focus guard agree: a focus change outside the+ // dialog after it opened (a view finishing its own deferred focus)+ // returns to the first choice, never to Cancel.+ const initialFocus = overlay.querySelector('.conv-project-pick-row') || overlay.querySelector('[data-act="new"]');+ const releaseFocusGuard = _uiKeepDialogFocus(overlay, initialFocus);+ const selection = () => ({+ projectId: picked,+ agentIds: [...overlay.querySelectorAll('input[data-agent-id]:checked')].map((el) => el.dataset.agentId),+ });+ let picked = '';+ let finished = false;+ const finish = (value) => {+ if (finished) return;+ finished = true;+ document.removeEventListener('keydown', onKey, true);+ releaseFocusGuard();+ if (_closeConversationProjectPicker === finish) _closeConversationProjectPicker = null;+ overlay.remove();+ _uiRestoreDialogFocus(previousFocus);+ resolve(value || null);+ };+ const onKey = (e) => {+ // IME guard (PC/CLAUDE.md §8): Escape mid-composition belongs to the IME.+ if (e.isComposing || e.keyCode === 229) return;+ if (!_uiIsTopDialogOverlay(overlay)) return;+ if (_uiTrapDialogTab(overlay, e)) return;+ if (e.key === 'Escape') { e.preventDefault(); finish(null); }+ };+ _closeConversationProjectPicker = finish;+ overlay.querySelectorAll('.conv-project-pick-row').forEach((row) => {+ row.addEventListener('click', () => {+ picked = row.dataset.projectId || '';+ for (const other of overlay.querySelectorAll('.conv-project-pick-row')) {+ const on = other === row;+ other.classList.toggle('is-picked', on);+ other.setAttribute('aria-selected', String(on));+ }+ okBtn.disabled = !picked;+ });+ row.addEventListener('dblclick', () => { if (picked) finish(selection()); });+ });+ overlay.querySelector('[data-act="new"]').addEventListener('click', () => finish({ ...selection(), create: true }));+ okBtn.addEventListener('click', () => { if (picked) finish(selection()); });+ cancelBtn.addEventListener('click', () => finish(null));+ overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) finish(null); });+ document.addEventListener('keydown', onKey, true);+ setTimeout(() => {+ if (initialFocus && document.body.contains(overlay) && _uiIsTopDialogOverlay(overlay)) initialFocus.focus();+ }, 0);+ });+}++async function _moveConversationToExistingProject(cid) {+ const conv = _convMoveRow(cid);+ if (!conv || conv.project_id) return;+ if (isConvPending(cid)) { uiToast(t('chat.conv_move_running')); return; }+ let projects = [];+ try {+ const res = await window.orkas.invoke('projects.list', {});+ projects = Array.isArray(res && res.projects) ? res.projects : [];+ } catch (_) { uiToast(t('project.error.generic')); return; }++ const agents = await _convMoveAgents(cid, conv);+ const choice = await _openConversationProjectPicker(projects, agents);+ if (!choice) return;+ if (isConvPending(cid)) { uiToast(t('chat.conv_move_running')); return; }+ if (choice.create) { await _moveConversationToNewProject(cid, choice.agentIds); return; }+ const { projectId, agentIds } = choice;+ const picked = projects.find((p) => p && p.project_id === projectId);++ try {+ const moved = await _requestConversationMove(cid, projectId);+ await _applyConversationMoved(cid, moved);+ } catch (err) {+ uiToast(_convMoveErrorText(err && err.message));+ return;+ }+ await _finishConversationProjectMove(projectId, (picked && picked.name) || projectId, agentIds);+}diff --git a/src/renderer/modules/project-detail.js b/src/renderer/modules/project-detail.jsindex a51ab308..02dce12e 100644--- a/src/renderer/modules/project-detail.js+++ b/src/renderer/modules/project-detail.js@@ -2,8 +2,8 @@// Drives `#panel-project`: shows the project composer, task panes, and a// right-side rail for project agents + files.//-// Header carries Rename / Delete. The "Back" button was intentionally-// removed — the sidebar IS the back navigation.+// Header carries Rename / Delete. The "Back" button+// was intentionally removed — the sidebar IS the back navigation.//// Add picker and project-file viewer are centered modals (`.modal-overlay`)// so they don't get clipped by the project panel's scrolling regions.@@ -93,6 +93,7 @@ let _projectKbStatusRefreshTimer = null;let _projectKbReconcileInFlight = false;let _projectKbReconciledLoadSeq = -1;let _projectDetailLoadSeq = 0;+let _projectDetailResolvedPid = '';let _projectAutoTabLoad = null;let _projectAutoLoadedSeq = 0;let _projectRenameCommitInFlight = false;@@ -105,7 +106,6 @@ function _projectCachedSummary(pid) {function _setProjectDetailBusy(busy) {const content = document.getElementById('project-detail-content');if (!content) return;- content.classList.toggle('is-loading', !!busy);content.setAttribute('aria-busy', busy ? 'true' : 'false');}@@ -114,7 +114,11 @@ function _setProjectDetailBusy(busy) {/** Called by boot.js setView('project', pid) on entry. */async function loadProjectDetail(pid) {const loadSeq = ++_projectDetailLoadSeq;+ const account = typeof currentUserId === 'string' ? currentUserId : '';+ const isCurrent = () => loadSeq === _projectDetailLoadSeq && pid === _projectDetailPid+ && account === (typeof currentUserId === 'string' ? currentUserId : '');const prevPid = _projectDetailPid;+ if (prevPid !== pid) _projectDetailResolvedPid = '';if (prevPid && prevPid !== pid) {_projectLibraryDrafts.clear();_projectLibraryExpanded.clear();@@ -123,6 +127,7 @@ async function loadProjectDetail(pid) {_clearProjectLibraryViewer();}_projectDetailPid = pid || '';+ composerBindOwner('project-chat-input', _projectDetailPid);if (!_projectDetailPid) {_setProjectDetailBusy(false);_renderProjectDetailEmpty();@@ -147,8 +152,8 @@ async function loadProjectDetail(pid) {instructions: null,};_setProjectAutoTabCount(0);- // Paint the existing project shell immediately. Secondary cards remain in- // their empty/loading state while independent main-process work proceeds.+ // Paint the project shell immediately while independent local reads fill+ // its cards without loading placeholders._renderProjectDetail({ hydrateSecondary: false });if (_projectDetailActiveTab === 'auto') {_ensureProjectAutoTabLoaded(_projectDetailPid);@@ -181,21 +186,52 @@ async function loadProjectDetail(pid) {// off the bindings response alone rather than the whole batch below:// waiting for a large library's file tree would leave the stale target// sendable for that long.- const bindingsCall = window.orkas.invoke('projects.bindings.list', { projectId: pid });+ const getCall = window.orkas.invoke('projects.get', { projectId: pid });+ const bindingsCall = window.orkas.invoke('projects.bindings.list', { projectId: pid, localOnly: true });+ const filesCall = window.orkas.invoke('projects.files.tree', { projectId: pid });+ const instructionsCall = window.orkas.invoke('projects.instructions.get', { projectId: pid })+ .catch((err) => ({ ok: false, error: err?.message || String(err) }));bindingsCall.then((res) => {- if (loadSeq !== _projectDetailLoadSeq || pid !== _projectDetailPid) return;+ if (!isCurrent()) return;if (!res?.ok || typeof validateRecipientAgainstProject !== 'function') return;validateRecipientAgainstProject('project', pid, (res.bindings && res.bindings.agents) || []);}).catch(() => { /* the batch below owns the load failure */ });+ // Paint the Agent rail as soon as its own data is ready. A large file tree+ // or slow secondary card must not delay a newly added binding from showing.+ Promise.all([getCall, bindingsCall]).then(([getRes, listRes]) => {+ if (!isCurrent()) return;+ if (!getRes?.ok || !listRes?.ok || !_projectDetailMeta) return;+ _projectDetailMeta = {+ ..._projectDetailMeta,+ project: getRes.project,+ agentDetails: Array.isArray(listRes.agentDetails) ? listRes.agentDetails : [],+ };+ _renderProjectAgents();+ }).catch(() => { /* the batch below owns the load failure */ });+ void _loadProjectMemory(pid);+ // These cards read persisted project files. Show each answer as soon as it+ // arrives, even if an unrelated card or startup refresh is still pending.+ instructionsCall.then((res) => {+ if (!isCurrent() || !res?.ok || !_projectDetailMeta) return;+ _projectDetailMeta.instructions = { content: String(res.content || ''), limit: Number(res.limit) || 4000 };+ _renderProjectInstructions();+ }).catch(() => { /* the batch below owns the load failure */ });+ filesCall.then((res) => {+ if (!isCurrent() || !res?.ok || !_projectDetailMeta) return;+ _projectDetailMeta.files = Array.isArray(res.tree) ? res.tree : [];+ _renderProjectFiles(_projectDetailMeta.files);+ _bindProjectFileRows();+ if (typeof hydrateUiIcons === 'function') hydrateUiIcons(document.getElementById('project-files-list'));+ }).catch(() => { /* the batch below owns the load failure */ });const [getRes, listRes, filesRes, kbRes, instrRes, autoRes] = await Promise.all([- window.orkas.invoke('projects.get', { projectId: pid }),+ getCall,bindingsCall,- window.orkas.invoke('projects.files.tree', { projectId: pid }),+ filesCall,window.orkas.invoke('projects.files.status', { projectId: pid, skipReconcile: true }).catch((err) => ({ ok: false, error: err?.message || String(err) })),- window.orkas.invoke('projects.instructions.get', { projectId: pid }).catch((err) => ({ ok: false, error: err?.message || String(err) })),+ instructionsCall,window.orkas.invoke('autoTasks.list', { projectId: pid }).catch((err) => ({ ok: false, error: err?.message || String(err) })),]);- if (loadSeq !== _projectDetailLoadSeq || pid !== _projectDetailPid) return;+ if (!isCurrent()) return;if (!getRes?.ok || !listRes?.ok || !filesRes?.ok) {throw new Error((getRes && getRes.error) || (listRes && listRes.error) || (filesRes && filesRes.error) || 'load_failed');}@@ -209,17 +245,19 @@ async function loadProjectDetail(pid) {libraryStatus: kbRes?.ok ? kbRes : null,instructions: instrRes?.ok ? { content: String(instrRes.content || ''), limit: Number(instrRes.limit) || 4000 } : null,};- _renderProjectDetail();+ _projectDetailResolvedPid = pid;+ _renderProjectDetail({ refreshMemory: false });_setProjectAutoTabCount(Array.isArray(autoRes?.tasks) ? autoRes.tasks.length : 0);_kickProjectKbReconcileIfNeeded();_scheduleProjectKbStatusRefreshIfNeeded();+ _setProjectDetailBusy(false);} catch (err) {- if (loadSeq !== _projectDetailLoadSeq || pid !== _projectDetailPid) return;+ if (!isCurrent()) return;_projectDetailLog.warn('load project detail failed', err);if (typeof setView === 'function') setView('new-chat');if (typeof uiAlert === 'function') uiAlert(t('project.detail_load_failed'));} finally {- if (loadSeq === _projectDetailLoadSeq && pid === _projectDetailPid) {+ if (isCurrent()) {_setProjectDetailBusy(false);}}@@ -246,9 +284,32 @@ function _renderProjectDetailEmpty() {if (typeof _refreshUnreadTaskIndicators === 'function') _refreshUnreadTaskIndicators('');}-function _renderProjectDetail({ hydrateSecondary = true } = {}) {+function _renderProjectAgents() {+ const agentDetails = _projectDetailMeta?.agentDetails || [];+ const hasAgents = agentDetails.length > 0;+ const agentsList = document.getElementById('project-agents-list');+ if (agentsList) {+ agentsList.innerHTML = _renderProjectAgentCards(agentDetails);+ agentsList.style.display = hasAgents ? '' : 'none';+ }+ const agentsEmpty = document.getElementById('project-agents-empty');+ if (agentsEmpty) agentsEmpty.style.display = hasAgents ? 'none' : '';+ _setCardCount('project-detail-agents-count', agentDetails.length);+ _bindProjectAgentCards();+}++function _renderProjectDetail({ hydrateSecondary = true, refreshMemory = hydrateSecondary } = {}) {if (!_projectDetailMeta) { _renderProjectDetailEmpty(); return; }- const { project, agentDetails, files } = _projectDetailMeta;+ const { project, files } = _projectDetailMeta;+ const renameBtn = document.getElementById('project-action-rename');+ const deleteBtn = document.getElementById('project-action-delete');+ const addAgentBtn = document.getElementById('project-add-agent-btn');+ if (renameBtn) renameBtn.hidden = false;+ if (deleteBtn) {+ deleteBtn.hidden = false;+ deleteBtn.setAttribute('data-i18n', 'project.action.delete');+ }+ if (addAgentBtn) addAgentBtn.hidden = false;const titleEl = document.getElementById('project-detail-title');if (titleEl) titleEl.textContent = project?.name || '';@@ -256,14 +317,7 @@ function _renderProjectDetail({ hydrateSecondary = true } = {}) {_refreshUnreadTaskIndicators(_projectDetailPid);}- const agentsList = document.getElementById('project-agents-list');- const hasAgents = (agentDetails || []).length > 0;- if (agentsList) {- agentsList.innerHTML = _renderProjectAgentCards(agentDetails || []);- agentsList.style.display = hasAgents ? '' : 'none';- }- const agentsEmpty = document.getElementById('project-agents-empty');- if (agentsEmpty) agentsEmpty.style.display = hasAgents ? 'none' : '';+ _renderProjectAgents();_renderProjectFiles(files || []);_renderProjectAllTasks();_renderProjectInstructions();@@ -277,17 +331,15 @@ function _renderProjectDetail({ hydrateSecondary = true } = {}) {_bindProjectDriver();if (hydrateSecondary) {_loadProjectTodos(_projectDetailPid).catch(() => { /* ignore */ });- _loadProjectMemory(_projectDetailPid).catch(() => { /* ignore */ });+ if (refreshMemory) _loadProjectMemory(_projectDetailPid).catch(() => { /* ignore */ });_loadProjectDriver(_projectDetailPid).catch(() => { /* ignore */ });}// Per-card count chips beside each card title.- _setCardCount('project-detail-agents-count', (agentDetails || []).length);_setCardCount('project-detail-files-count', _flattenProjectLibraryFiles(files || []).length);applyDomI18n();_setProjectDetailRenameMode(_isProjectDetailRenameMode());- _bindProjectAgentCards();_bindProjectFileRows();if (typeof refreshWorkspaceChip === 'function') refreshWorkspaceChip();if (typeof hydrateUiIcons === 'function') hydrateUiIcons(document.getElementById('project-detail-content'));@@ -318,6 +370,7 @@ function _bindProjectDetailTabs() {// Re-read the persisted project setting on entry so a change made by// another surface/device is reflected by this tab's toggle._loadProjectDriver(_projectDetailPid);+ void _loadProjectTodos(_projectDetailPid);}});tab.addEventListener('keydown', (event) => {@@ -341,10 +394,6 @@ async function _ensureProjectAutoTabLoaded(pid) {// share one list refresh even when the first request finishes very quickly.if (_projectAutoLoadedSeq === _projectDetailLoadSeq) return;if (_projectAutoTabLoad?.pid === pid) return _projectAutoTabLoad.promise;- const listEl = document.getElementById('project-auto-list');- if (listEl && typeof loadProjectAutoList !== 'function') {- listEl.innerHTML = `<div class="empty muted">${escapeHtml(t('chat.loading'))}</div>`;- }const run = (async () => {const loader = typeof loadRendererFeature === 'function'? loadRendererFeature@@ -486,8 +535,10 @@ function _renderProjectInstructions() {if (!input) return;const meta = _projectDetailMeta?.instructions;const limit = (meta && Number(meta.limit)) || 4000;- input.value = meta ? meta.content : '';- input.dataset.savedValue = input.value;+ const editing = input.dataset.projectId === _projectDetailPid+ && document.getElementById('project-instructions-modal')?.classList.contains('open');+ if (!editing) input.value = meta ? meta.content : '';+ input.dataset.savedValue = meta ? meta.content : '';input.dataset.projectId = String(_projectDetailPid || '');input.dataset.limit = String(limit);// Instructions failed to load (e.g. legacy main) → disable rather than@@ -778,22 +829,29 @@ function _setProjectAutoTabCount(n) {// dispatched project agents receive it as read-only context.let _projectMemory = [];let _projectMemoryLoadSeq = 0;+let _projectMemoryLoadedPid = '';let _projectMemoryEditor = null; // { mode:'add'|'edit', oldText:string } | nulllet _projectMemoryMutating = false;async function _loadProjectMemory(pid) {const loadSeq = ++_projectMemoryLoadSeq;+ _projectMemoryLoadedPid = '';+ const account = typeof currentUserId === 'string' ? currentUserId : '';if (!pid) { _projectMemory = []; _renderProjectMemoryList(); return; }let nextMemory = [];+ let loaded = false;try {const res = await window.orkas.invoke('memory.list', { target: 'project', projectId: pid });- nextMemory = (res && res.ok && Array.isArray(res.entries)) ? res.entries : [];+ loaded = !!res?.ok && Array.isArray(res.entries);+ nextMemory = loaded ? res.entries : [];} catch (err) {_projectDetailLog.warn('load project memory failed', err);nextMemory = [];}- if (loadSeq !== _projectMemoryLoadSeq || pid !== _projectDetailPid) return;+ if (loadSeq !== _projectMemoryLoadSeq || pid !== _projectDetailPid+ || account !== (typeof currentUserId === 'string' ? currentUserId : '')) return;_projectMemory = nextMemory;+ _projectMemoryLoadedPid = loaded ? pid : '';_renderProjectMemoryList();}@@ -818,14 +876,14 @@ function _renderProjectMemoryList() {const actions = document.createElement('div');actions.className = 'project-memory-item-actions';- // Written-out verbs, not glyphs: these two sit under body copy the user- // is reading, and a pencil next to a paragraph reads as decoration.const edit = document.createElement('button');edit.type = 'button';edit.className = 'project-memory-item-action';edit.dataset.action = 'project-memory-edit';edit.dataset.memoryIndex = String(index);- edit.textContent = t('project.memory.edit');+ edit.title = t('project.memory.edit');+ edit.setAttribute('aria-label', edit.title);+ edit.innerHTML = _projectUiIconHtml('edit-pencil');actions.appendChild(edit);const remove = document.createElement('button');@@ -833,7 +891,9 @@ function _renderProjectMemoryList() {remove.className = 'project-memory-item-action is-danger';remove.dataset.action = 'project-memory-delete';remove.dataset.memoryIndex = String(index);- remove.textContent = t('project.memory.delete');+ remove.title = t('project.memory.delete');+ remove.setAttribute('aria-label', remove.title);+ remove.innerHTML = _projectUiIconHtml('trash');actions.appendChild(remove);row.appendChild(actions);@@ -1063,6 +1123,8 @@ let _todoEditorAgentLoading = false;// same shape the composer/auto editors use so the chip render can be shared.let _todoEditorTid = null;let _todoEditorAttachments = [];+// Existing tasks keep their files until the user commits the editor.+let _todoEditorRemovedAttachments = new Set();let _todoEditorSavedTid = false; // true once a create-draft's files are adopted// A fresh `t_<12hex>` matching the backend TASK_ID_RE, so the editor can stage@@ -1183,16 +1245,17 @@ function _setTodoLoadError(failed) {}function _renderProjectTodosList() {- const tasks = _projectTodos || [];+ let tasks = _projectTodos || [];const countEl = document.getElementById('project-todo-count');if (countEl) countEl.textContent = String(tasks.length);const listEl = document.getElementById('project-todo-list');if (!listEl) return;listEl.innerHTML = '';listEl.style.display = '';+ const context = _projectTodoContext();// The board always renders its four columns; each column carries its own// empty hint, so there is no list-level empty element.- listEl.appendChild(_renderTodoBoard(tasks, _projectTodoContext(), 'project:' + _projectDetailPid));+ listEl.appendChild(_renderTodoBoard(tasks, context, 'project:' + _projectDetailPid));}function _renderTodoCard(task, context) {@@ -1254,9 +1317,12 @@ function _renderTodoCard(task, context) {// get copied into the conversation the task starts, like a chat attachment).const attachCount = Array.isArray(task.attachments) ? task.attachments.length : 0;if (attachCount > 0) {- const att = document.createElement('span');+ const att = document.createElement('button');+ att.type = 'button';+ att.dataset.action = 'todo-attachments';att.className = 'project-todo-attach-badge';att.title = t('project.todo.attach_count', { n: attachCount });+ att.setAttribute('aria-label', att.title);att.innerHTML = (typeof uiIconHtml === 'function' ? uiIconHtml('paperclip', 'project-todo-attach-badge-icon') : '')+ `<span>${attachCount}</span>`;appendMeta(att);@@ -1395,7 +1461,7 @@ async function _loadTodoEditorAgents(task) {_updateProjectTodoEditor();try {const res = await window.orkas.invoke(pid ? 'projects.bindings.list' : 'agents.list',- pid ? { projectId: pid } : { summary: true });+ pid ? { projectId: pid, localOnly: true } : { summary: true });if (seq !== _todoEditorAgentLoadSeq || generation !== _todoEditorGeneration || pid !== _todoEditorPid) return;const agents = pid ? res?.agentDetails : res?.agents;if (res?.ok === false || !Array.isArray(agents)) throw new Error('load_failed');@@ -1438,18 +1504,54 @@ function _renderTodoEditorAttachments() {const label = escapeHtml(displayName);const spinner = busy ? `<span class="chat-attach-spinner" aria-label="${escapeHtml(t('chat.attach_uploading'))}"></span>` : '';const removeBtn = busy ? '' : `<span class="chat-attach-remove" data-idx="${idx}" title="${escapeHtml(t('chat.attach_remove_title'))}">×</span>`;- return `<div class="chat-attach-chip${busy ? ' is-uploading' : ''}" data-idx="${idx}" data-name="${escapeHtml((a && a.name) || '')}" title="${label}">`+ return `<div class="chat-attach-chip${busy ? ' is-uploading' : ''}"${busy ? '' : ' role="button" tabindex="0"'} data-idx="${idx}" data-name="${escapeHtml((a && a.name) || '')}" title="${label}">`+ `<span class="chat-attach-icon">${icon}</span>`+ `<span class="chat-attach-label">${label}</span>${spinner}${removeBtn}</div>`;}).join('');+ for (const chip of wrap.querySelectorAll('.chat-attach-chip:not(.is-uploading)')) {+ const preview = (event) => {+ if (event.target?.closest?.('.chat-attach-remove')) return;+ if (event.type === 'keydown' && event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ event.stopPropagation();+ const item = _todoEditorAttachments[Number(chip.dataset.idx)];+ if (item?.status === 'ready') void _previewTodoAttachment(_todoEditorPid, _todoEditorTid, item.name, chip);+ };+ chip.addEventListener('click', preview);+ chip.addEventListener('keydown', preview);+ }for (const rm of wrap.querySelectorAll('.chat-attach-remove')) {- rm.addEventListener('click', () => {+ rm.addEventListener('click', (event) => {+ event.stopPropagation();const item = _todoEditorAttachments[Number(rm.dataset.idx)];if (item && item.name) _removeTodoEditorAttachment(item.name);});}}+async function _previewTodoAttachment(pid, taskId, name, sourceElement) {+ if (pid === null || !taskId || !name || typeof openChatFileViewer !== 'function') return;+ try {+ const result = await window.orkas.invoke('projects.tasks.attachments.absPath', { projectId: pid, taskId, name });+ if (!result?.ok || !result.path) throw new Error('attachment_unavailable');+ await openChatFileViewer(result.path, name, { projectId: pid || null, cid: null, readOnly: true, sourceElement });+ } catch (_) {+ _projectDetailLog.warn('todo attachment preview failed');+ if (typeof uiAlert === 'function') await uiAlert(t('chat.file_missing_toast', { name }));+ }+}++function _openTodoAttachments(event, task, context) {+ const names = Array.isArray(task?.attachments) ? task.attachments : [];+ if (!names.length) return;+ const source = event.target?.closest?.('[data-action="todo-attachments"]');+ if (names.length === 1) return _previewTodoAttachment(context.pid || '', task.id, names[0], source);+ if (typeof showContextMenu === 'function') showContextMenu(event, names.map((name) => ({+ label: name,+ onClick: () => _previewTodoAttachment(context.pid || '', task.id, name, source),+ })));+}+function _setTodoEditorAttachments(items) {_todoEditorAttachments = Array.isArray(items) ? items : [];_renderTodoEditorAttachments();@@ -1460,7 +1562,7 @@ function _setTodoEditorAttachments(items) {// task's (possibly draft) attachment dir, showing an optimistic uploading chip.async function _todoPickAndUploadFiles(fileList) {const files = Array.from(fileList || []).filter(Boolean);- if (!files.length || _todoEditorPid === null) return;+ if (!files.length || _todoEditorPid === null || _projectTodoMutating) return;const pid = _todoEditorPid;const generation = _todoEditorGeneration;const accept = _todoAttachAccept();@@ -1472,7 +1574,7 @@ async function _todoPickAndUploadFiles(fileList) {pending.push(file);}if (rejected.length && typeof uiAlert === 'function') await uiAlert(t('chat.attach_rejected_prefix', { list: rejected.join('\n') }));- if (!pending.length || generation !== _todoEditorGeneration) return;+ if (!pending.length || generation !== _todoEditorGeneration || _projectTodoMutating) return;const tid = _ensureTodoEditorTid();const placeholders = pending.map((file) => {@@ -1501,15 +1603,22 @@ async function _todoPickAndUploadFiles(fileList) {const next = _todoEditorAttachments.slice();const idx = next.findIndex((it) => it && it.tempId === p.tempId);if (idx < 0) return;- if (ok) next[idx] = { name: finalName, displayName: p.displayName, kind: _todoAttachKind(finalName), bytes: p.file.size || 0, status: 'ready' };- else next.splice(idx, 1);+ if (ok) {+ _todoEditorRemovedAttachments.delete(finalName);+ next[idx] = { name: finalName, displayName: p.displayName, kind: _todoAttachKind(finalName), bytes: p.file.size || 0, status: 'ready' };+ } else next.splice(idx, 1);_setTodoEditorAttachments(next);_updateProjectTodoEditor();}));}async function _removeTodoEditorAttachment(name) {- if (!name || _todoEditorPid === null || !_todoEditorTid) return;+ if (!name || _todoEditorPid === null || !_todoEditorTid || _projectTodoMutating) return;+ if (_todoEditorTaskId) {+ _todoEditorRemovedAttachments.add(name);+ _setTodoEditorAttachments(_todoEditorAttachments.filter((a) => !a || a.name !== name));+ return;+ }const generation = _todoEditorGeneration;try {const res = await window.orkas.invoke('projects.tasks.attachments.delete', {@@ -1537,7 +1646,8 @@ function _openProjectTodoEditor(task, context = _projectTodoContext(), status =_todoEditorPid = context.pid || '';_todoEditorReturnFocus = document.activeElement;_todoEditorTaskId = task && task.id ? task.id : null;- _todoEditorInitial = task ? { status: task.status || 'todo', owner_agent: task.owner_agent, owner_agent_id: task.owner_agent_id } : null;+ _todoEditorInitial = task ? { status: task.status || 'todo', owner_agent: task.owner_agent,+ owner_agent_id: task.owner_agent_id, } : null;// Edit stages attachments onto the real task; create lazily allocates a draft// id on first attach (adopted by create on save, discarded on cancel)._todoEditorTid = _todoEditorTaskId;@@ -1600,7 +1710,7 @@ function _closeProjectTodoEditor() {_todoEditorReleaseFocus?.();_todoEditorReleaseFocus = null;// Create-mode cancel with staged-but-unsaved files: drop the draft dir so the- // uploads aren't orphaned. Edit-mode attachment changes are already persisted.+ // uploads aren't orphaned. Edit-mode removals are only committed by Save.if (!_todoEditorSavedTid && !_todoEditorTaskId && _todoEditorTid && _todoEditorPid !== null) {window.orkas.invoke('projects.tasks.attachments.discardDraft', { projectId: _todoEditorPid, taskId: _todoEditorTid }).catch((err) => _projectDetailLog.warn('todo draft discard failed', err));@@ -1612,6 +1722,7 @@ function _closeProjectTodoEditor() {_todoEditorInitial = null;_todoEditorTid = null;_todoEditorSavedTid = false;+ _todoEditorRemovedAttachments.clear();_setTodoEditorAttachments([]);const editor = document.getElementById('project-todo-add');const input = document.getElementById('project-todo-input');@@ -1646,7 +1757,7 @@ async function _todoMutate(fn, pid = _projectDetailPid) {if (!ok && typeof uiAlert === 'function') uiAlert(t('project.todo.failed'));try {if (pid && pid === _projectDetailPid) await _loadProjectTodos(pid);- if (typeof _refreshGlobalTodos === 'function') await _refreshGlobalTodos(pid);+ if (typeof _refreshGlobalTodos === 'function') void _refreshGlobalTodos(pid).catch(() => {});} finally {_projectTodoMutating = false;_updateProjectTodoEditor();@@ -1671,21 +1782,36 @@ async function _saveProjectTodoEditor() {const startedAt = Date.now();// Create passes the pre-allocated draft id when files were staged so the// persisted task adopts them. Edits update the existing task in place.- const outcome = await _todoMutate(() => (taskId- ? window.orkas.invoke('projects.tasks.update', {- projectId: pid,- taskId,- content,- ...(status !== _todoEditorInitial?.status ? { status } : {}),- ...owner,- })- : window.orkas.invoke('projects.tasks.create', {- projectId: pid,- content,- status,- ...owner,- ...(_todoEditorTid ? { taskId: _todoEditorTid } : {}),- })), pid);+ const outcome = await _todoMutate(async () => {+ const result = await (taskId+ ? window.orkas.invoke('projects.tasks.update', {+ projectId: pid,+ taskId,+ content,+ ...(status !== _todoEditorInitial?.status ? { status } : {}),+ ...owner,+ })+ : window.orkas.invoke('projects.tasks.create', {+ projectId: pid,+ content,+ status,+ ...owner,+ ...(_todoEditorTid ? { taskId: _todoEditorTid } : {}),+ }));+ if (result?.ok === false) return result;+ // Save content first: a rejected edit must not delete any attachment.+ // Retain only unsuccessful removals so a retry cannot delete a file again.+ if (taskId) {+ for (const name of _todoEditorRemovedAttachments) {+ const removed = await window.orkas.invoke('projects.tasks.attachments.delete', {+ projectId: pid, taskId, name,+ });+ if (!removed?.ok) return { ok: false, error: 'attachment_delete_failed' };+ _todoEditorRemovedAttachments.delete(name);+ }+ }+ return result;+ }, pid);if (!outcome.ok) {_projectLogFailure('project_todo_action', { action: taskId ? 'edit' : 'create', ...outcome.failure });} else if (generation === _todoEditorGeneration) {@@ -1955,7 +2081,10 @@ function _bindTodoListActions(listEl, resolveContext) {if (!tid || _projectTodoMutating) return;const context = resolveContext(row.dataset.pid);if (!_todoContextHasScope(context)) return;- if (e.target.closest('[data-action="todo-project"]')) {+ if (e.target.closest('[data-action="todo-attachments"]')) {+ e.stopPropagation();+ void _openTodoAttachments(e, context.tasks.find((task) => task.id === tid), context);+ } else if (e.target.closest('[data-action="todo-project"]')) {_projectDetailActiveTab = 'todo';setView('project', context.pid);} else if (e.target.closest('[data-action="todo-conversation"]')) {@@ -3889,7 +4018,9 @@ async function _submitProjectChat() {const projectId = _projectDetailPid;const input = document.getElementById('project-chat-input');const btn = document.getElementById('project-chat-send-btn');- const raw = (input?.value || '').trim();+ const submittedDraft = composerSnapshot(input);+ const navigationEpoch = _composerNavigationEpoch;+ const raw = submittedDraft.text().trim();const draftCid = _projectChatDraftCid(projectId);const quotes = (typeof _getQuotes === 'function') ? _getQuotes(draftCid).slice() : [];if (!raw && !quotes.length) return;@@ -3967,9 +4098,10 @@ async function _submitProjectChat() {const conv = data.conversation;convId = conv.conversation_id;if (titleText) {- conv.title = (typeof _autoTitle === 'function')- ? _autoTitle(titleText)- : (titleText.length > 25 ? `${titleText.slice(0, 25)}…` : titleText);+ // Optimistic only: the persisted title comes from the backend+ // `autoTitle`. Without the shared helper loaded there is no width table+ // to cut against, so show the text as typed until the backend replies.+ conv.title = (typeof _autoTitle === 'function') ? _autoTitle(titleText) : titleText;}createdConversation = conv;} catch (err) {@@ -4046,25 +4178,28 @@ async function _submitProjectChat() {if (typeof loadProjects === 'function') loadProjects(true);}if (typeof consumeChatUseSelections === 'function') consumeChatUseSelections('project');- if (typeof _clearQuotes === 'function') _clearQuotes(draftCid);+ _consumeSubmittedQuotes(draftCid, quotes);- if (input) {- input.value = '';+ const ownsDraft = submittedDraft.matches();+ const openCreated = ownsDraft && navigationEpoch === _composerNavigationEpoch;+ if (ownsDraft) {+ composerSetText(input, '');if (typeof _draftHadRecipient !== 'undefined') _draftHadRecipient.delete('project');- if (typeof autoGrow === 'function') autoGrow(input, 180);+ if (typeof _updateComposerSeqToggle === 'function') _updateComposerSeqToggle('project');}- if (typeof _updateComposerSeqToggle === 'function') _updateComposerSeqToggle('project');- const chatInput = document.getElementById('chat-input');- if (chatInput) {- chatInput.value = '';- if (typeof autoGrow === 'function') autoGrow(chatInput, 200);+ if (recipient) {+ _recipientByCid[convId] = recipient.defaultRecipient || recipient;+ _saveRecipientMap();}- if (typeof setView === 'function') setView('conversation', convId, { skipLoad: true });- if (recipient && typeof setChatRecipient === 'function') {- setChatRecipient('conversation', recipient.defaultRecipient || recipient);+ if (openCreated) {+ if (currentCid) _flushDraftSave(currentCid);+ composerBindOwner('chat-input', convId);+ composerSetText('chat-input', '');+ setView('conversation', convId, { skipLoad: true });+ if (recipient) setChatRecipient('conversation', recipient.defaultRecipient || recipient);}if (btn) btn.disabled = false;- if (typeof sendInCurrentConversation === 'function') {+ if (typeof sendInConversation === 'function') {const extra = {title_text: titleText,...commanderDisplay,@@ -4081,7 +4216,11 @@ async function _submitProjectChat() {attachments: _adopted.map((name) => ({ name })),});}- await sendInCurrentConversation(content, Object.keys(extra).length ? extra : undefined, { restoreComposerOnFailure: true });+ await sendInConversation(convId, content, Object.keys(extra).length ? extra : undefined, {+ restoreComposerOnFailure: true,+ source_view: 'project',+ content_length: requestText.length,+ });}}@@ -4132,7 +4271,9 @@ async function _openAddPicker() {projectId: _projectDetailPid,});if (!res?.ok) throw new Error(res?.error || 'load_failed');- candidates = (res.agents || []).slice().sort(_byDisplayName);+ // Group custom agents first; retain the existing name order within each source.+ candidates = (res.agents || []).slice().sort((a, b) =>+ Number(b.source === 'custom') - Number(a.source === 'custom') || _byDisplayName(a, b));} catch (err) {_projectDetailLog.warn('load candidates failed', err);return;@@ -4194,13 +4335,14 @@ async function _openAddPicker() {const descHtml = desc ? `<div class="project-binding-desc muted">${escapeHtml(desc)}</div>` : '';const source = _projectBindingSourceHtml(c.source);return `- <div class="project-binding-picker-item" data-kind="agent" data-id="${escapeHtml(id)}">+ <div class="project-binding-picker-item" data-kind="agent" data-id="${escapeHtml(id)}" data-source="${escapeHtml(c.source || '')}"><div class="project-binding-main"><div class="project-binding-head"><span class="project-binding-name">${name}</span>${source}</div>${descHtml}+</div><button type="button" class="btn btn-sm" data-action="pick" aria-label="Add">+</button></div>@@ -4218,6 +4360,8 @@ async function _openAddPicker() {const k = row.dataset.kind;const projectId = _projectDetailPid;const startedAt = performance.now();+ btn.disabled = true;+ btn.textContent = t('common.processing');try {const res = await window.orkas.invoke('projects.bindings.add', {projectId, kind: k, id,@@ -4236,9 +4380,12 @@ async function _openAddPicker() {loadProjectDetail(projectId).catch((err) => _projectDetailLog.warn('refresh failed', err));}} catch (err) {+ btn.disabled = false;+ btn.textContent = '+';const failure = _projectDetailFailure(err, 'binding_add_failed');_projectLogFailure('project_binding_add', { binding_kind: k, ...failure });_projectDetailLog.warn('add binding failed', err);+ await uiAlert(t('project.bindings.add_failed'));}});});@@ -4282,6 +4429,7 @@ function _onRenameAction() {async function _commitRename(newName) {if (!_projectDetailPid || !_projectDetailMeta || _projectRenameCommitInFlight) return;+ const projectId = _projectDetailPid;const old = _projectDetailMeta.project?.name || '';let trimmed = String(newName || '').trim();if (typeof window.limitNameDisplayText === 'function') trimmed = window.limitNameDisplayText(trimmed);@@ -4296,7 +4444,7 @@ async function _commitRename(newName) {_projectRenameCommitInFlight = true;try {const res = await window.orkas.invoke('projects.rename', {- projectId: _projectDetailPid, name: trimmed,+ projectId, name: trimmed,});if (!res || !res.ok) {code = (res && res.error) || 'generic';@@ -4397,6 +4545,8 @@ function _initProjectDetailBindings() {window.orkas.onPushEvent('projects:advance', _onProjectAdvance);window.orkas.onPushEvent('projects:tasks-changed', _onProjectTasksChanged);}+ window.addEventListener('i18n-change', () => {+ });document.getElementById('project-add-agent-btn')?.addEventListener('click', (e) => {e.stopPropagation();_openAddPicker();@@ -4438,17 +4588,10 @@ function _initProjectDetailBindings() {});const projectInput = document.getElementById('project-chat-input');if (projectInput) {- projectInput.addEventListener('input', () => {+ projectInput.addEventListener(composerChangeEvent(projectInput), () => {if (typeof autoGrow === 'function') autoGrow(projectInput, 180);});- projectInput.addEventListener('keydown', (e) => {- if (e.isComposing || e.keyCode === 229) return;- if (_handleModifiedComposerEnter(e)) return;- if (_isPlainComposerEnter(e)) {- e.preventDefault();- _submitProjectChat();- }- });+}document.getElementById('project-chat-send-btn')?.addEventListener('click', (e) => {e.stopPropagation();diff --git a/src/renderer/modules/projects.js b/src/renderer/modules/projects.jsindex 03cd4cf4..837eb9ee 100644--- a/src/renderer/modules/projects.js+++ b/src/renderer/modules/projects.js@@ -276,9 +276,7 @@ function _renderProjectRow(p, convs) {const expanded = !!_projectsExpanded[p.project_id];const selected = _isProjectSelected(p.project_id);const editing = _projectsInlineRenamePid === p.project_id;- const folderIcon = expanded- ? _projectUiIconHtml('folder-open', 'project-folder-icon')- : _projectUiIconHtml('folder', 'project-folder-icon');+ const folderIcon = _projectUiIconHtml('folder', 'project-folder-icon');const moreTitle = escapeHtml(t('project.menu.more_actions'));const safeName = escapeHtml(p.name || '');const renameErrorClass = editing && _projectsInlineRenameError ? ' is-error' : '';@@ -778,23 +776,6 @@ async function _runProjectMenuAction(action, pid) {if (action === 'delete') return _confirmDeleteProject(pid);}-async function _showProjectMemberInviteGate() {- const download = await uiConfirm({- message: t('project.invite_members.commercial_only'),- okLabel: t('project.invite_members.download'),- cancelLabel: t('common.cancel'),- });- if (!download) return;- const lang = getLang();- const url = `https://orkas.ai/download/?lang=${encodeURIComponent(lang)}`;- try {- const result = await window.orkas.invoke('auth.openExternal', { url });- if (!result?.ok) throw new Error('open rejected');- } catch (_) {- await uiAlert(t('project.invite_members.open_failed'));- }-}-// ── Delete flow ─────────────────────────────────────────────────────────function _pickProjectDeleteFallback(deletedPid, projectsBeforeDelete, projectsAfterDelete, conversationsAfterDelete) {@@ -1010,3 +991,20 @@ document.addEventListener('DOMContentLoaded', () => {});if (typeof window !== 'undefined') window.primeProjectDetailShell = primeProjectDetailShell;++async function _showProjectMemberInviteGate() {+ const download = await uiConfirm({+ message: t('project.invite_members.commercial_only'),+ okLabel: t('project.invite_members.download'),+ cancelLabel: t('common.cancel'),+ });+ if (!download) return;+ const lang = getLang();+ const url = `https://orkas.ai/download/?lang=${encodeURIComponent(lang)}`;+ try {+ const result = await window.orkas.invoke('auth.openExternal', { url });+ if (!result?.ok) throw new Error('open rejected');+ } catch (_) {+ await uiAlert(t('project.invite_members.open_failed'));+ }+}diff --git a/src/renderer/modules/todos.js b/src/renderer/modules/todos.jsindex 4ef35286..54fc6e77 100644--- a/src/renderer/modules/todos.js+++ b/src/renderer/modules/todos.js@@ -4,6 +4,9 @@let _globalTodoGroups = [];let _globalTodoProjects = [];let _globalTodoMode = 'project';+// Presentation-only: the by-project view paints one scope at a time ('' is the+// global scope). Never persisted, and never narrows what a load fetches.+let _globalTodoActiveScope = null;let _globalTodoLoadSeq = 0;let _globalTodoRefreshTimer = null;// True until a full load commits (and again after any failed load): a change@@ -213,6 +216,33 @@ function _renderGlobalTodoDriverBar(groups) {return bar;}+function _renderGlobalTodoScopeSwitcher(groups) {+ const nav = document.createElement('nav');+ nav.className = 'todo-scope-switcher';+ nav.setAttribute('aria-label', t('todo.by_project'));+ for (const group of groups) {+ const pid = group.project.project_id || '';+ const chip = document.createElement('button');+ chip.type = 'button';+ chip.className = 'todo-scope-chip';+ chip.dataset.pid = pid;+ chip.setAttribute('aria-pressed', String(pid === _globalTodoActiveScope));+ const folder = typeof uiIconHtml === 'function'+ ? uiIconHtml('folder', 'todo-scope-chip-icon')+ : '';+ chip.innerHTML = folder+ + `<span class="todo-scope-chip-name">${escapeHtml(group.project.name)}</span>`+ + `<span class="todo-scope-chip-count">${group.tasks.length}</span>`;+ chip.addEventListener('click', () => {+ if (_globalTodoActiveScope === pid) return;+ _globalTodoActiveScope = pid;+ _renderGlobalTodos();+ });+ nav.appendChild(chip);+ }+ return nav;+}+function _renderGlobalTodos() {const host = document.getElementById('todos-content');if (!host) return;@@ -237,36 +267,21 @@ function _renderGlobalTodos() {}, 'global:status'));return;}+ const scopes = groups.map((group) => group.project.project_id || '');+ // A scope that emptied out since the last paint drops off the switcher, so+ // fall back to the first one rather than painting nothing.+ if (!scopes.includes(_globalTodoActiveScope)) _globalTodoActiveScope = scopes[0];+ host.appendChild(_renderGlobalTodoScopeSwitcher(groups));for (const group of groups) {const pid = group.project.project_id;+ if ((pid || '') !== _globalTodoActiveScope) continue;const section = document.createElement('section');- section.className = 'todo-project-group auto-group';+ section.className = 'todo-project-group';section.dataset.pid = pid;- const header = document.createElement('div');- header.className = 'todo-project-head auto-group-head';- const toggle = document.createElement('button');- toggle.type = 'button';- toggle.className = 'todo-collapse auto-group-toggle';const key = 'global:project:' + pid;- const collapsed = _todoCollapsed.get(key) || false;- toggle.setAttribute('aria-expanded', String(!collapsed));- const folder = typeof uiIconHtml === 'function'- ? `<span class="auto-group-icon">${uiIconHtml(collapsed ? 'folder' : 'folder-open', 'auto-group-folder-icon')}</span>`- : '';- toggle.innerHTML = folder + '<strong class="auto-group-name">' + escapeHtml(group.project.name)- + '</strong><span class="auto-group-count">' + group.tasks.length + '</span>';const board = _renderTodoBoard(group.tasks, _globalTodoContext(pid), key);- board.className += ' auto-group-list';- board.hidden = collapsed;- toggle.addEventListener('click', () => {- board.hidden = !board.hidden;- _todoCollapsed.set(key, board.hidden);- toggle.setAttribute('aria-expanded', String(!board.hidden));- if (typeof uiIconHtml === 'function') {- const icon = toggle.querySelector('.auto-group-icon');- if (icon) icon.innerHTML = uiIconHtml(board.hidden ? 'folder' : 'folder-open', 'auto-group-folder-icon');- }- });+ const actions = document.createElement('div');+ actions.className = 'todo-scope-actions';const add = document.createElement('button');add.type = 'button';add.className = 'project-todo-menu todo-project-add';@@ -279,11 +294,10 @@ function _renderGlobalTodos() {// place for choosing a different project or the global scope._openProjectTodoEditor(null, { ...context, projects: undefined });});- header.appendChild(toggle);- if (group === groups[0]) header.appendChild(_renderGlobalTodoDriverHint());- header.appendChild(_renderGlobalTodoDriverToggle(group, false));- header.appendChild(add);- section.appendChild(header);+ actions.appendChild(_renderGlobalTodoDriverHint());+ actions.appendChild(_renderGlobalTodoDriverToggle(group, false));+ actions.appendChild(add);+ section.appendChild(actions);section.appendChild(board);host.appendChild(section);}diff --git a/test/e2e/projects_e2e_smoke.spec.ts b/test/e2e/projects_e2e_smoke.spec.tsindex f9124702..eb2346fc 100644--- a/test/e2e/projects_e2e_smoke.spec.ts+++ b/test/e2e/projects_e2e_smoke.spec.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';import path from 'node:path';import { expect, test, type OrkasTestApp } from './fixtures/orkas';@@ -14,6 +14,16 @@ async function expectProjectFileReady(orkas: OrkasTestApp, projectId: string, fi}, { timeout: 40_000 }).toEqual({ status: 'ready', error: null });}+/** The unprojected `cloud/chats` dir of whichever account the run activated. */+function globalChatsDir(workspaceRoot: string): string {+ for (const entry of readdirSync(workspaceRoot, { withFileTypes: true })) {+ if (!entry.isDirectory()) continue;+ const candidate = path.join(workspaceRoot, entry.name, 'cloud', 'chats');+ if (existsSync(candidate)) return candidate;+ }+ throw new Error('global chats dir not found');+}+async function createProject(orkas: OrkasTestApp, name: string): Promise<void> {if (!orkas.page) throw new Error('Orkas renderer is unavailable');const page = orkas.page;@@ -156,6 +166,8 @@ test.describe('projects', () => {await orkas.invoke('projects.tasks.delete', { projectId, taskId });await expect(todo).toHaveCount(0);await page.locator('[data-project-tab="tasks"]').click();+ // Memory actions become interactive when the user hovers the entry.+ await memory.hover();await memory.locator('[data-action="project-memory-delete"]').click();await expect(page.locator('.ui-dialog-overlay:visible .ui-dialog')).toBeVisible();await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();@@ -438,16 +450,21 @@ test.describe('projects', () => {const concurrentUiEdit = `${replacement}\nUse the July launch checklist.`;const staleModelReplacement = `${replacement}\nPublish on Friday.`;const conflictReply = 'E2E stale project-instructions replacement was rejected.';- modelOrkas.setProjectInstructionsScenario(staleModelReplacement, conflictReply, {- toolDelayMs: 750,- });+ // Hold the tool response until the concurrent edit is actually persisted.+ // A fixed delay races the IPC round trip on a busy host and can test the+ // opposite ordering, where accepting the tool write is correct.+ let releaseTool!: () => void;+ const beforeTool = new Promise<void>((resolve) => { releaseTool = resolve; });+ modelOrkas.setProjectInstructionsScenario(staleModelReplacement, conflictReply, { beforeTool });await page.locator('#chat-input').fill('Also add that publishing happens on Friday.');await page.locator('#chat-send-btn').click();- await expect.poll(() => modelOrkas.modelRequests.length).toBe(4);- await modelOrkas.invoke('projects.instructions.set', {- projectId,- content: concurrentUiEdit,- });+ try {+ await expect.poll(() => modelOrkas.modelRequests.length).toBe(4);+ await modelOrkas.invoke('projects.instructions.set', {+ projectId,+ content: concurrentUiEdit,+ });+ } finally { releaseTool(); }await expect(page.locator('#chat-history .chat-message.assistant [data-role="final"]', {hasText: conflictReply,})).toBeVisible({ timeout: 20_000 });@@ -556,6 +573,12 @@ test.describe('projects', () => {const picker = page.locator('#project-binding-picker-overlay');await expect(picker).toBeVisible();const pickerDialog = picker.locator('.project-binding-picker-modal');+ const headerCenters = await pickerDialog.evaluate((dialog) => {+ const title = dialog.querySelector('.project-binding-picker-title')!.getBoundingClientRect();+ const close = dialog.querySelector('.project-binding-picker-close')!.getBoundingClientRect();+ return [title.top + title.height / 2, close.top + close.height / 2];+ });+ expect(Math.abs(headerCenters[0] - headerCenters[1])).toBeLessThan(2);const searchInput = picker.locator('#project-binding-picker-search-input');const initialPickerHeight = await pickerDialog.evaluate((element) => element.getBoundingClientRect().height);await expect(searchInput).toHaveCSS('background-color', 'rgba(0, 0, 0, 0)');@@ -780,4 +803,268 @@ test.describe('projects', () => {const relaunchedPage = await orkas.relaunch();await expect(relaunchedPage.locator('.project-name', { hasText: projectName })).toHaveCount(1);});++ // Filing a loose task under a project relocates its messages, sessions,+ // attachments and artifacts on disk, so the check is that the task still+ // opens and reads the same afterwards — not just that a row moved.+ test('keeps the conversation project picker modal and settles replaced pickers', async ({ orkas }) => {+ const page = orkas.page!;+ await page.evaluate(() => {+ const host = window as any;+ host.__pickerResult = 'pending';+ host._openConversationProjectPicker([{ project_id: 'p_one', name: 'One' }])+ .then((result: unknown) => { host.__pickerResult = result; });+ });+ const overlay = page.locator('#conv-project-picker-overlay');+ const row = overlay.locator('.conv-project-pick-row');+ await expect(row).toBeFocused();+ await page.keyboard.press('Shift+Tab');+ await expect(overlay.locator('[data-act="cancel"]')).toBeFocused();+ await page.keyboard.press('Tab');+ await expect(row).toBeFocused();+ await page.evaluate(() => {+ const host = window as any;+ host.__replacementResult = 'pending';+ host._openConversationProjectPicker([{ project_id: 'p_two', name: 'Two' }])+ .then((result: unknown) => { host.__replacementResult = result; });+ });+ await expect.poll(() => page.evaluate(() => (window as any).__pickerResult)).toBe(null);+ await expect(overlay.locator('.conv-project-pick-row')).toHaveText('Two');+ await page.keyboard.press('Escape');+ await expect(overlay).toHaveCount(0);+ await expect.poll(() => page.evaluate(() => (window as any).__replacementResult)).toBe(null);+ await page.evaluate(() => { (window as any)._openConversationProjectPicker([]); });+ await expect(overlay.locator('[data-act="new"]')).toBeFocused();+ await expect(overlay.locator('[data-act="ok"]')).toBeDisabled();+ await page.keyboard.press('Escape');+ await expect(overlay).toHaveCount(0);++ });++ test('hides commander-only agents and scrolls long project and agent lists inside the panel', async ({ orkas }, testInfo) => {+ const page = orkas.page!;+ const { conversation } = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: 'Commander only' });+ await page.evaluate(() => (window as any).loadConversations());+ const row = page.locator(`#conversation-list .conv-item[data-cid="${conversation.conversation_id}"]`);+ await row.hover();+ await row.locator('.conv-item-menu').click();+ await page.locator('#conversation-action-menu [data-action="to-project"]').click();+ const picker = page.locator('#conv-project-picker-overlay');+ await expect(picker).toBeVisible();+ await expect(picker.locator('.conv-project-agents')).toHaveCount(0);+ await page.keyboard.press('Escape');++ await page.setViewportSize({ width: 1000, height: 600 });+ await page.evaluate(() => {+ const host = window as any;+ host.__longPickerResult = null;+ host._openConversationProjectPicker(+ Array.from({ length: 20 }, (_, index) => ({ project_id: `p_${index}`, name: `Project ${index + 1}` })),+ Array.from({ length: 20 }, (_, index) => ({ id: `agent_${index}`, name: `Agent ${index + 1}` })),+ ).then((result: unknown) => { host.__longPickerResult = result; });+ });+ await expect(picker.getByRole('checkbox')).toHaveCount(20);+ for (const [selector, max] of [['.conv-project-pick-list', 252], ['.conv-project-agent-list', 150]] as const) {+ const list = picker.locator(selector);+ const metrics = await list.evaluate((el) => ({ height: el.clientHeight, content: el.scrollHeight }));+ expect(metrics.height).toBeGreaterThan(0);+ expect(metrics.height).toBeLessThanOrEqual(max);+ expect(metrics.content).toBeGreaterThan(metrics.height);+ await list.evaluate((el) => { el.scrollTop = el.scrollHeight; });+ expect(await list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);+ }+ await picker.locator('.conv-project-pick-row').last().click();+ await picker.getByRole('checkbox').last().uncheck();+ const bounds = await picker.locator('[role="dialog"]').evaluate((el) => ({+ top: el.getBoundingClientRect().top, bottom: el.getBoundingClientRect().bottom,+ height: el.clientHeight, content: el.scrollHeight,+ }));+ expect(bounds.top).toBeGreaterThanOrEqual(0);+ expect(bounds.bottom).toBeLessThanOrEqual(600);+ expect(bounds.content).toBeLessThanOrEqual(bounds.height + 1);+ const agentBottom = await picker.locator('.conv-project-agent-list').evaluate((el) => el.getBoundingClientRect().bottom);+ const actionsTop = await picker.locator('.modal-actions').evaluate((el) => el.getBoundingClientRect().top);+ expect(agentBottom).toBeLessThanOrEqual(actionsTop);+ await page.evaluate(() => (window as any).setLang('zh'));+ await picker.locator('[role="dialog"]').screenshot({ path: testInfo.outputPath('add-to-project-scroll-zh.png') });+ await picker.locator('[data-act="ok"]').click();+ await expect.poll(() => page.evaluate(() => (window as any).__longPickerResult)).toEqual({+ projectId: 'p_19', agentIds: Array.from({ length: 19 }, (_, index) => `agent_${index}`),+ });+ });++ test('files a loose task into new and existing projects with the selected agents', async ({ orkas }, testInfo) => {+ if (!orkas.page) throw new Error('Orkas renderer is unavailable');+ const agent = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {+ name: 'E2EFilingAgent',+ description: 'Takes part in the task being filed.',+ category: 'general',+ });+ const agentId = agent.agent.agent_id;+ const optionalAgent = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {+ name: 'E2EOptionalAgent', description: 'Can be excluded when filing.', category: 'general',+ });+ const optionalId = optionalAgent.agent.agent_id;++ const loose = await orkas.invoke<{ conversation: { conversation_id: string } }>(+ 'conversations.create', { title: 'Loose filing task' });+ const cid = loose.conversation.conversation_id;+ const second = await orkas.invoke<{ conversation: { conversation_id: string } }>(+ 'conversations.create', { title: 'Second loose task' });++ // The participant roster is what the new-project flow binds. Seeding it is+ // the deterministic stand-in for an @-mention turn.+ const chatsDir = globalChatsDir(orkas.workspaceRoot);+ mkdirSync(path.join(chatsDir, cid), { recursive: true });+ writeFileSync(path.join(chatsDir, cid, 'members.json'), JSON.stringify({+ version: 1,+ actors: [+ { kind: 'agent', id: agentId, name: 'E2EFilingAgent', joined_at: new Date().toISOString() },+ { kind: 'agent', id: optionalId, name: 'E2EOptionalAgent', joined_at: new Date().toISOString() },+ ],+ }));+ writeFileSync(path.join(chatsDir, `${cid}.jsonl`),+ `${JSON.stringify({ from: 'user', text: 'filed message body', ts: new Date().toISOString() })}\n`);++ mkdirSync(path.join(chatsDir, second.conversation.conversation_id), { recursive: true });+ writeFileSync(path.join(chatsDir, second.conversation.conversation_id, 'members.json'), JSON.stringify({+ version: 1, actors: [+ { kind: 'agent', id: agentId, name: 'E2EFilingAgent' },+ { kind: 'agent', id: optionalId, name: 'E2EOptionalAgent' },+ ],+ }));+ const page = await orkas.relaunch();+ const row = page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`);+ await expect(row).toHaveCount(1);++ // A running task keeps a visible, disabled entry. Finishing the task+ // enables the already-open menu without reopening or navigating away.+ await page.evaluate((taskId) => {+ (window as any).setGroupConversationBusy(taskId, true);+ }, cid);+ await row.hover();+ await row.locator('.conv-item-menu').click();+ const moveItem = page.locator('#conversation-action-menu [data-action="to-project"]');+ await expect(moveItem).toHaveAttribute('aria-disabled', 'true');+ await expect(moveItem).toHaveClass(/is-disabled/);+ await moveItem.dispatchEvent('click');+ await expect(page.locator('#conv-project-picker-overlay')).toHaveCount(0);+ await page.evaluate((taskId) => {+ (window as any).setGroupConversationBusy(taskId, false);+ (window as any)._updateConvSidebarBadge(taskId);+ }, cid);+ await expect(moveItem).toHaveAttribute('aria-disabled', 'false');+ await row.locator('.conv-item-menu').click();++ // New project: name it, and the task plus its agent land inside.+ await row.hover();+ await row.locator('.conv-item-menu').click();+ await expect(page.locator('#conversation-action-menu [data-action="to-new-project"]')).toHaveCount(0);+ await page.locator('#conversation-action-menu [data-action="to-project"]').click();+ const firstPicker = page.locator('#conv-project-picker-overlay');+ await expect(firstPicker.locator('.avatar-circle svg')).toHaveCount(2);+ await expect(firstPicker.locator('.conv-project-agents .conv-project-picker-hint')).toHaveCount(0);+ await expect(firstPicker.getByRole('checkbox', { name: 'E2EFilingAgent', exact: true })).toBeChecked();+ await expect(firstPicker.getByRole('checkbox', { name: 'E2EOptionalAgent', exact: true })).toBeChecked();+ await firstPicker.getByRole('checkbox', { name: 'E2EOptionalAgent', exact: true }).uncheck();+ await firstPicker.locator('[data-act="new"]').click();+ const promptInput = page.locator('.ui-dialog-overlay:visible .ui-dialog-input');+ await expect(promptInput).toBeVisible();+ await promptInput.fill('E2E Filed Project');+ await page.locator('.ui-dialog-overlay:visible [data-act="ok"]').click();++ const projects = page.locator('.project-row', {+ has: page.locator('.project-name', { hasText: 'E2E Filed Project' }),+ });+ await expect(projects).toHaveCount(1);+ await expect(page.locator(`#conversation-list .conv-item[data-cid="${cid}"]`)).toHaveCount(0);+ await expect.poll(async () => {+ const list = await orkas.invoke<{ conversations: Array<{ conversation_id: string; project_id?: string }> }>(+ 'conversations.list');+ return list.conversations.find((c) => c.conversation_id === cid)?.project_id || '';+ }, { timeout: 15_000 }).not.toBe('');++ const all = await orkas.invoke<{ projects: Array<{ project_id: string; name: string }> }>('projects.list');+ const projectId = all.projects.find((p) => p.name === 'E2E Filed Project')?.project_id;+ expect(projectId).toBeTruthy();+ await expect.poll(async () => {+ const bindings = await orkas.invoke<{ bindings: { agents: string[] } }>(+ 'projects.bindings.list', { projectId });+ return bindings.bindings.agents;+ }, { timeout: 15_000 }).toContain(agentId);++ const initialBindings = await orkas.invoke<{ bindings: { agents: string[] } }>('projects.bindings.list', { projectId });+ expect(initialBindings.bindings.agents).not.toContain(optionalId);++ // The history moved with it: reading the task through the normal path+ // still returns the message that was written before the move.+ const history = await orkas.invoke<{ history: Array<{ text?: string }> }>(+ 'conversations.history', { cid });+ expect(history.history.some((m) => String(m.text || '').includes('filed message body'))).toBe(true);++ // Add to project: the second loose task joins the same project, and the+ // menu no longer offers filing for a task that already has one.+ const secondRow = page.locator(`#conversation-list .conv-item[data-cid="${second.conversation.conversation_id}"]`);+ await secondRow.hover();+ await secondRow.locator('.conv-item-menu').click();+ await page.locator('#conversation-action-menu [data-action="to-project"]').click();+ const picker = page.locator('#conv-project-picker-overlay');+ await expect(picker).toBeVisible();+ // The primary action stays out of reach until a row is chosen, so a stray+ // click cannot move the task.+ const confirm = picker.locator('[data-act="ok"]');+ await expect(confirm).toBeDisabled();+ await picker.locator('.conv-project-pick-row', { hasText: 'E2E Filed Project' }).click();+ await expect(confirm).toBeEnabled();+ await expect(picker.getByRole('checkbox', { name: 'E2EFilingAgent', exact: true })).toBeChecked();+ await expect(picker.getByRole('checkbox', { name: 'E2EOptionalAgent', exact: true })).toBeChecked();+ // Capture the actual localized panel, then keep the selection while switching back.+ await page.evaluate(() => (window as any).setLang('zh'));+ await expect(picker.locator('legend')).toHaveText('同时添加任务中的 Agent');+ await picker.locator('[role="dialog"]').screenshot({ path: testInfo.outputPath('add-to-project-zh.png') });+ await page.evaluate(() => (window as any).setLang('en'));+ await picker.getByRole('checkbox', { name: 'E2EFilingAgent', exact: true }).uncheck();+ await confirm.click();+ await expect(secondRow).toHaveCount(0);+ await expect.poll(async () => (await orkas.invoke<{ bindings: { agents: string[] } }>(+ 'projects.bindings.list', { projectId })).bindings.agents.sort()).toEqual([agentId, optionalId].sort());++ const filedRow = page.locator(`.conv-item[data-cid="${cid}"]`).first();+ await filedRow.hover();+ await filedRow.locator('.conv-item-menu').click();+ await expect(page.locator('#conversation-action-menu [data-action="to-new-project"]')).toHaveCount(0);+ await expect(page.locator('#conversation-action-menu [data-action="to-project"]')).toHaveCount(0);+ });+ test('keeps a filed task and reports an agent disabled after the picker opened', async ({ orkas }) => {+ const { project } = await orkas.invoke<{ project: { project_id: string } }>('projects.create', { name: 'Partial filing' });+ const { agent } = await orkas.invoke<{ agent: { agent_id: string } }>('agents.create', {+ name: 'UnavailableAgent', description: 'Disabled after selection.', category: 'general',+ });+ const { conversation } = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', {+ title: 'Partial filing task',+ });+ // Conversation creation does not accept an agent. Seed the persisted roster+ // as in the filing happy path, then restart to discard any roster cache.+ const rosterDir = path.join(globalChatsDir(orkas.workspaceRoot), conversation.conversation_id);+ mkdirSync(rosterDir, { recursive: true });+ writeFileSync(path.join(rosterDir, 'members.json'), JSON.stringify({+ version: 1, actors: [{ kind: 'agent', id: agent.agent_id, name: 'UnavailableAgent' }],+ }));+ const page = await orkas.relaunch();+ const row = page.locator(`#conversation-list .conv-item[data-cid="${conversation.conversation_id}"]`);+ await row.hover();+ await row.locator('.conv-item-menu').click();+ await page.locator('#conversation-action-menu [data-action="to-project"]').click();+ const picker = page.locator('#conv-project-picker-overlay');+ await expect(picker.getByRole('checkbox', { name: 'UnavailableAgent' })).toBeChecked();+ await orkas.invoke('agents.setEnabled', { agent_id: agent.agent_id, enabled: false });+ await picker.locator('.conv-project-pick-row', { hasText: 'Partial filing' }).click();+ await picker.locator('[data-act="ok"]').click();+ await expect(page.locator('.ui-toast')).toContainText('1 agent(s) could not be added');+ const list = await orkas.invoke<{ conversations: Array<{ conversation_id: string; project_id?: string }> }>('conversations.list');+ expect(list.conversations.find((item) => item.conversation_id === conversation.conversation_id)?.project_id).toBe(project.project_id);+ const bindings = await orkas.invoke<{ bindings: { agents: string[] } }>('projects.bindings.list', { projectId: project.project_id });+ expect(bindings.bindings.agents).not.toContain(agent.agent_id);+ });+});diff --git a/test/e2e/todos_e2e_attachment_preview.spec.ts b/test/e2e/todos_e2e_attachment_preview.spec.tsnew file mode 100644index 00000000..7a8a7ff3--- /dev/null+++ b/test/e2e/todos_e2e_attachment_preview.spec.ts@@ -0,0 +1,53 @@+import { expect, test } from './fixtures/orkas';++++for (const scope of ['global', 'project'] as const) {+ test(`previews ${scope} todo attachments from the card and editor without editing or removing them`, async ({ orkas }, info) => {+ const page = orkas.page!;+ const project = scope === 'project' ? await orkas.invoke<any>('projects.create', { name: 'Preview project' }) : null;+ const projectId = project?.project.project_id || '';+ const created = await orkas.invoke<any>('projects.tasks.create', { projectId, content: 'Read the attached document' });+ const taskId = created.task.id;+ const upload = (name: string, text: string) => orkas.invoke('projects.tasks.attachments.upload', {+ projectId, taskId, name, dataBase64: Buffer.from(text).toString('base64'),+ });+ await upload('brief.txt', 'Original attachment body');+ if (projectId) {+ await page.evaluate(async (pid) => {+ await (window as any).setView('project', pid);+ }, projectId);+ await page.locator('[data-project-tab="todo"]').click();+ } else await page.locator('#todos-btn').click();+ const card = page.locator(`.project-todo-item[data-tid="${taskId}"]:visible`);+ const preview = await orkas.openPreview(() => card.locator('[data-action="todo-attachments"]').click());+ await expect(preview.locator('.chat-file-viewer-body')).toContainText('Original attachment body');+ await expect(preview.locator('[data-tve-action="edit"]')).toHaveCount(0);+ await expect(page.locator('#todo-editor-modal')).not.toHaveClass(/\bopen\b/);+ await preview.close();++ // Multiple files require a choice; selecting one previews its actual bytes.+ await upload('second.txt', 'Second attachment body');+ await page.evaluate(async (pid) => {+ if (pid) await (window as any)._loadProjectTodos(pid);+ else await (window as any)._refreshGlobalTodos('');+ }, projectId);+ await card.locator('[data-action="todo-attachments"]').click();+ const chosen = await orkas.openPreview(() => page.locator('.context-menu-item', { hasText: 'second.txt' }).click());+ await expect(chosen.locator('.chat-file-viewer-body')).toContainText('Second attachment body');+ await chosen.close();++ await card.locator('[data-action="todo-edit"]').click();+ const chip = page.locator('#project-todo-attachments .chat-attach-chip[data-name="brief.txt"]');+ const editorPreview = await orkas.openPreview(() => scope === 'project' ? chip.press('Enter') : chip.click());+ await expect(editorPreview.locator('.chat-file-viewer-body')).toContainText('Original attachment body');+ await editorPreview.close();+ await expect(page.locator('#project-todo-input')).toHaveValue('Read the attached document');+ await page.screenshot({ path: info.outputPath('todo-attachment-editor.png') });+ await chip.locator('.chat-attach-remove').click();+ await expect(chip).toHaveCount(0);+ await page.locator('#project-todo-cancel').click();+ const saved = await orkas.invoke<any>('projects.tasks.list', { projectId });+ expect(saved.tasks.find((task: any) => task.id === taskId).attachments).toEqual(['brief.txt', 'second.txt']);+ });+}diff --git a/test/e2e/todos_e2e_board.spec.ts b/test/e2e/todos_e2e_board.spec.tsindex 56ee6b30..2eda3602 100644--- a/test/e2e/todos_e2e_board.spec.ts+++ b/test/e2e/todos_e2e_board.spec.ts@@ -1,7 +1,9 @@import { expect, test } from './fixtures/orkas';// The assignment journey exercises both account-scoped agents and execution.-test('manages the same backlog from global and project boards with independent disclosures', async ({ connectorOrkas: orkas }, testInfo) => {+++test('manages the same backlog from global and project boards without a duplicate project disclosure', async ({ orkas }, testInfo) => {const page = orkas.page!;await page.evaluate(() => (window as any).setLang('zh'));const alpha = await orkas.invoke<{ project: { project_id: string } }>('projects.create', { name: '桌面应用' });@@ -37,20 +39,25 @@ test('manages the same backlog from global and project boards with independent dawait expect(page.locator('#todos-project-filter')).toHaveCount(0);await expect(page.locator('#todos-add-btn')).toHaveText('+创建');await expect(page.locator('#todos-add-btn')).not.toHaveClass(/btn-primary/);- await expect(content.locator('.todo-project-group')).toHaveCount(2);+ // Every scope with tasks gets a switcher chip; only the picked one paints a board.+ await expect(content.locator('.todo-scope-chip')).toHaveCount(2);+ await expect(content.locator('.todo-scope-chip[aria-pressed="true"]')).toHaveCount(1);await expect(content.getByText('空项目', { exact: true })).toHaveCount(0);await expect(content.getByText('查看项目', { exact: true })).toHaveCount(0);- await expect(content.locator('.todo-project-head .todo-collapse')).toHaveCount(2);- await expect(content.locator('.todo-project-head .todo-project-add')).toHaveCount(2);- await expect(content.locator('.todo-project-head .todo-scope-driver-toggle')).toHaveCount(2);+ await content.locator(`.todo-scope-chip[data-pid="${a}"]`).click();+ await expect(content.locator('.todo-project-group')).toHaveCount(1);+ await expect(content.locator('.todo-project-group')).toHaveAttribute('data-pid', a);+ await expect(content.locator('.todo-project-head')).toHaveCount(0);+ await expect(content.locator('.todo-scope-actions .todo-project-add')).toHaveCount(1);+ await expect(content.locator('.todo-scope-actions .todo-scope-driver-toggle')).toHaveCount(1);await expect(content.locator('.todo-column-head .project-todo-menu')).toHaveCount(0);- await expect(content.locator('.project-todo-item [data-action="todo-menu"]')).toHaveCount(7);+ await expect(content.locator('.project-todo-item [data-action="todo-menu"]')).toHaveCount(4);+ await expect(content.getByText('整理首页文案', { exact: true })).toHaveCount(0);await expect(page.locator('#todos-btn')).toHaveText('待办');await expect(page.locator('[data-project-tab="todo"]')).toHaveText('待办 0');const alphaGroup = content.locator(`.todo-project-group[data-pid="${a}"]`);await expect(alphaGroup.locator('.todo-column-head .todo-collapse')).toHaveText(['待处理1', '处理中1', '待确认1', '已完成1']);- await expect(alphaGroup.locator('.todo-project-head .auto-group-icon svg')).toHaveCount(1);- await expect(alphaGroup.locator('.todo-project-head .todo-disclosure-chevron')).toHaveCount(0);+ await expect(alphaGroup.locator('.todo-board')).toBeVisible();await expect(alphaGroup.locator('.todo-column-head .todo-disclosure-chevron')).toHaveCount(4);for (const status of ['todo', 'progress', 'review']) {await expect(alphaGroup.locator(`.todo-column.is-${status} .todo-collapse`)).toHaveAttribute('aria-expanded', 'true');@@ -61,11 +68,10 @@ test('manages the same backlog from global and project boards with independent dawait doneToggle.focus();await page.keyboard.press('Space');await expect(alphaGroup.getByText('确认视觉规范', { exact: true })).toBeVisible();- const projectToggle = alphaGroup.locator('.todo-project-head .todo-collapse');- await projectToggle.click();- await expect(alphaGroup.locator('.todo-board')).toBeHidden();+ await content.locator(`.todo-scope-chip[data-pid="${b}"]`).click();await expect(content.getByText('整理首页文案', { exact: true })).toBeVisible();- await projectToggle.click();+ await content.locator(`.todo-scope-chip[data-pid="${a}"]`).click();+ await expect(alphaGroup.locator('.todo-board')).toBeVisible();await expect(doneToggle).toHaveAttribute('aria-expanded', 'true');// One project-level + replaces the four status-level buttons and creates in@@ -181,24 +187,18 @@ test('manages the same backlog from global and project boards with independent dattachments: ['global-notes.txt'],});expect(globalTask.detail).toBeUndefined();- await expect(content.locator('.todo-project-group')).toHaveCount(3);+ await expect(content.locator('.todo-scope-chip')).toHaveCount(3);+ await content.locator('.todo-scope-chip[data-pid=""]').click();+ await expect(content.locator('.todo-project-group')).toHaveCount(1);const globalGroup = content.locator('.todo-project-group[data-pid=""]');await expect(globalGroup).toContainText('全局跟进发票');await expect(globalGroup.locator('.todo-scope-driver-toggle')).toBeVisible();await expect(globalGroup.locator('.todo-column.is-progress .todo-column-empty')).toHaveCSS('text-align', 'center');- const globalToggle = globalGroup.locator('.todo-project-head .todo-collapse');- const globalFolder = globalToggle.locator('.auto-group-folder-icon');- await expect(globalFolder).toHaveCount(1);- await expect(globalFolder).toHaveClass(/\bis-folder-open\b/);- await globalToggle.click();- await expect(globalToggle).toHaveAttribute('aria-expanded', 'false');- await expect(globalGroup.locator('.todo-board')).toBeHidden();- await expect(globalFolder).toHaveClass(/\bis-folder(?:\s|$)/);+ await expect(globalGroup.locator('.todo-board')).toBeVisible();+ await content.locator(`.todo-scope-chip[data-pid="${a}"]`).click();await expect(alphaGroup.locator('.todo-board')).toBeVisible();- await globalToggle.click();- await expect(globalToggle).toHaveAttribute('aria-expanded', 'true');+ await content.locator('.todo-scope-chip[data-pid=""]').click();await expect(globalGroup.locator('.todo-board')).toBeVisible();- await expect(globalFolder).toHaveClass(/\bis-folder-open\b/);// The same editor can still opt into a project explicitly.await page.locator('#todos-add-btn').click();@@ -318,6 +318,13 @@ test('manages the same backlog from global and project boards with independent dawait expect(page.locator('#project-driver-toggle')).toBeVisible();await expect(page.locator('#project-driver-toggle')).toHaveAttribute('aria-pressed', 'true');const projectList = page.locator('#project-todo-list');+ const projectBoard = projectList.locator(':scope > .todo-board');+ const [listBox, boardBox] = await Promise.all([projectList.boundingBox(), projectBoard.boundingBox()]);+ expect(listBox).not.toBeNull();+ expect(boardBox).not.toBeNull();+ expect(boardBox!.x).toBeGreaterThanOrEqual(listBox!.x - 1);+ expect(boardBox!.x + boardBox!.width).toBeLessThanOrEqual(listBox!.x + listBox!.width + 1);+ expect(await projectBoard.evaluate((board) => getComputedStyle(board).gridTemplateColumns.split(' ').length)).toBe(4);const projectCard = projectList.locator(`.project-todo-item[data-tid="${created.id}"]`);await expect(projectList.locator('.todo-column.is-progress').getByText('完善价格页', { exact: true })).toBeVisible();await expect(projectList.getByText('设计项目看板', { exact: true })).toHaveCount(0);@@ -331,6 +338,24 @@ test('manages the same backlog from global and project boards with independent d};});expect(projectCardStyle).toEqual(globalCardStyle);+ await page.setViewportSize({ width: 1024, height: 768 });+ const narrowGeometry = await projectBoard.evaluate((board) => {+ const list = board.parentElement!;+ const last = board.lastElementChild!;+ board.scrollLeft = board.scrollWidth;+ return {+ listRight: list.getBoundingClientRect().right,+ boardRight: board.getBoundingClientRect().right,+ lastRight: last.getBoundingClientRect().right,+ columnCount: getComputedStyle(board).gridTemplateColumns.split(' ').length,+ boardOverflow: board.scrollWidth - board.clientWidth,+ };+ });+ expect(narrowGeometry.boardRight).toBeLessThanOrEqual(narrowGeometry.listRight + 1);+ expect(narrowGeometry.lastRight).toBeLessThanOrEqual(narrowGeometry.boardRight + 1);+ expect(narrowGeometry.columnCount).toBe(4);+ expect(narrowGeometry.boardOverflow).toBeGreaterThan(1);+ await page.setViewportSize({ width: 1440, height: 900 });// Counts include completed/legacy tasks and reconcile external writes even// while the user is on a different project tab.await page.locator('[data-project-tab="tasks"]').click();@@ -353,8 +378,10 @@ test('manages the same backlog from global and project boards with independent d// Reopening the app reads persisted tasks and restores default disclosure states.const reloaded = await orkas.relaunch();await reloaded.locator('#todos-btn').click();- await expect(reloaded.locator('#todos-content').getByText('完善价格页与导航', { exact: true })).toBeVisible();+ // A fresh launch focuses the first scope; the rest stay one chip away.await expect(reloaded.locator('#todos-content').getByText('全局跟进发票', { exact: true })).toBeVisible();+ await reloaded.locator(`#todos-content .todo-scope-chip[data-pid="${b}"]`).click();+ await expect(reloaded.locator('#todos-content').getByText('完善价格页与导航', { exact: true })).toBeVisible();await expect(reloaded.locator('#todos-content .todo-column.is-done .todo-collapse').first()).toHaveAttribute('aria-expanded', 'false');await expect(reloaded.locator('#todos-project-filter')).toHaveCount(0);await expect(reloaded.locator('#todos-content').getByText('空项目', { exact: true })).toHaveCount(0);@@ -447,6 +474,8 @@ test('assigns global and project todos in the editor and keeps cards and saved oif (!scope) await page.screenshot({ path: testInfo.outputPath('todo-agent-editor.png') });await page.locator('#project-todo-save').click();await expect(page.locator('#todo-editor-modal')).not.toHaveClass(/open/);+ // The by-project view paints one scope at a time; focus the one just written to.+ await page.locator(`#todos-content .todo-scope-chip[data-pid="${scope}"]`).click();const card = page.locator('#todos-content .project-todo-item', { hasText: title });await expect(card.locator('.project-todo-assign')).toContainText(agent.name);let tasks = await orkas.invoke<{ tasks: any[] }>('projects.tasks.list', { projectId: scope });diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.tsindex 5072df9e..943fb339 100644--- a/test/main/features/agents.test.ts+++ b/test/main/features/agents.test.ts@@ -1300,10 +1300,39 @@ describe('agents › createCustomAgent', () => {expect(raw).not.toHaveProperty('description');});- it('defaults empty name to the localized no-space fallback', async () => {+ it.each([+ ['en', 'CodeReviewAssistant'],+ ['ar', 'CodeReviewAssistant'],+ ['hi', 'CodeReviewAssistant'],+ ['th', 'CodeReviewAssistant'],+ ['tr', 'KodIncelemeAsistani'],+ ['vi', 'TroLyDanhGiaMa'],+ ['zh-tw', '程式碼審查助手'],+ ['pt-pt', 'AssistenteRevisaoCodigo'],+ ['es-419', 'AsistenteRevisionCodigo'],+ ] as const)('keeps default and suggested Agent names editable in %s', async (lang, suggestedName) => {+ const { setLanguage } = await import('../../../src/main/features/config');+ setLanguage(lang);+ const mainTable = JSON.parse(fs.readFileSync(+ path.resolve(__dirname, '../../../src/main/locales', `${lang}.json`), 'utf8',+ ));+ const rendererTable = JSON.parse(fs.readFileSync(+ path.resolve(__dirname, '../../../src/renderer/locales', `${lang}.json`), 'utf8',+ ));const a = await loadAgents();const agent = await a.createCustomAgent({ description: 'desc', category: 'general' });- expect(agent?.name).toBe('UntitledAgent');+ expect(agent?.name).toBe(mainTable['agent.default_name']);+ if (lang === 'en') expect(agent?.name).toBe('UntitledAgent');+ // Creation applies the locale fallback after the initial name check. Saving+ // that generated name exercises the real validator and @-mention contract.+ const saved = await a.updateCustomAgent(agent!.agent_id, { name: agent!.name });+ expect(saved?.name).toBe(agent!.name);+ expect(rendererTable['agent_modal.name_placeholder'].endsWith(suggestedName)).toBe(true);+ const renamed = await a.updateCustomAgent(agent!.agent_id, { name: suggestedName });+ expect(renamed?.name).toBe(suggestedName);+ expect(JSON.parse(fs.readFileSync(+ path.join(customAgentsDir(), agent!.agent_id, 'agent.json'), 'utf8',+ )).name).toBe(suggestedName);});it('stores workflow skill references by display name', async () => {@@ -1732,6 +1761,7 @@ describe('agents › listAgents', () => {expect(searchListing).toMatchObject({agent_id: 'brief',name: 'Brief Agent',+ runtime: { kind: 'cli', cli: 'codex' },description_zh: '',description_en: 'Test agent',enabled: false,diff --git a/test/main/features/chats-move-to-project.test.ts b/test/main/features/chats-move-to-project.test.tsnew file mode 100644index 00000000..a1e2764a--- /dev/null+++ b/test/main/features/chats-move-to-project.test.ts@@ -0,0 +1,439 @@+/**+ * Moving an existing conversation into a project.+ *+ * `project_id` used to be frozen at create time, and it is not just a field:+ * it decides where the messages, group companion dir, commander and per-agent+ * sessions, attachments and artifacts live. A move that flips the row without+ * carrying the bytes leaves the user with a conversation that opens empty, so+ * these cases check the filesystem on both sides rather than the returned+ * record.+ */++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { spawnSync } from 'node:child_process';++vi.mock('../../../src/main/logger', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));++let tmpDir: string;+let prevWs: string | undefined;+const UID = 'u1';+const PID = 'p_move_target';++beforeEach(async () => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-conv-move-'));+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;+ vi.resetModules();+ const users = await import('../../../src/main/features/users');+ users.activateUser(UID);+});++afterEach(async () => {+ await (await import('../../../src/main/features/search/indexer')).flushAll();+ vi.restoreAllMocks();+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;+ fs.rmSync(tmpDir, { recursive: true, force: true });+});++const cloud = (...parts: string[]) => path.join(tmpDir, UID, 'cloud', ...parts);++function write(file: string, body: string): void {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, body);+}++/** Give a conversation one file of every kind a move has to carry. */+function seedConversationBytes(cid: string): void {+ write(cloud('chats', `${cid}.jsonl`), '{"from":"user","text":"hello"}\n');+ write(cloud('chats', cid, 'members.json'), '{"version":1,"actors":[]}');+ write(cloud('chats', cid, 'state.json'), '{"status":"idle"}');+ write(cloud('sessions', `gconv-${cid}.jsonl`), 'commander\n');+ write(cloud('sessions', `gconv-${cid}.jsonl.context.json`), '{}');+ write(cloud('sessions', `gconv-${cid}.tool-results`, 'r1.json'), '{}');+ write(cloud('sessions', `gmember-${cid}-agent1.jsonl`), 'member\n');+ write(cloud('sessions', `gmember-${cid}-agent1.tool-results`, 'r2.json'), '{}');+ write(cloud('chat_attachments', cid, 'note.txt'), 'attached');+ write(cloud('chat_artifacts', cid, 'art1', 'index.html'), '<p>art</p>');+ // Another conversation's bytes sit in the same flat directories and must be+ // left alone; the session sweep matches by prefix.+ write(cloud('sessions', 'gconv-other.jsonl'), 'other\n');+ write(cloud('sessions', `gmember-other-${cid}.jsonl`), 'not mine\n');+}++function projectPaths(cid: string): string[] {+ return [+ cloud('projects', PID, 'chats', `${cid}.jsonl`),+ cloud('projects', PID, 'chats', cid, 'members.json'),+ cloud('projects', PID, 'chats', cid, 'state.json'),+ cloud('projects', PID, 'sessions', `gconv-${cid}.jsonl`),+ cloud('projects', PID, 'sessions', `gconv-${cid}.jsonl.context.json`),+ cloud('projects', PID, 'sessions', `gconv-${cid}.tool-results`, 'r1.json'),+ cloud('projects', PID, 'sessions', `gmember-${cid}-agent1.jsonl`),+ cloud('projects', PID, 'sessions', `gmember-${cid}-agent1.tool-results`, 'r2.json'),+ cloud('projects', PID, 'chat_attachments', cid, 'note.txt'),+ cloud('projects', PID, 'chat_artifacts', cid, 'art1', 'index.html'),+ ];+}++function globalPaths(cid: string): string[] {+ return [+ cloud('chats', `${cid}.jsonl`),+ cloud('chats', cid),+ cloud('sessions', `gconv-${cid}.jsonl`),+ cloud('sessions', `gconv-${cid}.jsonl.context.json`),+ cloud('sessions', `gconv-${cid}.tool-results`),+ cloud('sessions', `gmember-${cid}-agent1.jsonl`),+ cloud('sessions', `gmember-${cid}-agent1.tool-results`),+ cloud('chat_attachments', cid),+ cloud('chat_artifacts', cid),+ ];+}++function readIndex(file: string): any[] {+ try { return JSON.parse(fs.readFileSync(file, 'utf-8')); } catch { return []; }+}++async function seedProject(): Promise<void> {+ write(cloud('projects', PID, 'project.json'),+ JSON.stringify({ project_id: PID, name: 'Target', created_at: new Date().toISOString() }));+}++describe('chats › moveConversationToProject', () => {+ it('carries every location into the project and leaves nothing behind', async () => {+ const chats = await import('../../../src/main/features/chats');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'loose task' });+ const cid = conv.conversation_id;+ seedConversationBytes(cid);++ const result = await chats.moveConversationToProject(UID, cid, PID);+ expect(result.ok).toBe(true);++ for (const file of projectPaths(cid)) expect({ file, exists: fs.existsSync(file) }).toEqual({ file, exists: true });+ for (const file of globalPaths(cid)) expect({ file, exists: fs.existsSync(file) }).toEqual({ file, exists: false });+ // Content, not just presence: a move that truncated a file would pass an+ // existence check.+ expect(fs.readFileSync(cloud('projects', PID, 'chats', `${cid}.jsonl`), 'utf-8'))+ .toBe('{"from":"user","text":"hello"}\n');+ expect(fs.readFileSync(cloud('projects', PID, 'chat_attachments', cid, 'note.txt'), 'utf-8'))+ .toBe('attached');++ // Someone else's sessions stayed put.+ expect(fs.existsSync(cloud('sessions', 'gconv-other.jsonl'))).toBe(true);+ expect(fs.existsSync(cloud('sessions', `gmember-other-${cid}.jsonl`))).toBe(true);++ // The row lives in exactly one index.+ expect(readIndex(cloud('chats', '_index.json')).some((r) => r.conversation_id === cid)).toBe(false);+ const projectRow = readIndex(cloud('projects', PID, 'chats', '_index.json'))+ .find((r) => r.conversation_id === cid);+ expect(projectRow?.project_id).toBe(PID);+ expect(projectRow?.title).toBe('loose task');+ });++ it.each([false, true])('rejects admission during a move and resumes after commit or rollback (rollback: %s)', async (rollback) => {+ const chats = await import('../../../src/main/features/chats');+ const storage = await import('../../../src/main/storage');+ const bus = await import('../../../src/main/features/group_chat/bus');+ const layout = await import('../../../src/main/util/project-layout');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'Move admission' });+ const cid = conv.conversation_id;+ seedConversationBytes(cid);+ expect(layout.findProjectIdForConversation(UID, cid)).toBeNull();+ let entered!: () => void;+ let release!: () => void;+ const atCommit = new Promise<void>(resolve => { entered = resolve; });+ const resume = new Promise<void>(resolve => { release = resolve; });+ const original = storage.writeJson;+ let sideEffect!: () => void;+ const oldRootWrite = new Promise<'old-root-write'>(resolve => { sideEffect = () => resolve('old-root-write'); });+ let paused = false;+ vi.spyOn(storage, 'writeJson').mockImplementation(async (file, data) => {+ if (!paused && file === cloud('chats', '_index.json')) {+ paused = true;+ entered();+ await resume;+ if (rollback) throw new Error('injected move commit failure');+ }+ if (file.startsWith(cloud('chats', cid) + path.sep)) sideEffect();+ return original(file, data);+ });+ const moving = chats.moveConversationToProject(UID, cid, PID);+ let admission: Promise<unknown> | undefined;+ try {+ await atCommit;+ // This enqueue has no model recipient; admission itself must be rejected+ // before roster/state/message writers can recreate the old source tree.+ admission = bus.enqueue({ uid: UID, cid, fromActorId: 'commander',+ forceTo: ['user'], text: 'must not land during relocation' })+ .then(() => 'accepted', () => 'rejected');+ expect(await Promise.race([admission, oldRootWrite])).toBe('rejected');+ expect(fs.existsSync(cloud('chats', cid))).toBe(false);+ expect(fs.existsSync(cloud('chats', `${cid}.jsonl`))).toBe(false);+ } finally { release(); await moving; await admission; }+ expect(await moving).toMatchObject({ ok: !rollback });+ const delivered = await bus.enqueue({ uid: UID, cid, fromActorId: 'commander',+ forceTo: ['user'], text: 'sent after settled move' });+ expect(delivered.text).toBe('sent after settled move');+ const file = layout.conversationMessageReadFile(UID, cid);+ expect(file).toBe(rollback ? cloud('chats', `${cid}.jsonl`)+ : cloud('projects', PID, 'chats', `${cid}.jsonl`));+ expect(fs.readFileSync(file, 'utf8')).toContain('sent after settled move');+ expect(fs.readFileSync(file, 'utf8')).not.toContain('must not land');+ await bus.dropConv(UID, cid);+ });++ it('resolves later reads against the new root', async () => {+ // Ownership is cached per process and a positive answer never expires, so+ // a lookup taken before the move would otherwise pin the old root for the+ // rest of the session and every path derived from it would be wrong.+ const chats = await import('../../../src/main/features/chats');+ const layout = await import('../../../src/main/util/project-layout');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'loose task' });+ const cid = conv.conversation_id;+ seedConversationBytes(cid);++ expect(layout.findProjectIdForConversation(UID, cid)).toBe(null);+ await chats.moveConversationToProject(UID, cid, PID);++ expect(layout.findProjectIdForConversation(UID, cid)).toBe(PID);+ expect(layout.conversationMessageReadFile(UID, cid))+ .toBe(cloud('projects', PID, 'chats', `${cid}.jsonl`));+ });++ it.each([{ status: 'running' }, { status: 'aborted', in_flight: ['agent1'] }])('refuses while a turn is active or draining (%j) and moves nothing', async (state) => {+ const chats = await import('../../../src/main/features/chats');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'busy task' });+ const cid = conv.conversation_id;+ seedConversationBytes(cid);+ write(cloud('chats', cid, 'state.json'), JSON.stringify(state));++ const result = await chats.moveConversationToProject(UID, cid, PID);+ expect(result).toEqual({ ok: false, error: 'has_running_conv' });+ expect(fs.existsSync(cloud('chats', `${cid}.jsonl`))).toBe(true);+ expect(fs.existsSync(cloud('projects', PID, 'chats', `${cid}.jsonl`))).toBe(false);+ expect(readIndex(cloud('chats', '_index.json')).some((r) => r.conversation_id === cid)).toBe(true);+ });++ it('tells the search index its source layout changed', async () => {+ // The move must revoke search trust and schedule repair before returning.+ // The worker persists the invalidation asynchronously, so a synchronous+ // database assertion would mistake a queued write for a missing repair.+ const chats = await import('../../../src/main/features/chats');+ const search = await import('../../../src/main/features/search');+ const indexer = await import('../../../src/main/features/search/indexer');+ const chatStore = await import('../../../src/main/features/search/chat_store');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'loose task' });+ const cid = conv.conversation_id;+ seedConversationBytes(cid);+ expect((await indexer.reconcileChatsIndex(UID)).complete).toBe(true);+ expect((await search.searchIndexStatus(UID)).chat_index_complete).toBe(true);++ expect((await chats.moveConversationToProject(UID, cid, PID)).ok).toBe(true);+ expect((await search.searchIndexStatus(UID)).chat_index_complete).toBe(false);+ expect(search.__searchTestHooks.hasPendingChatRepair(UID)).toBe(true);+ await indexer.drainDeferredChatWrites(UID);+ expect(chatStore.readSourceStamp(UID)).toBeUndefined();+ });++ it('refuses a conversation that already belongs to a project', async () => {+ const chats = await import('../../../src/main/features/chats');+ await seedProject();+ write(cloud('projects', 'p_origin', 'project.json'),+ JSON.stringify({ project_id: 'p_origin', name: 'Origin' }));+ const conv = await chats.createConversation(UID, { title: 'owned', projectId: 'p_origin' });++ const result = await chats.moveConversationToProject(UID, conv.conversation_id, PID);+ expect(result).toEqual({ ok: false, error: 'already_in_project' });+ });++ it('restores every location when one of them cannot move', async () => {+ // A destination collision must leave every source untouched and preserve+ // the existing destination rather than merging unrelated bytes.+ const chats = await import('../../../src/main/features/chats');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'loose task' });+ const cid = conv.conversation_id;+ seedConversationBytes(cid);+ write(cloud('projects', PID, 'chat_attachments', cid, 'squatter.txt'), 'in the way');++ const result = await chats.moveConversationToProject(UID, cid, PID);+ expect(result).toEqual({ ok: false, error: 'move_failed' });++ for (const file of globalPaths(cid)) expect({ file, exists: fs.existsSync(file) }).toEqual({ file, exists: true });+ expect(fs.readFileSync(cloud('chats', `${cid}.jsonl`), 'utf-8'))+ .toBe('{"from":"user","text":"hello"}\n');+ expect(fs.existsSync(cloud('projects', PID, 'chats', `${cid}.jsonl`))).toBe(false);+ expect(fs.existsSync(cloud('projects', PID, 'sessions', `gconv-${cid}.jsonl`))).toBe(false);+ expect(readIndex(cloud('chats', '_index.json')).some((r) => r.conversation_id === cid)).toBe(true);+ expect(readIndex(cloud('projects', PID, 'chats', '_index.json')).some((r) => r.conversation_id === cid))+ .toBe(false);+ });+ it.each(['source-index', 'target-index', 'meta'])('restores indexes and bytes after a failed %s commit', async (stage) => {+ const chats = await import('../../../src/main/features/chats');+ const storage = await import('../../../src/main/storage');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'retained history' });+ const unrelated = await chats.createConversation(UID, { title: 'other task', projectId: PID });+ const cid = conv.conversation_id;+ seedConversationBytes(cid);+ const failedPath = stage === 'source-index' ? cloud('chats', '_index.json')+ : stage === 'target-index' ? cloud('projects', PID, 'chats', '_index.json')+ : cloud('projects', PID, 'chats', cid, 'meta.json');+ const original = storage.writeJson;+ let failed = false;+ vi.spyOn(storage, 'writeJson').mockImplementation(async (file, data) => {+ if (file === failedPath && !failed) { failed = true; throw new Error('injected write failure'); }+ // A sibling index may still be in flight after Promise.all rejects.+ if (!failed && file === cloud('chats', '_index.json')) await new Promise(resolve => setTimeout(resolve, 20));+ return original(file, data);+ });+ expect(await chats.moveConversationToProject(UID, cid, PID)).toEqual({ ok: false, error: 'move_failed' });+ expect(failed).toBe(true);+ await new Promise(resolve => setTimeout(resolve, 60));+ expect(readIndex(cloud('chats', '_index.json')).find(r => r.conversation_id === cid)?.title).toBe('retained history');+ const targetRows = readIndex(cloud('projects', PID, 'chats', '_index.json'));+ expect(targetRows.some(r => r.conversation_id === cid)).toBe(false);+ expect(targetRows.some(r => r.conversation_id === unrelated.conversation_id)).toBe(true);+ for (const file of globalPaths(cid)) expect(fs.existsSync(file)).toBe(true);+ expect((await chats.listConversations(UID)).find(r => r.conversation_id === cid)?.project_id).toBeFalsy();+ expect((await chats.moveConversationToProject(UID, cid, PID)).ok).toBe(true);+ });++ // Kill the actual writer process, so catch/finally and in-memory rollback+ // cannot conceal a missing durable recovery step.+ it.each(['rename', 'source-index', 'target-index', 'meta', 'committed'])(+ 'recovers history and ownership after process exit at %s', async (stage) => {+ const chats = await import('../../../src/main/features/chats');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'survives restart' });+ const other = await chats.createConversation(UID, { title: 'unrelated', projectId: PID });+ const cid = conv.conversation_id;+ seedConversationBytes(cid);+ const result = spawnSync(process.execPath, ['-r', 'tsx/cjs', '-e', `+ const fs = require('node:fs');+ const slash = file => file.split(require('node:path').sep).join('/');+ const uid = ${JSON.stringify(UID)}, cid = ${JSON.stringify(cid)}, pid = ${JSON.stringify(PID)};+ const stage = ${JSON.stringify(stage)};+ require('./src/main/features/users.ts').activateUser(uid);+ const chats = require('./src/main/features/chats.ts');+ const rename = fs.renameSync;+ fs.renameSync = function(from, to) {+ const out = rename(from, to);+ if (stage === 'rename' && slash(from).endsWith('/chats/' + cid + '.jsonl')) process.exit(73);+ if (stage === 'committed' && slash(to).endsWith('/conversation-moves/' + cid + '.json')+ && JSON.parse(fs.readFileSync(to, 'utf8')).phase === 'committed') process.exit(73);+ return out;+ };+ const fsp = require('node:fs/promises');+ const renameAsync = fsp.rename;+ fsp.rename = async function(from, to) {+ const out = await renameAsync(from, to);+ const suffix = stage === 'source-index' ? '/cloud/chats/_index.json'+ : stage === 'target-index' ? '/projects/' + pid + '/chats/_index.json'+ : stage === 'meta' ? '/projects/' + pid + '/chats/' + cid + '/meta.json' : '';+ if (suffix && slash(to).endsWith(suffix)) process.exit(73);+ return out;+ };+ chats.moveConversationToProject(uid, cid, pid).then(() => process.exit(74));+ `], {+ cwd: path.resolve(__dirname, '../../..'),+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', ORKAS_WORKSPACE_ROOT: tmpDir },+ encoding: 'utf8', timeout: 30_000,+ });+ expect({ status: result.status, stdout: result.stdout, stderr: result.stderr, error: result.error?.message })+ .toEqual({ status: 73, stdout: '', stderr: '', error: undefined });+ // Persisted bytes moved before interruption, with a real recovery record.+ expect(fs.existsSync(cloud('projects', PID, 'chats', `${cid}.jsonl`))).toBe(true);+ expect(fs.existsSync(path.join(tmpDir, UID, 'local', 'conversation-moves', `${cid}.json`))).toBe(true);+ vi.resetModules();+ const users = await import('../../../src/main/features/users');+ users.activateUser(UID);+ users.activateUser(UID); // A second activation cannot undo committed work.+ const restarted = await import('../../../src/main/features/chats');+ const layout = await import('../../../src/main/util/project-layout');+ const owner = stage === 'committed' ? PID : null;+ expect(layout.findProjectIdForConversation(UID, cid)).toBe(owner);+ expect(fs.readFileSync(layout.conversationMessageReadFile(UID, cid), 'utf8'))+ .toBe('{"from":"user","text":"hello"}\n');+ const attachments = layout.chatAttachmentDirForConversation(UID, cid);+ expect(fs.readFileSync(path.join(attachments, 'note.txt'), 'utf8')).toBe('attached');+ const rows = await restarted.listConversations(UID);+ expect(rows.filter(row => row.conversation_id === cid)).toHaveLength(1);+ expect(rows.find(row => row.conversation_id === cid)?.project_id || null).toBe(owner);+ expect(rows.find(row => row.conversation_id === other.conversation_id)?.project_id).toBe(PID);+ for (const file of stage === 'committed' ? projectPaths(cid) : globalPaths(cid)) expect(fs.existsSync(file)).toBe(true);+ if (stage !== 'committed') expect((await restarted.moveConversationToProject(UID, cid, PID)).ok).toBe(true);+ }, 40_000,+ );++ it('preserves conflicting copies and retains recovery evidence until the conflict is resolved', async () => {+ const chats = await import('../../../src/main/features/chats');+ const relocation = await import('../../../src/main/util/conversation-relocate');+ await seedProject();+ const conv = await chats.createConversation(UID, { title: 'conflict' });+ const cid = conv.conversation_id;+ const other = await chats.createConversation(UID, { title: 'unrelated task' });+ seedConversationBytes(cid);+ relocation.relocateConversationIntoProject(UID, cid, PID, { ...conv });+ write(cloud('chats', `${cid}.jsonl`), 'new source bytes');+ expect(relocation.recoverConversationRelocations(UID)).toBe(1);+ const layout = await import('../../../src/main/util/project-layout');+ expect(() => layout.conversationMessageFile(UID, cid, null)).toThrow();+ expect(() => layout.conversationMessageFile(UID, 'unrelated', null)).not.toThrow();+ const users = await import('../../../src/main/features/users');+ expect(() => users.activateUser(UID)).not.toThrow();+ // One blocked conversation in the running journal must not abort the+ // stale-state sweep for the rest of the account: the unrelated+ // interrupted run still gets settled.+ const paths = await import('../../../src/main/paths');+ write(paths.userRunningConversationsFile(UID), JSON.stringify({+ version: 1, items: [{ conversation_id: cid }, { conversation_id: other.conversation_id }],+ }));+ const otherState = cloud('chats', other.conversation_id, 'state.json');+ write(otherState, JSON.stringify({+ version: 1, status: 'running', in_flight: ['commander'],+ last_active_at: new Date(Date.now() - 60_000).toISOString(),+ }));+ const indexer = await import('../../../src/main/features/search/indexer');+ try {+ expect((await chats.sweepStaleProcessing(UID)).swept).toBe(1);+ expect(JSON.parse(fs.readFileSync(otherState, 'utf8')).status).toBe('idle');+ } finally { await indexer.flushAll(); }+ expect((await chats.listConversations(UID)).some(row => row.conversation_id === other.conversation_id)).toBe(true);+ expect(await chats.renameConversation(UID, other.conversation_id, 'still usable')).toMatchObject({ title: 'still usable' });++ expect(fs.readFileSync(cloud('chats', `${cid}.jsonl`), 'utf8')).toBe('new source bytes');+ expect(fs.readFileSync(cloud('projects', PID, 'chats', `${cid}.jsonl`), 'utf8')).toContain('hello');+ expect(fs.existsSync(path.join(tmpDir, UID, 'local', 'conversation-moves', `${cid}.json`))).toBe(true);++ // Journal inspection stays available: the conflicted conversation is+ // reported with both of its trees, a record this version cannot read is+ // reported by its file name, and neither counts as a committed intent.+ const broken = await chats.createConversation(UID, { title: 'broken record' });+ write(path.join(tmpDir, UID, 'local', 'conversation-moves', `${broken.conversation_id}.json`), '{"version":99,"pid":"p_x"}');+ const journals = relocation.readConversationRelocationJournals(UID);+ expect(journals.committed).toEqual([]);+ expect(journals.unresolved.map((item) => item.cid).sort()).toEqual([cid, broken.conversation_id].sort());+ for (const rel of [+ `cloud/chats/${cid}.jsonl`, `cloud/chats/${cid}/state.json`, `cloud/sessions/gconv-${cid}.jsonl`,+ `cloud/chat_attachments/${cid}/note.txt`, `cloud/projects/${PID}/chats/${cid}.jsonl`,+ `cloud/projects/${PID}/chat_artifacts/${cid}/art1/index.html`,+ `cloud/chats/${broken.conversation_id}.jsonl`, `cloud/projects/p_x/sessions/gmember-${broken.conversation_id}-agent1.jsonl`,+ ]) expect(relocation.matchesUnresolvedRelocation(journals.unresolved, rel), rel).toBe(true);+ for (const rel of [+ `cloud/chats/${other.conversation_id}.jsonl`, 'cloud/sessions/gconv-other.jsonl',+ `cloud/sessions/gmember-other-${cid}.jsonl`, 'cloud/contexts/notes.md',+ ]) expect(relocation.matchesUnresolvedRelocation(journals.unresolved, rel), rel).toBe(false);+ expect(relocation.committedConversationRelocations(UID)).toEqual([]);+ });++});diff --git a/test/main/features/project_driver_run_now.test.ts b/test/main/features/project_driver_run_now.test.tsindex c2eb4568..9486f513 100644--- a/test/main/features/project_driver_run_now.test.ts+++ b/test/main/features/project_driver_run_now.test.ts@@ -33,6 +33,7 @@ vi.mock('../../../src/main/features/agents', () => ({}));vi.mock('../../../src/main/features/projects', () => ({projectExists: vi.fn(async () => true),+ getProject: vi.fn(async () => ({ project_id: 'p_112233445566', owner_uid: 'uRUNNOW' })),getBindings: vi.fn(async () => ({ agents: ['a_owner'], skills: [] })),listProjects: vi.fn(async () => []),}));diff --git a/test/main/features/project_files.test.ts b/test/main/features/project_files.test.tsindex 97ea375d..3cc0bb97 100644--- a/test/main/features/project_files.test.ts+++ b/test/main/features/project_files.test.ts@@ -12,6 +12,7 @@ const enqueueCalls: Array<{ userId: string; projectId: string; name: string; op:vi.mock('../../../src/main/features/projects', () => ({projectExists: async () => true,+ getProject: async () => null,}));vi.mock('../../../src/main/features/project_library_indexer', () => ({diff --git a/test/main/features/project_tasks.test.ts b/test/main/features/project_tasks.test.tsindex 27856d47..4278c7b9 100644--- a/test/main/features/project_tasks.test.ts+++ b/test/main/features/project_tasks.test.ts@@ -67,6 +67,121 @@ function globalAttachDir(tid: string): string {}describe('project_tasks › global scope', () => {+ it.each(['project', 'global'])('copies a chat attachment through the todo tool into durable %s storage', async (scope) => {+ const { pt, pid: projectId } = await setup();+ const pid = scope === 'global' ? '' : projectId;+ const { chatAttachmentDirForConversation } = await import('../../../src/main/util/project-layout');+ const { createProjectTasksHandler } = await import('../../../src/main/features/project_tasks_tool_handler');+ const { createProjectTasksTool } = await import('../../../src/core-agent/src/tools/project-tasks-tool');+ const sourceDir = chatAttachmentDirForConversation(TEST_UID, 'c-attachment');+ fs.mkdirSync(sourceDir, { recursive: true });+ const source = path.join(sourceDir, 'brief.txt');+ fs.writeFileSync(source, 'The actual document, not just its name.');+ const tool = createProjectTasksTool(createProjectTasksHandler(TEST_UID, pid, 'c-attachment', new Map()));+ const receipt = JSON.parse((await tool.execute({ action: 'create', content: 'Review attached brief' }, { state: {} })).content);+ const added = await tool.execute({ action: 'add_attachment', task_id: receipt.task.id, source_path: source }, { state: {} });+ expect(added.isError).toBe(false);+ expect(JSON.parse(added.content).task.attachments).toEqual(['brief.txt']);+ const dir = pid ? path.join(path.dirname(taskFile(pid, receipt.task.id)), '..', 'task_attachments', receipt.task.id) : globalAttachDir(receipt.task.id);+ expect(fs.readFileSync(path.join(dir, 'brief.txt'), 'utf8')).toBe('The actual document, not just its name.');+ fs.writeFileSync(source, 'Must not replace the saved document');+ const repeat = await tool.execute({ action: 'add_attachment', task_id: receipt.task.id, source_path: source }, { state: {} });+ expect(repeat.isError).toBe(true);+ expect(JSON.parse(repeat.content).error).toBe('attachment_already_exists');+ fs.unlinkSync(source);+ expect(fs.readFileSync(path.join(dir, 'brief.txt'), 'utf8')).toBe('The actual document, not just its name.');+ expect(await pt.getTask(TEST_UID, pid, receipt.task.id)).toMatchObject({ attachments: ['brief.txt'], status: 'todo' });+ expect(JSON.parse((await tool.execute({ action: 'get', task_id: receipt.task.id }, { state: {} })).content).task.attachments).toEqual(['brief.txt']);+ const deleted = await tool.execute({ action: 'delete', task_id: receipt.task.id }, { state: {} });+ expect(JSON.parse(deleted.content)).toEqual({ ok: true, task_id: receipt.task.id, deleted: true });+ expect(await pt.getTask(TEST_UID, pid, receipt.task.id)).toBeNull();+ expect(fs.existsSync(dir)).toBe(false);++ });++ it('rejects foreign files, symlink escapes, missing files, unsupported files and oversized inputs without changing a todo', async () => {+ const { pt, pid } = await setup();+ const { createProjectTasksHandler } = await import('../../../src/main/features/project_tasks_tool_handler');+ const workspace = path.join(tmpDir, 'allowed');+ fs.mkdirSync(workspace);+ const outside = path.join(tmpDir, 'foreign.txt');+ fs.writeFileSync(outside, 'private');+ fs.symlinkSync(outside, path.join(workspace, 'escape.txt'));+ fs.writeFileSync(path.join(workspace, 'program.exe'), 'exe');+ const oversized = path.join(workspace, 'big.txt');+ fs.writeFileSync(oversized, '');+ fs.truncateSync(oversized, pt.TASK_ATTACHMENT_MAX_BYTES + 1);+ const created = await pt.createTask(TEST_UID, pid, { content: 'No attachment on failure' });+ if (!created.ok) throw new Error('fixture failed');+ const handler = createProjectTasksHandler(TEST_UID, pid, '', new Map(), {}, { workingDir: workspace });+ for (const source of [outside, path.join(workspace, 'escape.txt'), path.join(workspace, 'missing.txt'),+ path.join(workspace, 'program.exe'), oversized, 'relative.txt']) {+ expect((await handler.addAttachment!(created.task.id, source)).ok).toBe(false);+ expect(await pt.getTask(TEST_UID, pid, created.task.id)).toEqual(created.task);+ expect(await pt.listTaskAttachments(TEST_UID, pid, created.task.id)).toEqual([]);+ }+ const valid = path.join(workspace, 'valid.txt'); fs.writeFileSync(valid, 'Valid');+ expect((await handler.addAttachment!('t_000000000000', valid)).error).toBe('task_not_found');+ const users = await import('../../../src/main/features/users');+ users.activateUser('other');+ expect((await handler.addAttachment!(created.task.id, valid)).error).toBe('account_changed');+ });++ it('preserves the first attachment when two additions race for the same name', async () => {+ const { pt, pid } = await setup();+ const task = await pt.createTask(TEST_UID, pid, { content: 'Race attachment' });+ if (!task.ok) throw new Error('fixture failed');+ const results = await Promise.all(['First', 'Second'].map(value =>+ pt.uploadTaskAttachment(TEST_UID, pid, task.task.id, 'brief.txt', Buffer.from(value), { overwrite: false })));+ expect(results.filter(r => r.ok)).toHaveLength(1);+ expect(results.filter(r => !r.ok)).toEqual([{ ok: false, error: 'attachment_already_exists' }]);+ expect(await pt.listTaskAttachments(TEST_UID, pid, task.task.id)).toEqual(['brief.txt']);+ });++ it('removes partial attachment bytes after a disk failure and permits a clean retry', async () => {+ const { pt, pid } = await setup();+ const created = await pt.createTask(TEST_UID, pid, { content: 'Recoverable attachment' });+ if (!created.ok) throw new Error('fixture failed');+ const { createProjectTasksHandler } = await import('../../../src/main/features/project_tasks_tool_handler');+ const source = path.join(tmpDir, 'brief.txt'); fs.writeFileSync(source, 'Complete bytes');+ const handler = createProjectTasksHandler(TEST_UID, pid, '', new Map(), {}, { workingDir: tmpDir });+ const original = nativeFs.promises.writeFile;+ const spy = vi.spyOn(nativeFs.promises, 'writeFile').mockImplementation(async (target, body, options) => {+ if (String(target).includes('.pending-')) {+ await original(target, 'partial', options);+ throw Object.assign(new Error('injected disk full'), { code: 'ENOSPC' });+ }+ return original(target, body, options);+ });+ syncBuiltinESMExports();+ try {+ expect(await handler.addAttachment!(created.task.id, source)).toEqual({ ok: false, error: 'write_failed' });+ expect(await pt.listTaskAttachments(TEST_UID, pid, created.task.id)).toEqual([]);+ expect(fs.readdirSync(path.join(path.dirname(taskFile(pid, created.task.id)), '..', 'task_attachments', created.task.id))).toEqual([]);+ expect(await pt.getTask(TEST_UID, pid, created.task.id)).toEqual(created.task);+ expect(taskLogs.some(args => args[0] === 'warn' && args[1] === 'attachment upload')).toBe(true);+ } finally { spy.mockRestore(); syncBuiltinESMExports(); }+ expect((await handler.addAttachment!(created.task.id, source)).ok).toBe(true);+ });++ it('does not gain access to the destination project workspace when attaching from a different conversation scope', async () => {+ const { pt, pid } = await setup();+ const { setWorkspacePath } = await import('../../../src/main/features/user_workspace');+ const current = path.join(tmpDir, 'current-workspace'), other = path.join(tmpDir, 'other-workspace');+ fs.mkdirSync(current); fs.mkdirSync(other);+ setWorkspacePath(TEST_UID, current); setWorkspacePath(TEST_UID, other, pid);+ const source = path.join(current, 'brief.txt'), foreign = path.join(other, 'private.txt');+ fs.writeFileSync(source, 'Current conversation document'); fs.writeFileSync(foreign, 'Unrelated document');+ const created = await pt.createTask(TEST_UID, pid, { content: 'Receive the current document' });+ if (!created.ok) throw new Error('fixture failed');+ const { createProjectTasksHandler } = await import('../../../src/main/features/project_tasks_tool_handler');+ const handler = createProjectTasksHandler(TEST_UID, pid, '', new Map(), {}, { sourceProjectId: '' });+ expect((await handler.addAttachment!(created.task.id, foreign)).ok).toBe(false);+ expect((await handler.addAttachment!(created.task.id, source)).ok).toBe(true);+ expect(await pt.listTaskAttachments(TEST_UID, pid, created.task.id)).toEqual(['brief.txt']);+ });++it('records attachment success and disk failure without disclosing the local identity or filename', async () => {const pt = await import('../../../src/main/features/project_tasks');const tid = 't_aabbccddeeff';@@ -633,6 +748,24 @@ function attachDir(pid: string, tid: string): string {}describe('project_tasks › attachments', () => {+ it('opens draft attachments only at their exact local account path', async () => {+ const { pt, pid } = await setup();+ const tid = 't_0123456789ab';+ expect(await pt.uploadTaskAttachment(TEST_UID, pid, tid, 'draft.txt', Buffer.from('Draft bytes'))).toEqual({ ok: true, name: 'draft.txt' });+ const expected = path.join(attachDir(pid, tid), 'draft.txt');+ expect(await pt.resolveTaskAttachmentPath(TEST_UID, pid, tid, 'draft.txt')).toBe(expected);+ for (const name of ['../draft.txt', 'sub/draft.txt', '.hidden', 'missing.txt']) {+ expect(await pt.resolveTaskAttachmentPath(TEST_UID, pid, tid, name)).toBeNull();+ }+ expect(await pt.resolveTaskAttachmentPath('other-account', pid, tid, 'draft.txt')).toBeNull();+ const foreign = path.join(tmpDir, 'outside.txt');+ fs.writeFileSync(foreign, 'Outside bytes');+ fs.unlinkSync(expected);+ fs.symlinkSync(foreign, expected);+ expect(await pt.resolveTaskAttachmentPath(TEST_UID, pid, tid, 'draft.txt')).toBeNull();+ expect(fs.readFileSync(foreign, 'utf8')).toBe('Outside bytes');+ });+it('uploads a file, caches the name on the task, and lists it', async () => {const { pt, pid } = await setup();const created = await pt.createTask(TEST_UID, pid, { content: 'with files' });diff --git a/test/main/features/project_todo_e2e.test.ts b/test/main/features/project_todo_e2e.test.tsindex f2bc0532..6f4d60ae 100644--- a/test/main/features/project_todo_e2e.test.ts+++ b/test/main/features/project_todo_e2e.test.ts@@ -24,6 +24,10 @@ vi.mock('../../../src/main/model/client', () => ({async *streamChatWithModel() { yield { type: 'final', text: '' }; yield { type: 'done' }; },async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },}));+// This deterministic trunk has no desktop window; browser input has its own suites.+vi.mock('../../../src/main/features/web_assist', () => ({+ bindHostStartedWebAssistConversation: () => false,+}));vi.mock('../../../src/main/features/chats', () => ({createConversation: vi.fn(),deleteConversation: vi.fn(),diff --git a/test/renderer/project-agent-sharing.test.ts b/test/renderer/project-agent-sharing.test.tsnew file mode 100644index 00000000..f6cb8b5e--- /dev/null+++ b/test/renderer/project-agent-sharing.test.ts@@ -0,0 +1,37 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';+import vm from 'node:vm';+import { describe, expect, it } from 'vitest';++const source = readFileSync(path.join(__dirname, '../../src/renderer/modules/project-detail.js'), 'utf8');+const start = source.indexOf('function _renderProjectAgentCards(items) {');+const end = source.indexOf('function _bindProjectAgentCards()', start);+if (start < 0 || end < 0) throw new Error('project Agent card renderer missing');+const projectMeta = { project: {} };+const renderCards = vm.runInNewContext(`(${source.slice(start, end).trim()})`, {+ _byDisplayName: (a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name),+ _projectDetailMeta: projectMeta,+ currentUserId: 'member',+ _projectDetailPid: 'project',+ escapeHtml: (value: string) => value,+ t: (key: string) => key,+ _projectUiIconHtml: (name: string) => `<svg data-icon="${name}"></svg>`,+});++describe('ordinary project Agent controls', () => {+ it('omits privacy locks for every Agent in an ordinary project', () => {+ for (const agent of [+ { source: 'custom', shared_with_members: false, runtime: { kind: 'in_process' } },+ { source: 'custom', shared_with_members: false, runtime: { kind: 'cli' } },+ { source: 'marketplace', seed_source: 'platform', shared_with_members: true },+ { source: 'builtin' },+ ]) {+ const html = renderCards([{ agent_id: 'agent', name: 'Agent', ...agent }]);+ expect(html).not.toContain('data-icon="lock"');+ expect(html).not.toContain('project-agent-row-sharing');+ expect(html).toContain('data-project-agent-run');+ expect(html).toContain('data-project-agent-remove');+ }+ });++});diff --git a/test/renderer/project-binding-picker-order.test.ts b/test/renderer/project-binding-picker-order.test.tsnew file mode 100644index 00000000..66f3ed0f--- /dev/null+++ b/test/renderer/project-binding-picker-order.test.ts@@ -0,0 +1,59 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';+import vm from 'node:vm';+import { describe, expect, it, vi } from 'vitest';++const source = readFileSync(path.join(__dirname, '../../src/renderer/modules/project-detail.js'), 'utf8');++describe('project binding picker order', () => {+ it('keeps custom agents first and natural name order within each source when browsing and searching', async () => {+ const agents = [+ { agent_id: 'platform10', source: 'marketplace', name: 'A Agent 10' },+ { agent_id: 'custom10', source: 'custom', name: 'Z Agent 10' },+ { agent_id: 'platform2', source: 'marketplace', name: 'a Agent 2' },+ { agent_id: 'custom2', source: 'custom', name: 'z Agent 2' },+ ].map(agent => ({ ...agent, description_en: 'Matching description' }));+ const inputHandlers: Record<string, () => void> = {};+ const search = {+ value: '', focus() {},+ addEventListener: (event: string, handler: () => void) => { inputHandlers[event] = handler; },+ };+ const list = { innerHTML: '', querySelectorAll: () => [] };+ const empty = { textContent: '', style: { display: '' } };+ const overlay = {+ innerHTML: '',+ querySelector: (selector: string) => ({+ '#project-binding-picker-list': list,+ '#project-binding-picker-empty': empty,+ '#project-binding-picker-search-input': search,+ })[selector] ?? null,+ };+ const warn = vi.fn();+ const context = vm.createContext({+ createLogger: () => ({ warn }),+ window: { addEventListener() {}, orkas: { invoke: async () => ({ ok: true, agents }) } },+ document: {+ readyState: 'loading', addEventListener() {}, getElementById: () => null,+ createElement: () => overlay, body: { appendChild() {} },+ },+ escapeHtml: (value: unknown) => String(value ?? ''),+ pickDesc: (item: { description_en: string }) => item.description_en,+ t: (key: string) => key,+ setTimeout: (callback: () => void) => callback(),+ });+ vm.runInContext(source, context, { filename: 'project-detail.js' });+ await context._openAddPicker();+ const visibleIds = () => [...list.innerHTML.matchAll(/data-id="([^"]+)"/g)].map(match => match[1]);+ const expected = ['custom2', 'custom10', 'platform2', 'platform10'];+ expect(visibleIds()).toEqual(expected);++ for (const query of ['Agent', ' matching ', 'no results', 'Agent 2', '']) {+ search.value = query;+ inputHandlers.input();+ expect(visibleIds()).toEqual(query === 'no results' ? []+ : query === 'Agent 2' ? ['custom2', 'platform2'] : expected);+ expect(empty.style.display).toBe(query === 'no results' ? '' : 'none');+ }+ expect(warn).not.toHaveBeenCalled();+ });+});diff --git a/test/renderer/project-chat-recipient-scope.test.ts b/test/renderer/project-chat-recipient-scope.test.tsindex c9365206..7bf4b325 100644--- a/test/renderer/project-chat-recipient-scope.test.ts+++ b/test/renderer/project-chat-recipient-scope.test.ts@@ -1,3 +1,4 @@+import { composerAccessorSource } from './composer-test-source';import { describe, expect, it } from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';@@ -50,10 +51,13 @@ type Recipient = { kind: string; id?: string; name?: string };/** Let pending microtasks and the IPC promise chain settle. */const settle = () => new Promise((resolve) => { setTimeout(resolve, 0); });-function mountProjectDetail(bindings: Bindings, held: string[] = []) {+function mountProjectDetail(bindings: Bindings, held: string[] = [], agentDetails: Record<string, Array<{ agent_id: string; name: string }>> = {}) {const holdSet = new Set(held);const gates: Record<string, Array<() => void>> = {};const bindingCalls: string[] = [];+ const agentList = { innerHTML: '', style: {}, querySelectorAll() { return []; } };+ const agentEmpty = { style: {} };+ const agentCount = { textContent: '' };const answer = (channel: string, value: unknown) => {if (!holdSet.has(channel)) return Promise.resolve(value);return new Promise((resolve) => {@@ -62,11 +66,17 @@ function mountProjectDetail(bindings: Bindings, held: string[] = []) {};const context = vm.createContext({console,+ currentUserId: 'project-recipient-fixture',createLogger: () => ({ warn() {}, info() {}, error() {} }),document: {readyState: 'loading',addEventListener() {},- getElementById() { return null; },+ getElementById(id: string) {+ if (id === 'project-agents-list') return agentList;+ if (id === 'project-agents-empty') return agentEmpty;+ if (id === 'project-detail-agents-count') return agentCount;+ return null;+ },querySelectorAll() { return []; },createElement() { return { appendChild() {}, className: '', dataset: {}, style: {} }; },},@@ -83,7 +93,7 @@ function mountProjectDetail(bindings: Bindings, held: string[] = []) {return answer(channel, {ok: true,bindings: { agents: bindings[pid] || [] },- agentDetails: [],+ agentDetails: agentDetails[pid] || [],});case 'projects.files.tree':return answer(channel, { ok: true, tree: [] });@@ -99,10 +109,12 @@ function mountProjectDetail(bindings: Bindings, held: string[] = []) {},},t: (key: string) => key,+ escapeHtml: (value: unknown) => String(value ?? ''),uiAlert() {},setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(projectDetailSource, context, { filename: 'project-detail.js' });vm.runInContext('const _COMMANDER = { kind: "commander", id: "", name: "" }; const _composerAgentScopes = new Map();\n'@@ -126,11 +138,14 @@ function mountProjectDetail(bindings: Bindings, held: string[] = []) {function __readProjectRecipient() { return JSON.parse(JSON.stringify(__projectRecipient)); }function __pickProjectAgent(id, name) { __projectRecipient = { kind: 'agent', id, name }; }_renderProjectDetail = function () {};+ _bindProjectAgentCards = function () {};_setProjectAutoTabCount = function () {};_kickProjectKbReconcileIfNeeded = function () {};_scheduleProjectKbStatusRefreshIfNeeded = function () {};`, context);return {+ agentList,+ agentCount,bindingCalls,pickAgent(id: string, name: string) {vm.runInContext(`__pickProjectAgent(${JSON.stringify(id)}, ${JSON.stringify(name)})`, context);@@ -155,6 +170,22 @@ function mountProjectDetail(bindings: Bindings, held: string[] = []) {const COMMANDER: Recipient = { kind: 'commander' };describe('project composer recipient follows the open project', () => {+ it('shows a bound Agent while a large project library is still loading', async () => {+ const panel = mountProjectDetail(+ { p_alpha: ['agent_writer'] },+ ['projects.files.tree'],+ { p_alpha: [{ agent_id: 'agent_writer', name: 'Writer' }] },+ );+ const opening = panel.open('p_alpha');+ await settle();++ expect(panel.agentList.innerHTML).toContain('Writer');+ expect(panel.agentCount.textContent).toBe('1');++ panel.release('projects.files.tree');+ await opening;+ });+it('drops an agent the newly opened project is not bound to', async () => {const panel = mountProjectDetail({ p_alpha: ['agent_writer'], p_beta: ['agent_coder'] });await panel.open('p_alpha');@@ -213,6 +244,8 @@ describe('project composer recipient follows the open project', () => {const panel = mountProjectDetail({ p_alpha: ['agent_writer'], p_beta: ['agent_coder'] },['projects.bindings.list'],+ { p_alpha: [{ agent_id: 'agent_writer', name: 'Writer' }],+ p_beta: [{ agent_id: 'agent_coder', name: 'Coder' }] },);const first = panel.open('p_alpha');const second = panel.open('p_beta');@@ -222,6 +255,8 @@ describe('project composer recipient follows the open project', () => {await Promise.all([first, second]);expect(panel.recipient()).toEqual({ kind: 'agent', id: 'agent_coder', name: 'Coder' });+ expect(panel.agentList.innerHTML).toContain('Coder');+ expect(panel.agentList.innerHTML).not.toContain('Writer');expect(panel.bindingCalls).toEqual(['p_alpha', 'p_beta']);});diff --git a/test/renderer/project-detail-local-cache.test.ts b/test/renderer/project-detail-local-cache.test.tsnew file mode 100644index 00000000..c11a42c8--- /dev/null+++ b/test/renderer/project-detail-local-cache.test.ts@@ -0,0 +1,139 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import * as vm from 'node:vm';+import { describe, expect, it, vi } from 'vitest';++const source = readFileSync(join(__dirname, '../../src/renderer/modules/project-detail.js'), 'utf8');++function mountWithSlowSecondaryCard({ delayInstructionsFor = '' } = {}) {+ let finishAutoTasks!: (value: unknown) => void;+ const delayedAutoTasks = new Promise((resolve) => { finishAutoTasks = resolve; });+ let finishInstructions: ((value: unknown) => void) | null = null;+ const nodes: Record<string, any> = {+ 'project-agents-list': { innerHTML: '', style: {}, querySelectorAll: () => [] },+ 'project-detail-agents-count': { textContent: '' },+ 'project-detail-content': { classList: { toggle() {} }, setAttribute() {} },+ 'project-instructions-input': { value: '', dataset: {}, disabled: false },+ 'project-instructions-read': { textContent: '', hidden: false },+ 'project-instructions-empty': { hidden: false },+ 'project-instructions-edit-btn': { disabled: false },+ 'project-instructions-setup-btn': { disabled: false },+ 'project-files-list': { innerHTML: '', querySelectorAll: () => [] },+ 'project-files-status': { textContent: '', style: {} },+ 'project-detail-files-count': { textContent: '' },+ };+ const context = vm.createContext({+ console,+ currentUserId: 'member',+ _byDisplayName: (a: any, b: any) => a.name.localeCompare(b.name),+ createLogger: () => ({ warn() {}, info() {}, error() {} }),+ document: {+ readyState: 'loading',+ addEventListener() {},+ getElementById: (id: string) => nodes[id] || null,+ querySelector: () => null,+ querySelectorAll: () => [],+ },+ window: { addEventListener() {}, orkas: { invoke(channel: string, args: { projectId?: string }) {+ if (channel === 'projects.get') return Promise.resolve({ ok: true, project: { project_id: args.projectId } });+ if (channel === 'projects.bindings.list') return Promise.resolve({ ok: true, bindings: { agents: ['writer'] }, agentDetails: [{ agent_id: 'writer', name: 'Cached Writer' }] });+ if (channel === 'projects.files.tree') return Promise.resolve({ ok: true, tree: [+ { type: 'file', name: 'cached.md', relPath: 'cached.md', kind: 'text', mtime: 0 },+ ] });+ if (channel === 'projects.files.status') return Promise.resolve({ ok: true, files: [] });+ if (channel === 'projects.instructions.get') {+ if (args.projectId === delayInstructionsFor) {+ return new Promise((resolve) => { finishInstructions = resolve; });+ }+ return Promise.resolve({ ok: true, content: args.projectId === 'project_a'+ ? 'Saved local rules' : 'Other project rules', limit: 4000 });+ }+ if (channel === 'memory.list') return Promise.resolve({ ok: true, entries: ['Saved memory'] });+ if (channel === 'autoTasks.list') return delayedAutoTasks;+ throw new Error(`Unexpected IPC channel: ${channel}`);+ } } },+ composerBindOwner() {},+ _setTodoLoadError() {},+ _renderProjectTodosList() {},+ _setProjectAutoTabCount() {},+ _renderProjectDetail() {},+ _buildProjectKbStatusMap: () => ({}),+ _flattenProjectLibraryFiles: () => [],+ _kickProjectKbReconcileIfNeeded() {},+ _scheduleProjectKbStatusRefreshIfNeeded() {},+ _updateProjectInstructionsFoot() {},+ escapeHtml: (value: unknown) => String(value ?? ''),+ setTimeout,+ clearTimeout,+ t: (key: string) => key,+ });+ vm.runInContext(source, context, { filename: 'project-detail.js' });+ vm.runInContext('_renderProjectDetail = function () {}; _kickProjectKbReconcileIfNeeded = function () {}; _scheduleProjectKbStatusRefreshIfNeeded = function () {};', context);+ return { context, nodes, finishAutoTasks,+ releaseInstructions() { finishInstructions?.({ ok: true, content: 'Saved local rules', limit: 4000 }); } };+}++describe('project detail local cache after restart', () => {+it('preserves automation content while its feature loads without a loading placeholder', async () => {+ const { context, nodes } = mountWithSlowSecondaryCard();+ const list = { innerHTML: 'Saved automation' };+ nodes['project-auto-list'] = list;+ let release!: () => void;+ context.loadRendererFeature = () => new Promise<void>(resolve => { release = resolve; });+ vm.runInContext('_projectDetailPid = "project_a"; _projectDetailActiveTab = "auto"; _projectDetailLoadSeq = 1;', context);+ const opening = context._ensureProjectAutoTabLoaded('project_a');+ expect(list.innerHTML).toBe('Saved automation');+ context.loadProjectAutoList = vi.fn(async () => { list.innerHTML = 'Updated automation'; });+ release();+ await opening;+ expect(list.innerHTML).toBe('Updated automation');+ expect(context.loadProjectAutoList).toHaveBeenCalledWith('project_a');+ });++it('does not paint memory returned after the account changes', async () => {+ const { context, finishAutoTasks } = mountWithSlowSecondaryCard();+ context.currentUserId = 'first';+ const invoke = context.window.orkas.invoke;+ let finishMemory!: (value: unknown) => void;+ context.window.orkas.invoke = (channel: string, args: any) => channel === 'memory.list'+ ? new Promise(resolve => { finishMemory = resolve; }) : invoke(channel, args);+ const opening = context.loadProjectDetail('project_a');+ finishAutoTasks({ ok: true, tasks: [] });+ await opening;+ context.currentUserId = 'second';+ finishMemory({ ok: true, entries: ['First account memory'] });+ await new Promise(resolve => setTimeout(resolve, 0));+ expect(vm.runInContext('_projectMemory', context)).toEqual([]);+ });++it('shows saved project rules and files while a secondary card is still loading', async () => {+ const { context, nodes, finishAutoTasks } = mountWithSlowSecondaryCard();+ const opening = context.loadProjectDetail('project_a') as Promise<void>;+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(nodes['project-instructions-read'].textContent).toBe('Saved local rules');+ expect(nodes['project-instructions-empty'].hidden).toBe(true);+ expect(nodes['project-files-list'].innerHTML).toContain('cached.md');+ expect(nodes['project-agents-list'].innerHTML).toContain('Cached Writer');+ expect(vm.runInContext('_projectMemory', context)).toEqual(['Saved memory']);+ expect(nodes['project-detail-files-count'].textContent).toBe('1');++ finishAutoTasks({ ok: true, tasks: [] });+ await opening;+ });++it('does not show the previous project’s late local rules after navigation', async () => {+ const { context, nodes, finishAutoTasks, releaseInstructions } = mountWithSlowSecondaryCard({ delayInstructionsFor: 'project_a' });+ const first = context.loadProjectDetail('project_a') as Promise<void>;+ const second = context.loadProjectDetail('project_b') as Promise<void>;+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(nodes['project-instructions-read'].textContent).toBe('Other project rules');++ releaseInstructions();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(nodes['project-instructions-read'].textContent).toBe('Other project rules');++ finishAutoTasks({ ok: true, tasks: [] });+ await Promise.all([first, second]);+ });+});diff --git a/test/renderer/project-instructions-editor.test.ts b/test/renderer/project-instructions-editor.test.tsindex 1ccb44ca..88d8f840 100644--- a/test/renderer/project-instructions-editor.test.ts+++ b/test/renderer/project-instructions-editor.test.ts@@ -126,6 +126,18 @@ describe('project instructions editor', () => {expect(input.value).toBe('Original rules.');});+ it('preserves an open draft when background refresh updates the saved rules', async () => {+ const { context, elements } = mount('Original rules.');+ context._openProjectInstructionsEditor();+ elements['project-instructions-input'].value = 'My unsaved draft';+ vm.runInContext('_projectDetailMeta.instructions.content = "Updated shared rules"', context);+ context._renderProjectInstructions();+ expect(elements['project-instructions-input'].value).toBe('My unsaved draft');+ expect(elements['project-instructions-read'].textContent).toBe('Updated shared rules');+ await context._closeProjectInstructionsEditor({ force: true });+ expect(elements['project-instructions-input'].value).toBe('Updated shared rules');+ });+it('refuses to open the editor for instructions it could not load', () => {const { context, elements } = mount(null);context._openProjectInstructionsEditor();diff --git a/test/renderer/project-library-external-drop.test.ts b/test/renderer/project-library-external-drop.test.tsindex a5644a65..47627b6b 100644--- a/test/renderer/project-library-external-drop.test.ts+++ b/test/renderer/project-library-external-drop.test.ts@@ -294,7 +294,7 @@ describe('Project Library external file drag-and-drop', () => {expect(context.window.orkas.invoke).toHaveBeenCalledTimes(7);});- it('keeps telemetry and rejection alerts when the post-upload refresh fails', async () => {+ it('keeps rejection alerts when the post-upload refresh fails', async () => {const context = loadProjectDetailScript();const file = { name: 'ok.md', arrayBuffer: vi.fn(async () => new ArrayBuffer(1)) };const rejected = { name: 'bad.zip', arrayBuffer: vi.fn() };@@ -305,17 +305,10 @@ describe('Project Library external file drag-and-drop', () => {context._projectLogFailure = vi.fn();await expect(context._uploadProjectFiles([file, rejected], '', 'drop')).resolves.toBeUndefined();-- expect(context._projectTrackEvent).toHaveBeenCalledWith('project_file_upload_result', expect.objectContaining({- result: 'partial_failure',- uploaded_count: 1,- rejected_count: 1,- }));expect(context._projectLogFailure).toHaveBeenCalledWith('project_file_upload', expect.objectContaining({error_code: 'files_rejected',error_type: 'validation',}));- expect(context._projectTrackEvent.mock.calls[0][1]).not.toHaveProperty('project_id');expect(context.uiAlert).toHaveBeenCalledWith(expect.stringContaining('bad.zip'));});});diff --git a/test/renderer/project-memory-controls.test.ts b/test/renderer/project-memory-controls.test.tsindex 6544d242..20db9b5a 100644--- a/test/renderer/project-memory-controls.test.ts+++ b/test/renderer/project-memory-controls.test.ts@@ -98,10 +98,6 @@ describe('project memory controls', () => {expect(source).toContain("input.value !== (input.dataset.savedValue || '')");expect(source).toContain('saveBtn.disabled = !dirty || over');expect(source).toContain("uiAlert(t('project.instructions.save_failed'))");- expect(source).toContain("_projectTrackEvent('project_instructions_update_result'");- expect(source).toContain("result: 'success'");- expect(source).toContain("result: 'failure'");- expect(source).toContain('duration_ms: Math.max(0, Math.round(performance.now() - startedAt))');expect(source).toContain("input.dataset.projectId = String(_projectDetailPid || '')");expect(source).toContain('if (input.dataset.projectId === projectId) input.dataset.savedValue = content');});diff --git a/test/renderer/project-todo-controls.test.ts b/test/renderer/project-todo-controls.test.tsindex 01dea48f..f765b5be 100644--- a/test/renderer/project-todo-controls.test.ts+++ b/test/renderer/project-todo-controls.test.ts@@ -1,3 +1,4 @@+import { composerAccessorSource } from './composer-test-source';import { describe, expect, it } from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';@@ -27,6 +28,7 @@ describe('project to-do controls', () => {t: (key: string) => key,setTimeout, clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context);context._openTodoRowMenu({}, 't_123456789abc', {pid: 'p_test', tasks: [{ id: 't_123456789abc', title: 'Continue work', status }],@@ -86,6 +88,7 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });const card = context._renderTodoCard(task, { pid: 'p_test', tasks: [task], agents: [] });@@ -178,6 +181,7 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'; _bindProjectTodos();", context);await context._loadProjectTodos('p_test');@@ -295,6 +299,7 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test';"@@ -414,6 +419,7 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'; _bindProjectTodos();", context);await context._loadProjectTodos('p_test');@@ -493,6 +499,7 @@ describe('project to-do controls', () => {uiAlert() {},setTimeout, clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test';", context);@@ -574,6 +581,7 @@ describe('project to-do controls', () => {uiAlert() {},setTimeout, clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'; _bindProjectTodos();", context);context._openProjectTodoEditor();@@ -587,9 +595,8 @@ describe('project to-do controls', () => {expect(attachWrap.innerHTML).toContain('brief.txt');});- it('keeps the next project editor intact when an earlier attachment deletion finishes late', async () => {- let resolveDelete!: (value: unknown) => void;- const deletion = new Promise((resolve) => { resolveDelete = resolve; });+ it('discards staged attachment removals when switching to another project editor', async () => {+ const deletions: string[] = [];const editor = { hidden: true };const input = { value: '', maxLength: 200, dataset: {}, focus() {}, setSelectionRange() {}, addEventListener() {} };const attachWrap = { innerHTML: '', hidden: true, querySelectorAll: () => [] as any[] };@@ -604,13 +611,14 @@ describe('project to-do controls', () => {console,createLogger: () => ({ warn() {}, info() {}, error() {} }),document: { readyState: 'loading', addEventListener() {}, getElementById(id: string) { return elements[id] || null; } },- window: { addEventListener() {}, orkas: { async invoke(channel: string) { return channel === 'projects.tasks.attachments.delete' ? deletion : { ok: true }; } } },+ window: { addEventListener() {}, orkas: { async invoke(channel: string) { if (channel === 'projects.tasks.attachments.delete') deletions.push(channel); return { ok: true }; } } },_chatFileIconHtml: () => '<svg></svg>',t: (key: string) => key,escapeHtml: (value: unknown) => String(value == null ? '' : value),uiIconHtml: () => '<svg></svg>',setTimeout, clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test';", context);@@ -618,16 +626,18 @@ describe('project to-do controls', () => {expect(attachWrap.hidden).toBe(false);expect(attachWrap.innerHTML).toContain('a.txt');expect(attachWrap.innerHTML).toContain('b.png');- const pending = context._removeTodoEditorAttachment('a.txt');+ await context._removeTodoEditorAttachment('a.txt');context._openProjectTodoEditor({ id: 't_defdefdefdef', title: 'Other project', status: 'todo', attachments: ['a.txt', 'c.png'] },{ pid: 'p_other', tasks: [], agents: [] },);- resolveDelete({ ok: true });- await pending;+ expect(deletions).toEqual([]);expect(attachWrap.innerHTML).toContain('a.txt');expect(attachWrap.innerHTML).toContain('c.png');expect(attachWrap.innerHTML).not.toContain('b.png');+ input.value = 'Saved in the other project';+ await context._saveProjectTodoEditor();+ expect(deletions).toEqual([]);});it('confirms the auto-advance toggle with a toast', async () => {@@ -666,6 +676,7 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'; _bindProjectDriver();", context);@@ -702,6 +713,7 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });// A background driver advance pushes its new conversation; it lands in the@@ -744,6 +756,7 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'; _projectDetailMeta = { project: {} };", context);@@ -761,14 +774,8 @@ describe('project to-do controls', () => {});it('restores the send control when project conversation creation fails', async () => {- const events: any[] = [];- const clicks: any[] = [];const input = { value: 'project question' };const button = { disabled: false };- const Monitor = {- click(name: string, payload: any) { clicks.push({ name, payload }); },- event(name: string, payload: any) { events.push({ name, payload }); },- };const context = vm.createContext({console,performance,@@ -782,14 +789,9 @@ describe('project to-do controls', () => {return null;},},- window: { addEventListener() {}, Monitor: true },- Monitor,+ window: { addEventListener() {} },t: (key: string) => key,ensureModelConfigured: () => true,- _chatModelTelemetryContext: () => ({- provider: 'deepseek',- model: 'deepseek-v4-pro',- }),_getQuotes: () => [],_referenceSnapshotsForQuotes: () => [],consumeChatUseSelections: () => [],@@ -801,12 +803,12 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'", context);await context._submitProjectChat();- expect(events).toEqual([]);expect(button.disabled).toBe(false);});@@ -830,6 +832,7 @@ describe('project to-do controls', () => {},window: { addEventListener() {} },conversations: [],+ currentCid: null,t: (key: string) => key,ensureModelConfigured: () => true,_getQuotes: () => [],@@ -849,16 +852,18 @@ describe('project to-do controls', () => {renderConversationList() {},loadProjects() {},_chatAttachList: () => [],+ _consumeSubmittedQuotes() {},_clearQuotes() {},autoGrow() {},setView() {},setChatRecipient() {},- async sendInCurrentConversation(content: string, extra: Record<string, unknown>) {+ async sendInConversation(_cid: string, content: string, extra: Record<string, unknown>) {sent.push({ content, extra });},setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'", context);@@ -891,6 +896,7 @@ describe('project to-do controls', () => {},window: { addEventListener() {} },conversations: [],+ currentCid: null,t: (key: string) => key,ensureModelConfigured: () => true,_getQuotes: () => [],@@ -911,16 +917,18 @@ describe('project to-do controls', () => {renderConversationList() {},loadProjects() {},_chatAttachList: () => [],+ _consumeSubmittedQuotes() {},_clearQuotes() {},autoGrow() {},setView() {},setChatRecipient() {},- async sendInCurrentConversation(content: string, extra: Record<string, unknown>) {+ async sendInConversation(_cid: string, content: string, extra: Record<string, unknown>) {sent.push({ content, extra });},setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'", context);@@ -954,6 +962,7 @@ describe('project to-do controls', () => {},window: { addEventListener() {} },conversations: [],+ currentCid: null,t: (key: string) => key,ensureModelConfigured: () => true,_getQuotes: () => [],@@ -970,6 +979,7 @@ describe('project to-do controls', () => {items: [{ name: 'diagram.png', kind: 'image', bytes: 42, status: 'ready' }],}),_chatAttachClear() {},+ _consumeSubmittedQuotes() {},_clearQuotes() {},autoGrow() {},renderConversationList() {},@@ -989,12 +999,13 @@ describe('project to-do controls', () => {items: [{ sourceName: 'diagram.png', targetName: 'diagram.png' }],}) };},- async sendInCurrentConversation(content: string, extra: any) {+ async sendInConversation(_cid: string, content: string, extra: any) {sent.push({ content, extra });},setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'", context);@@ -1011,7 +1022,6 @@ describe('project to-do controls', () => {});it('keeps the project composer intact and records failure when attachment adoption fails', async () => {- const events: any[] = [];const invocations: any[] = [];const alerts: string[] = [];const input = { value: 'Review the attached brief' };@@ -1035,7 +1045,6 @@ describe('project to-do controls', () => {},window: {addEventListener() {},- Monitor: true,orkas: {async invoke(channel: string, payload: any) {invocations.push({ channel, payload });@@ -1043,11 +1052,8 @@ describe('project to-do controls', () => {},},},- Monitor: {- click() {},- event(name: string, payload: any) { events.push({ name, payload }); },- },conversations: [],+ currentCid: null,t: (key: string) => key,ensureModelConfigured: () => true,_getQuotes: () => [{ id: 'quote-1' }],@@ -1060,6 +1066,7 @@ describe('project to-do controls', () => {applyRecipientPrefix: (value: string) => value,_chatAttachList: () => [{ name: 'brief.pdf', status: 'ready' }],_chatAttachClear: () => { clearedAttachments += 1; },+ _consumeSubmittedQuotes: () => { clearedQuotes += 1; },_clearQuotes: () => { clearedQuotes += 1; },apiFetch: async (url: string) => ({json: async () => url.endsWith('/create')@@ -1069,10 +1076,11 @@ describe('project to-do controls', () => {uiAlert: async (message: string) => { alerts.push(message); },renderConversationList() {},loadProjects() {},- async sendInCurrentConversation() { sends += 1; },+ async sendInConversation() { sends += 1; },setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'", context);@@ -1111,6 +1119,7 @@ describe('project to-do controls', () => {},window: { addEventListener() {} },conversations: [],+ currentCid: null,t: (key: string) => key,ensureModelConfigured: () => true,_getQuotes: () => [],@@ -1123,6 +1132,7 @@ describe('project to-do controls', () => {applyRecipientPrefix: (value: string) => value,_chatAttachList: () => [{ name: 'brief.pdf', status: 'ready' }],_chatAttachClear: (cid: string) => { cleared.push(cid); },+ _consumeSubmittedQuotes() {},_clearQuotes() {},apiFetch: async (url: string) => ({json: async () => url.endsWith('/create')@@ -1138,10 +1148,11 @@ describe('project to-do controls', () => {autoGrow() {},setView() {},setChatRecipient() {},- async sendInCurrentConversation(content: string, extra: any) { sent.push({ content, extra }); },+ async sendInConversation(_cid: string, content: string, extra: any) { sent.push({ content, extra }); },setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'", context);@@ -1154,15 +1165,11 @@ describe('project to-do controls', () => {expect(cleared).toEqual(['projchat-p_test']);});- it('blocks project chat when no model is configured without telemetry', async () => {- const events: any[] = [];- const clicks: any[] = [];+ it('blocks project chat when no model is configured without creating a conversation', async () => {const input = { value: 'project question' };- const Monitor = {- click(name: string, payload: any) { clicks.push({ name, payload }); },- event(name: string, payload: any) { events.push({ name, payload }); },- };+ let attempted = false;const apiFetch = async () => {+ attempted = true;throw new Error('conversation creation must not run while blocked');};const context = vm.createContext({@@ -1176,14 +1183,9 @@ describe('project to-do controls', () => {return id === 'project-chat-input' ? input : null;},},- window: { addEventListener() {}, Monitor: true },- Monitor,+ window: { addEventListener() {} },t: (key: string) => key,ensureModelConfigured: () => false,- _chatModelTelemetryContext: () => ({- provider: 'deepseek',- model: 'deepseek-v4-pro',- }),_getQuotes: () => [],getChatUseSelections: () => [{ kind: 'skill', id: 'review' },@@ -1196,12 +1198,46 @@ describe('project to-do controls', () => {setTimeout,clearTimeout,});+ vm.runInContext(composerAccessorSource, context);vm.runInContext(source, context, { filename: 'project-detail.js' });vm.runInContext("_projectDetailPid = 'p_test'", context);await context._submitProjectChat();+ expect(attempted).toBe(false);+ expect(input.value).toBe('project question');++ });+});- expect(clicks).toEqual([]);- expect(events).toEqual([]);+describe('todo attachment preview recovery', () => {+ it('reports an unavailable file without opening a viewer and permits a scoped retry', async () => {+ let available = false;+ const opened: any[] = [];+ const alerts: string[] = [];+ const warnings: string[] = [];+ const calls: any[] = [];+ const context = vm.createContext({+ document: { readyState: 'loading', addEventListener() {} },+ window: { addEventListener() {}, orkas: { async invoke(channel: string, payload: any) {+ calls.push({ channel, payload });+ return available ? { ok: true, path: '/fixture/brief.txt' } : { ok: false };+ } } },+ createLogger: () => ({ warn: (message: string) => warnings.push(message), info() {}, error() {} }),+ openChatFileViewer: (...args: any[]) => opened.push(args),+ uiAlert: (message: string) => alerts.push(message), t: (key: string) => key,+ });+ vm.runInContext(composerAccessorSource, context);+ vm.runInContext(source, context);+ await context._previewTodoAttachment('p_other', 't_123456abcdef', 'brief.txt');+ expect(opened).toEqual([]);+ expect(alerts).toEqual(['chat.file_missing_toast']);+ expect(warnings).toEqual(['todo attachment preview failed']);+ available = true;+ await context._previewTodoAttachment('p_other', 't_123456abcdef', 'brief.txt');+ expect(opened).toEqual([['/fixture/brief.txt', 'brief.txt', {+ projectId: 'p_other', cid: null, readOnly: true, sourceElement: undefined,+ }]]);+ expect(calls.every(call => call.channel === 'projects.tasks.attachments.absPath'+ && call.payload.projectId === 'p_other' && call.payload.taskId === 't_123456abcdef')).toBe(true);});});diff --git a/test/renderer/todo-attachment-cancel.test.ts b/test/renderer/todo-attachment-cancel.test.tsnew file mode 100644index 00000000..558968a9--- /dev/null+++ b/test/renderer/todo-attachment-cancel.test.ts@@ -0,0 +1,140 @@+import { describe, expect, it, vi } from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import * as vm from 'node:vm';+import { composerAccessorSource } from './composer-test-source';++const source = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/project-detail.js'), 'utf8');+const { _arrayBufferToBase64 } = require('../../src/renderer/modules/utils.js');++// Real renderer actions with a disk-backed IPC fixture: cancellation must preserve+// bytes, not merely repaint the attachment chip. Main storage has its own suite.+function editorFixture(pid: string) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'todo-cancel-'));+ for (const name of ['a.txt', 'b.txt']) fs.writeFileSync(path.join(dir, name), `original ${name}`);+ const editor = { hidden: true };+ const input = { value: '', dataset: {}, focus() {}, setSelectionRange() {} };+ const chips = { innerHTML: '', hidden: true, querySelectorAll: () => [] };+ const elements: Record<string, any> = {+ 'project-todo-add': editor, 'project-todo-input': input, 'project-todo-attachments': chips,+ 'project-todo-save': {}, 'project-todo-cancel': {}, 'project-todo-counter': {},+ };+ const alerts = vi.fn();+ const state = { failUpdate: false, failDelete: '', content: 'Original', blockUpdate: null as Promise<any> | null };+ const invoke = vi.fn(async (channel: string, p: any) => {+ if (channel === 'projects.tasks.update') {+ if (state.blockUpdate) await state.blockUpdate;+ if (state.failUpdate) return { ok: false, error: 'save_failed' };+ state.content = p.content;+ }+ if (channel === 'projects.tasks.attachments.delete') {+ if (state.failDelete === p.name) return { ok: false };+ fs.rmSync(path.join(dir, p.name), { force: true });+ }+ if (channel === 'projects.tasks.attachments.upload') {+ fs.writeFileSync(path.join(dir, p.name), Buffer.from(p.dataBase64, 'base64'));+ return { name: p.name };+ }+ return { ok: true };+ });+ const context = vm.createContext({+ document: { readyState: 'loading', addEventListener() {}, getElementById: (id: string) => elements[id] || null },+ window: { addEventListener() {}, orkas: { invoke } },+ createLogger: () => ({ warn() {}, info() {}, error() {} }),+ t: (key: string) => key, escapeHtml: String, uiIconHtml: () => '', uiAlert: alerts,+ CHAT_ATTACH_ACCEPT: ['.txt'], _arrayBufferToBase64,+ btoa: (value: string) => Buffer.from(value, 'binary').toString('base64'),+ setTimeout: () => 0, clearTimeout() {},+ });+ vm.runInContext(composerAccessorSource, context);+ vm.runInContext(source, context);+ const open = () => context._openProjectTodoEditor({ id: 't_abcabcabcabc', content: state.content,+ status: 'todo', attachments: fs.readdirSync(dir) }, { pid, global: !pid, tasks: [], agents: [] });+ open();+ return { context, state, editor, input, chips, alerts, invoke, open,+ bytes: (name: string) => fs.readFileSync(path.join(dir, name), 'utf8'),+ names: () => fs.readdirSync(dir), dispose: () => fs.rmSync(dir, { recursive: true, force: true }) };+}++describe('todo attachment removal is committed by Save', () => {+ it.each(['p_project', ''])('cancel preserves original bytes and reopening restores chips (scope %s)', async (pid) => {+ const f = editorFixture(pid);+ try {+ await f.context._removeTodoEditorAttachment('a.txt');+ expect(f.chips.innerHTML).not.toContain('a.txt');+ expect(f.bytes('a.txt')).toBe('original a.txt');+ f.context._closeProjectTodoEditor();+ f.open();+ expect(f.chips.innerHTML).toContain('a.txt');+ expect(f.bytes('a.txt')).toBe('original a.txt');+ expect(f.invoke.mock.calls.some(([c]) => c === 'projects.tasks.attachments.delete')).toBe(false);+ } finally { f.dispose(); }+ });++ it('does not delete on failed Save and commits only selected files on retry', async () => {+ const f = editorFixture('p_project');+ try {+ await f.context._removeTodoEditorAttachment('a.txt');+ f.input.value = 'Edited';+ f.state.failUpdate = true;+ await f.context._saveProjectTodoEditor();+ expect(f.names()).toEqual(['a.txt', 'b.txt']);+ expect(f.editor.hidden).toBe(false);+ expect(f.alerts).toHaveBeenCalledWith('project.todo.failed');+ f.state.failUpdate = false;+ await f.context._saveProjectTodoEditor();+ expect(f.names()).toEqual(['b.txt']);+ expect(f.state.content).toBe('Edited');+ expect(f.editor.hidden).toBe(true);+ } finally { f.dispose(); }+ });++ it('retains failed deletions for retry without repeating successful removals', async () => {+ const f = editorFixture('p_project');+ try {+ await f.context._removeTodoEditorAttachment('a.txt');+ await f.context._removeTodoEditorAttachment('b.txt');+ f.state.failDelete = 'b.txt';+ await f.context._saveProjectTodoEditor();+ expect(f.names()).toEqual(['b.txt']);+ expect(f.editor.hidden).toBe(false);+ expect(f.alerts).toHaveBeenCalledWith('project.todo.failed');+ f.state.failDelete = '';+ await f.context._saveProjectTodoEditor();+ expect(f.names()).toEqual([]);+ expect(f.invoke.mock.calls.filter(([c, p]) => c === 'projects.tasks.attachments.delete' && p.name === 'a.txt')).toHaveLength(1);+ expect(f.editor.hidden).toBe(true);+ } finally { f.dispose(); }+ });++ it('keeps a reattached file when Save commits the edit', async () => {+ const f = editorFixture('p_project');+ try {+ await f.context._removeTodoEditorAttachment('a.txt');+ await f.context._todoPickAndUploadFiles([{ name: 'a.txt', size: 3,+ arrayBuffer: async () => new Uint8Array([110, 101, 119]).buffer }]);+ await f.context._saveProjectTodoEditor();+ expect(f.bytes('a.txt')).toBe('new');+ expect(f.names()).toEqual(['a.txt', 'b.txt']);+ } finally { f.dispose(); }+ });++ it('ignores attachment changes while Save is in progress', async () => {+ const f = editorFixture('p_project');+ let release!: () => void;+ try {+ await f.context._removeTodoEditorAttachment('a.txt');+ f.state.blockUpdate = new Promise<void>((resolve) => { release = resolve; });+ const save = f.context._saveProjectTodoEditor();+ await f.context._removeTodoEditorAttachment('b.txt');+ await f.context._todoPickAndUploadFiles([{ name: 'a.txt', size: 3,+ arrayBuffer: async () => new Uint8Array([110, 101, 119]).buffer }]);+ release();+ await save;+ expect(f.names()).toEqual(['b.txt']);+ expect(f.invoke.mock.calls.some(([c]) => c === 'projects.tasks.attachments.upload')).toBe(false);+ expect(f.editor.hidden).toBe(true);+ } finally { release?.(); f.dispose(); }+ });+});