Skip to content

armgit / Orkas

Public Imported from GitHub
0

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.

Refine home navigation and reversible task history cleanup

wyt448e8e70157b
diff --git a/src/main/features/chat_attachments.ts b/src/main/features/chat_attachments.ts
index 656fbe0b..b13807ad 100644
--- a/src/main/features/chat_attachments.ts
+++ b/src/main/features/chat_attachments.ts
@@ -1414,13 +1414,28 @@ export async function purgeByCid(userId: string, cid: string): Promise<number> {
let count = 0;
let names: string[] = [];
try {
- if (fs.existsSync(dir)) {
- const entries = fs.readdirSync(dir);
- names = entries.filter((n) => !n.startsWith('.'));
- for (const n of entries) {
- try { fs.unlinkSync(path.join(dir, n)); count++; } catch { /* best-effort */ }
+ const root = await fs.promises.lstat(dir).catch(err => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (root) {
+ const pending = root.isDirectory() ? [''] : [];
+ const files: string[] = [];
+ for (let cursor = 0; cursor < pending.length; cursor++) {
+ const parent = pending[cursor];
+ const entries = await fs.promises.readdir(path.join(dir, parent), { withFileTypes: true });
+ for (const entry of entries) {
+ const relative = path.join(parent, entry.name);
+ if (entry.isDirectory()) pending.push(relative);
+ else files.push(relative);
+ }
}
- try { fs.rmdirSync(dir); } catch { /* best-effort */ }
+ // rm removes links themselves; neither inventory nor removal follows
+ // a linked directory into another task or an external workspace.
+ await fs.promises.rm(dir, { recursive: true, force: true });
+ count = files.length;
+ names = files.filter(name => !name.split(path.sep).some(part => part.startsWith('.')))
+ .map(name => name.split(path.sep).join('/'));
}
} catch (err) { log.warn('attachment purge failed', { cid: maskId(cid), error: logErrorSummary(err) }); }
try { await purgeFileCacheByCid(userId, safeConvId); }
diff --git a/src/main/features/chats.ts b/src/main/features/chats.ts
index 9c005422..b3e6a938 100644
--- a/src/main/features/chats.ts
+++ b/src/main/features/chats.ts
@@ -1,3 +1,4 @@
+import { taskForPath, type TaskOwnership } from './conversation_deletions';
/**
* Conversations (per-user) — CRUD + message reads.
*
@@ -29,6 +30,7 @@ import {
} from '../paths';
import {
conversationLayout,
+ cloudRelForAbs,
assertConversationRelocationReady,
setConversationRelocationBlocked,
chatAttachmentDirForConversation,
@@ -1092,20 +1094,13 @@ async function _repairConversationIndexFromDiskUnlocked(
await _removeConversationMeta(userId, c.conversation_id);
continue;
}
- const deletedMs = tsMs(c.deleted_at);
- if (!deletedMs || st.mtimeMs <= deletedMs) {
- await _removeConversationMeta(userId, c.conversation_id);
- if (isExpiredIsoTombstone(c.deleted_at)) {
- try { await fsp.unlink(file); } catch { /* ignore */ }
- invalidateLineCount(file);
- }
- continue;
+ // A sync download has a fresh filesystem mtime too. Only an explicit
+ // restore/recreation may clear the record tombstone.
+ await _removeConversationMeta(userId, c.conversation_id);
+ if (isExpiredIsoTombstone(c.deleted_at)) {
+ try { await fsp.unlink(file); } catch { /* ignore */ }
+ invalidateLineCount(file);
}
- delete c.deleted_at;
- const restoredAt = new Date(Number.isFinite(st.mtimeMs) ? st.mtimeMs : Date.now()).toISOString();
- if (tsMs(c.updated_at) < tsMs(restoredAt)) c.updated_at = restoredAt;
- _stampConversationSync(userId, c);
- resurrected += 1;
}
const compacted = pruneExpiredDeletedRecords(items) as Conversation[];
const expiredTombstoneCount = items.length - compacted.length;
@@ -2360,7 +2355,7 @@ function purgeSession(userId: string, sessionId: string): void {
deleteSessionFileForUser(userId, sessionId);
}
-async function _purgeDeletedConversationFiles(userId: string, cid: string, removed?: Conversation): Promise<void> {
+async function _purgeDeletedConversationFiles(userId: string, cid: string, ownership: TaskOwnership, removed?: Conversation): Promise<void> {
// A completed turn may still be materializing remote image/video output in
// the background. Abort it before removing the message file; attachment
// purge also holds the writer lock so a response already past abort cannot
@@ -2406,6 +2401,7 @@ async function _purgeDeletedConversationFiles(userId: string, cid: string, remov
const sessionIds = new Set<string>();
for (const name of names) {
if (!name.startsWith(gmemberPrefix)) continue;
+ if (taskForPath(ownership, cloudRelForAbs(userId, path.join(sessionsDir, name)))?.cid !== cid) continue;
// A model-state reset can leave only retained historical outputs.
const suffix = ['.jsonl', '.tool-results'].find((ext) => name.endsWith(ext));
if (suffix) sessionIds.add(name.slice(0, -suffix.length));
@@ -2452,11 +2448,18 @@ export async function deleteConversation(
beforeDelete?: (current: Conversation) => Promise<boolean>,
): Promise<boolean> {
let removed: Conversation | null = null;
+ let ownership: TaskOwnership = new Map();
const found = await _withConversationIndexStore(userId, async (store) => {
const target = await store.findTarget(cid, projectIdHint);
if (!target) return false;
if (beforeDelete && !await beforeDelete(target.conversation)) return false;
removed = target.conversation;
+ // Reuse the already loaded root; bulk cleanup must not scan every project's
+ // index twice per task just to disambiguate member-session prefixes.
+ ownership = new Map((await store.readRoot(target.rootKey)).map(row => [
+ `${target.rootKey}/${row.conversation_id}`,
+ { cid: row.conversation_id, projectId: target.rootKey || null },
+ ]));
if (!isDeletedConversation(target.conversation)) {
const deletedAt = nowIso();
const tombstone = _stampConversationSync(userId, {
@@ -2464,6 +2467,8 @@ export async function deleteConversation(
deleted_at: deletedAt,
updated_at: deletedAt,
});
+ // Capture can yield; revalidate the cleanup receipt before committing it.
+ if (beforeDelete && !await beforeDelete(target.conversation)) return false;
await store.persistTarget(target, tombstone);
} else {
try {
@@ -2473,7 +2478,7 @@ export async function deleteConversation(
return true;
});
if (!found || !removed) return false;
- await _purgeDeletedConversationFiles(userId, cid, removed);
+ await _purgeDeletedConversationFiles(userId, cid, ownership, removed);
await (await import('./saved_apps')).cleanupEditSnapshots(userId, false, cid);
return true;
}
@@ -2957,3 +2962,10 @@ export async function sweepStaleProcessing(activeUserId?: string): Promise<{ swe
if (swept) log.info(`cleared ${swept} stale running conversations`);
return { swept };
}
+
+/** Serialize explicit recycle restoration with ordinary task lifecycle writes. */
+export async function withConversationLifecycleWrite<T>(userId: string, fn: () => Promise<T>): Promise<T> {
+ _invalidateConversationListCache(userId);
+ try { return await _withConversationWrite(userId, fn); }
+ finally { _invalidateConversationListCache(userId); }
+}
diff --git a/src/main/features/conversation_deletions.ts b/src/main/features/conversation_deletions.ts
new file mode 100644
index 00000000..b7f39779
--- /dev/null
+++ b/src/main/features/conversation_deletions.ts
@@ -0,0 +1,32 @@
+/** Exact local task ownership prevents neighboring session-prefix deletion. */
+import { safeId } from '../storage';
+import { isSafeCloudRelPath } from '../util/cloud-path';
+
+export interface TaskIdentity { cid: string; projectId: string | null; }
+export type TaskOwnership = Map<string, TaskIdentity>;
+const key = (pid: string | null, cid: string) => `${pid || ''}/${cid}`;
+
+export function taskForPath(deletions: TaskOwnership, rel: string): TaskIdentity | undefined {
+ if (!isSafeCloudRelPath(rel)) return;
+ const parts = rel.split('/');
+ const pid = parts[1] === 'projects' ? parts[2] : null;
+ const rest = parts.slice(pid ? 3 : 1);
+ const [domain, name] = rest;
+ if (domain === 'chats' || domain === 'chat_attachments' || domain === 'chat_artifacts') {
+ const cid = domain === 'chats' && rest.length === 2 && name?.endsWith('.jsonl') ? name.slice(0, -6) : name;
+ return safeId(cid) ? deletions.get(key(pid, cid)) : undefined;
+ }
+ if (domain !== 'sessions' || !name) return;
+ if (name.startsWith('gconv-')) {
+ const cid = name.slice(6).split('.')[0];
+ if (/^\.(?:jsonl(?:\.context\.json)?|tool-results)$/.test(name.slice(6 + cid.length))) return deletions.get(key(pid, cid));
+ }
+ if (name.startsWith('gmember-')) {
+ const stem = name.slice(8).split('.')[0];
+ if (!/\.(?:jsonl(?:\.context\.json)?|tool-results)$/.test(name)) return;
+ for (let at = stem.lastIndexOf('-'); at > 0; at = stem.lastIndexOf('-', at - 1)) {
+ const match = deletions.get(key(pid, stem.slice(0, at)));
+ if (match) return match;
+ }
+ }
+}
diff --git a/src/main/features/project_tasks.ts b/src/main/features/project_tasks.ts
index 181418f7..a04159e8 100644
--- a/src/main/features/project_tasks.ts
+++ b/src/main/features/project_tasks.ts
@@ -321,7 +321,7 @@ async function _openTasksInScope(
/** Unfinished local to-dos across the global scope and every project. */
export async function listOpenTasks(
uid: string,
- limit: number,
+ limit?: number,
): Promise<{ tasks: OpenTaskRow[]; total: number }> {
const scopes: Array<{ pid: string; name: string }> = [
{ pid: '', name: '' },
@@ -352,7 +352,7 @@ export async function listOpenTasks(
_openTaskFiles.set(uid, keptFiles);
const touched = (task: ProjectTask) => task.updated_at || task.created_at || '';
rows.sort((a, b) => touched(b).localeCompare(touched(a)) || a.id.localeCompare(b.id));
- return { tasks: rows.slice(0, Math.max(0, limit)), total: rows.length };
+ return { tasks: limit === undefined ? rows : rows.slice(0, Math.max(0, limit)), total: rows.length };
}
/** Local snapshot for the initial owner import; never pulls from Server. */
diff --git a/src/main/features/recycle_bin.ts b/src/main/features/recycle_bin.ts
index 046839a7..65625a1c 100644
--- a/src/main/features/recycle_bin.ts
+++ b/src/main/features/recycle_bin.ts
@@ -1,3 +1,4 @@
+import { bumpRecordSyncVersion } from '../util/record_sync_fields';
/**
* Global local recycle bin.
*
@@ -908,10 +909,14 @@ async function buildRecycleDisplayItems(
for (const relPath of paths) {
const editRoot = editConversationRootFromRelPath(relPath);
if (editRoot) editConversationRoots.set(`${editRoot.kind}:${editRoot.id}`, editRoot);
- const cid = chatJsonlCid(relPath);
+ const cid = kind === 'conversation' || kind === 'conversations' ? chatCidFromRelPath(relPath) : chatJsonlCid(relPath);
if (cid) chatRoots.add(cid);
const projectChat = projectChatJsonlInfo(relPath);
if (projectChat) projectChatRoots.set(projectChat.cid, projectChat.pid);
+ else if (cid) {
+ const pid = projectIdFromRelPath(relPath);
+ if (pid) projectChatRoots.set(cid, pid);
+ }
const pid = projectRootDeletedId(relPath);
if (pid) projectRoots.add(pid);
const taskId = autoTaskRootDeletedId(relPath);
@@ -1445,18 +1450,26 @@ async function reactivateChatIndexRows(
relPaths: string[],
restoredAt: Date,
): Promise<string[]> {
- const cidToRelPath = new Map<string, string>();
- for (const relPath of relPaths) {
- const cid = chatJsonlCid(relPath);
- if (cid) cidToRelPath.set(cid, relPath);
- }
- if (cidToRelPath.size === 0) return [];
-
const metadataRows = new Map<string, Record<string, any>>();
for (const row of batch.metadata?.chat_index_rows || []) {
const cid = typeof row.conversation_id === 'string' ? row.conversation_id : '';
if (safeId(cid)) metadataRows.set(cid, row);
}
+ const transcripts = new Set(batch.items.map(item => chatJsonlCid(item.path)).filter(Boolean));
+ const cidToRelPath = new Map<string, string>();
+ for (const relPath of relPaths) {
+ const transcriptCid = chatJsonlCid(relPath);
+ if (transcriptCid) cidToRelPath.set(transcriptCid, relPath);
+ else if (relPath.endsWith('/meta.json')) {
+ const cid = chatCidFromRelPath(relPath);
+ const pid = projectIdFromRelPath(relPath);
+ const taskMeta = pid ? `cloud/projects/${pid}/chats/${cid}/meta.json` : `cloud/chats/${cid}/meta.json`;
+ // An unsent task has no transcript to restore. Its restored metadata is
+ // sufficient, but must not hide a failed transcript in a nonempty task.
+ if (cid && relPath === taskMeta && metadataRows.has(cid) && !transcripts.has(cid)) cidToRelPath.set(cid, relPath);
+ }
+ }
+ if (cidToRelPath.size === 0) return [];
const legacyProjectIds = new Set<string>();
for (const item of batch.items) {
const pid = projectIdFromRelPath(item.path);
@@ -1468,9 +1481,9 @@ async function reactivateChatIndexRows(
const restoredIso = restoredAt.toISOString();
const buckets = new Map<string, { rows: any[]; rowsByCid: Map<string, any>; changed: boolean }>();
const bucketFor = async (relPath: string) => {
- const projectChat = projectChatJsonlInfo(relPath);
- const indexFile = projectChat
- ? await resolveCloudRelPath(userCloudRoot(uid), `cloud/projects/${projectChat.pid}/chats/_index.json`)
+ const pid = projectIdFromRelPath(relPath);
+ const indexFile = pid
+ ? await resolveCloudRelPath(userCloudRoot(uid), `cloud/projects/${pid}/chats/_index.json`)
: await resolveCloudRelPath(userCloudRoot(uid), 'cloud/chats/_index.json');
const existing = buckets.get(indexFile);
if (existing) return existing;
@@ -1493,14 +1506,14 @@ async function reactivateChatIndexRows(
};
for (const [cid, relPath] of cidToRelPath) {
- const projectChat = projectChatJsonlInfo(relPath);
+ const pid = projectIdFromRelPath(relPath);
const bucket = await bucketFor(relPath);
const row = bucket.rowsByCid.get(cid);
const metadataRow = metadataRows.get(cid);
if (!row && !metadataRow) {
const restoredRow = await deriveChatIndexRowFromArchive(uid, batch.id, cid, relPath, restoredIso);
if (!restoredRow) continue;
- if (projectChat && !restoredRow.project_id) restoredRow.project_id = projectChat.pid;
+ if (pid && !restoredRow.project_id) restoredRow.project_id = pid;
bucket.rows.unshift(restoredRow);
bucket.rowsByCid.set(cid, restoredRow);
reactivated.add(relPath);
@@ -1510,7 +1523,7 @@ async function reactivateChatIndexRows(
if (!row) {
const restoredRow: Record<string, any> = { ...metadataRow, conversation_id: cid };
- if (projectChat && !restoredRow.project_id) restoredRow.project_id = projectChat.pid;
+ if (pid && !restoredRow.project_id) restoredRow.project_id = pid;
delete restoredRow.deleted_at;
bucket.rows.unshift(restoredRow);
bucket.rowsByCid.set(cid, restoredRow);
@@ -1526,13 +1539,15 @@ async function reactivateChatIndexRows(
if (!rowDeleted && !canRepairMetadataProject && !canRepairLegacyProject) continue;
if (rowDeleted && metadataRow) {
+ const revision = Math.max(Number(row._sync_rev) || 0, Number(metadataRow._sync_rev) || 0);
Object.assign(row, metadataRow);
+ row._sync_rev = revision;
} else if (canRepairMetadataProject) {
row.project_id = metadataProjectId;
} else if (canRepairLegacyProject) {
row.project_id = legacyProjectId;
}
- if (projectChat && !row.project_id) row.project_id = projectChat.pid;
+ if (pid && !row.project_id) row.project_id = pid;
delete row.deleted_at;
if (rowDeleted && !metadataRow) row.updated_at = restoredIso;
reactivated.add(relPath);
@@ -1541,6 +1556,11 @@ async function reactivateChatIndexRows(
for (const [indexFile, bucket] of buckets) {
if (!bucket.changed) continue;
+ for (const row of bucket.rows) {
+ if (!row.deleted_at && cidToRelPath.has(row.conversation_id)) {
+ bumpRecordSyncVersion(row, row._sync_device_id || '');
+ }
+ }
await writeJson(indexFile, bucket.rows);
}
return Array.from(reactivated);
@@ -1794,6 +1814,17 @@ export async function createAppRecycleBatch(
const files = await collectCloudEntryFiles(uid, relPath);
if (files.length) {
for (const f of files) expanded.add(f);
+ } else if ((opts.kind === 'conversation' || opts.kind === 'conversations') && chatJsonlCid(relPath)) {
+ // Unsent conversations can have metadata/drafts without a transcript.
+ // Freeze existing related files; any later disappearance still fails the
+ // strict archive instead of weakening backup-before-delete protection.
+ const relatedPaths = await expandRecycleRelPaths(uid, [relPath]);
+ // Without the task metadata file, attachments alone cannot reactivate
+ // this conversation on restore. Keep the missing primary path strict.
+ if (!relatedPaths.includes(relPath.slice(0, -'.jsonl'.length) + '/meta.json')) expanded.add(relPath);
+ for (const related of relatedPaths) {
+ if (related !== relPath) expanded.add(related);
+ }
} else {
expanded.add(relPath);
}
@@ -2073,7 +2104,10 @@ export async function deleteRecycleBatch(uid: string, batchId: string): Promise<
}
export function restoreRecycleBatch(uid: string, batchId: string) {
- return withEditSnapshotRetention(uid, () => restoreBatch(uid, batchId));
+ return withEditSnapshotRetention(uid, async () => {
+ const chats = await import('./chats');
+ return chats.withConversationLifecycleWrite(uid, () => restoreBatch(uid, batchId));
+ });
}
async function restoreBatch(
diff --git a/src/main/features/task_cleanup.ts b/src/main/features/task_cleanup.ts
index 09a7d96e..2e05a92d 100644
--- a/src/main/features/task_cleanup.ts
+++ b/src/main/features/task_cleanup.ts
@@ -1,133 +1,237 @@
/** Settings-only history maintenance. No model or application-SDK authority.
- * Preview reads index metadata once and only inspects old, unprotected tasks.
- * Receipts freeze membership; each deletion revalidates after its backup.
- * Recycle data stays local and uses the existing task storage category.
+ * Metadata receipts freeze membership; deletion revalidates activity and
+ * attachment revisions after backup. Recycle data retains task ownership.
*/
import { randomUUID } from 'node:crypto';
import * as path from 'node:path';
import * as fs from 'node:fs/promises';
import * as chats from './chats';
import * as recycle from './recycle_bin';
-import { isQuiescent } from './group_chat/bus';
+import { getProject } from './projects';
+import { abort, isQuiescent } from './group_chat/bus';
import { hasPendingAttachmentsForCleanup } from './chat_attachments';
-import { conversationLayout } from '../util/project-layout';
+import { conversationLayout, conversationMessageReadFile, chatAttachmentDirForConversation } from '../util/project-layout';
+import { indexedJsonlStamp } from '../util/indexed-jsonl';
import { safeId } from '../storage';
const PAGE_SIZE = 20;
const TTL = 30 * 60 * 1000;
-interface Row { cid: string; title: string; activeAt: string; projectId: string | null; }
+interface Row {
+ cid: string; title: string; activeAt: string; projectId: string | null;
+ selectable: boolean; blocked?: 'busy' | 'unknown'; pinned: boolean; automation: boolean; draft: boolean;
+}
+interface ProjectRow {
+ type: 'project'; projectId: string; title: string; total: number; selectableTotal: number;
+}
interface Snapshot {
- token: string; expires: number; cutoff: number; rows: Row[];
- members: Map<string, string | null>; remaining: Set<string>; busy: boolean;
+ token: string; expires: number; cutoff: number; rows: Row[]; entries: (Row | ProjectRow)[];
+ projects: Map<string, Row[]>; selectableTotal: number;
+ members: Map<string, Row>; remaining: Set<string>; busy: boolean;
+ stopped: Map<string, { cutoff: number; revision: string }>;
}
const snapshots = new Map<string, Snapshot>();
const previewing = new Set<string>();
+// Match the sidebar activity clock; metadata edits intentionally count.
function activity(c: chats.Conversation) { return Math.max(Date.parse(c.updated_at), Date.parse(c.created_at)); }
function eligible(c: chats.Conversation | null, cutoff: number): boolean {
- return !!c && c.kind === 'normal' && (!c.project_id || safeId(c.project_id)) && !c.origin_auto_task_id
- && !c.deleted_at && !c.pinned_at && safeId(c.conversation_id)
- && Number.isFinite(activity(c)) && activity(c) < cutoff;
-}
-function quiescent(uid: string, cid: string): boolean {
- return isQuiescent(uid, cid);
+ return !!c && c.kind === 'normal' && (!c.project_id || safeId(c.project_id))
+ && !c.deleted_at && safeId(c.conversation_id) && Number.isFinite(activity(c)) && activity(c) < cutoff;
}
async function smallJson(filePath: string): Promise<any> {
- const file = await fs.open(filePath, 'r');
+ let file;
+ try { file = await fs.open(filePath, 'r'); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; throw error; }
try {
const size = (await file.stat()).size;
if (size > 2 * 1024 * 1024) return null;
const buffer = Buffer.alloc(size + 1);
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
return bytesRead === size ? JSON.parse(buffer.subarray(0, size).toString('utf8')) : null;
- } finally { await file.close(); }
+ } catch (error) { if (error instanceof SyntaxError) return null; throw error; }
+ finally { await file.close(); }
}
-async function completed(uid: string, cid: string, projectId: string | null, cutoff: number): Promise<boolean> {
- if (!quiescent(uid, cid)) return false;
+async function inspect(uid: string, c: chats.Conversation, cutoff: number): Promise<Row | null> {
+ const cid = c.conversation_id;
+ const projectId = c.project_id || null;
const layout = conversationLayout(uid, cid, projectId);
- if (layout.projectId !== projectId) return false;
- try {
- // Missing/corrupt records are unknown, never proof of completion. Do not
- // load the board runtime: that reader reconciles stale queued executions.
- const [state, tasks] = await Promise.all([
- smallJson(layout.stateFile),
- smallJson(path.join(path.dirname(layout.stateFile), 'tasks.json')),
- ]);
- if (state?.status !== 'idle' || !Array.isArray(state.in_flight) || state.in_flight.length
- || state.orchestration_ledger || !Array.isArray(tasks) || !tasks.length) return false;
- if (!Number.isFinite(Date.parse(state.last_active_at)) || Date.parse(state.last_active_at) >= cutoff) return false;
- if (tasks.some(t => !t || !['done', 'failed', 'stopped', 'cancelled'].includes(t.status))) return false;
- const roots = tasks.filter(t => t.created_by === 'user' && !t.parent_task_id && !t.absorbed_into_task_id);
- if (!roots.length || roots.some(t => !Number.isFinite(Date.parse(t.created_at)))) return false;
- const latest = roots.reduce((a, b) => Date.parse(a.created_at) >= Date.parse(b.created_at) ? a : b);
- const peers = roots.filter(t => t === latest || (latest.source_msg_id && t.source_msg_id === latest.source_msg_id));
- return peers.every(t => t.status === 'done' && Number.isFinite(Date.parse(t.ended_at)) && Date.parse(t.ended_at) < cutoff)
- && !await hasPendingAttachmentsForCleanup(uid, cid) && quiescent(uid, cid);
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ENOENT' || error instanceof SyntaxError) return false;
- throw new Error('cleanup_read_failed');
+ if (layout.projectId !== projectId) return null;
+ const [state, tasks] = await Promise.all([smallJson(layout.stateFile), smallJson(path.join(layout.groupDir, 'tasks.json'))]);
+ let activeAt = activity(c);
+ let blocked: Row['blocked'];
+ let busy = false;
+ const observeTime = (value: unknown) => {
+ if (value === undefined || value === null || value === '') return;
+ const parsed = typeof value === 'string' ? Date.parse(value) : NaN;
+ if (Number.isFinite(parsed)) activeAt = Math.max(activeAt, parsed); else blocked = 'unknown';
+ };
+ if (state === null || tasks === null || (tasks !== undefined && !Array.isArray(tasks))) blocked = 'unknown';
+ if (state !== undefined && state !== null) {
+ observeTime(state.last_active_at);
+ if (!['idle', 'running', 'aborted'].includes(state.status) || !Array.isArray(state.in_flight)) blocked = 'unknown';
+ else if (state.status === 'running' || state.in_flight.length) busy = true;
+ if (state.orchestration_ledger && !['waiting_for_form', 'interrupted'].includes(state.orchestration_ledger.status)) busy = true;
+ }
+ if (Array.isArray(tasks)) for (const task of tasks) {
+ if (!task || !['done', 'failed', 'stopped', 'cancelled', 'waiting_input', 'blocked', 'queued', 'running'].includes(task.status)) { blocked = 'unknown'; continue; }
+ for (const key of ['created_at', 'updated_at', 'started_at', 'ended_at']) observeTime(task[key]);
+ if (task.status === 'queued' || task.status === 'running') busy = true;
+ }
+ if (activeAt >= cutoff) return null;
+ if (!blocked && (busy || !isQuiescent(uid, cid))) blocked = 'busy';
+ return { cid, projectId, title: c.title.slice(0, 512), activeAt: new Date(activity(c)).toISOString(),
+ selectable: blocked !== 'unknown', ...(blocked ? { blocked } : {}), pinned: !!c.pinned_at,
+ automation: !!c.origin_auto_task_id, draft: await hasPendingAttachmentsForCleanup(uid, cid) };
+}
+async function executionRevision(uid: string, cid: string, projectId: string | null): Promise<string> {
+ const layout = conversationLayout(uid, cid, projectId);
+ return JSON.stringify(await Promise.all([layout.stateFile, path.join(layout.groupDir, 'tasks.json')].map(async file => {
+ try {
+ const stat = await fs.stat(file);
+ return [stat.size, stat.mtimeMs, stat.ctimeMs];
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+ })));
+}
+// Compare bounded file metadata, not attachment contents. Existing draft files
+// are allowed; a file added or edited while backing up invalidates this delete.
+async function attachmentRevision(uid: string, cid: string): Promise<string> {
+ const dir = chatAttachmentDirForConversation(uid, cid);
+ let root;
+ try { root = await fs.lstat(dir); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return '[]'; throw error; }
+ if (!root.isDirectory()) throw new Error('cleanup_attachment_unknown');
+ const stamps: unknown[] = [['', root.size, root.mtimeMs, root.ctimeMs]];
+ const directories = [''];
+ let count = 0;
+ for (let cursor = 0; cursor < directories.length; cursor++) {
+ const parent = directories[cursor];
+ const names = (await fs.readdir(path.join(dir, parent))).sort();
+ count += names.length;
+ if (count > 10000) throw new Error('cleanup_attachment_limit');
+ for (let i = 0; i < names.length; i += 8) {
+ const children = await Promise.all(names.slice(i, i + 8).map(async name => {
+ const relative = path.join(parent, name);
+ const stat = await fs.lstat(path.join(dir, relative));
+ if (!stat.isFile() && !stat.isDirectory()) throw new Error('cleanup_attachment_unknown');
+ return { relative, stat };
+ }));
+ for (const { relative, stat } of children) {
+ stamps.push([relative, stat.size, stat.mtimeMs, stat.ctimeMs]);
+ if (stat.isDirectory()) directories.push(relative);
+ }
+ }
}
+ return JSON.stringify(stamps);
}
function snapshot(uid: string, token: string): Snapshot {
const s = snapshots.get(uid);
if (!s || s.token !== token || s.expires < Date.now()) throw new Error('cleanup_preview_expired');
return s;
}
-export async function preview(uid: string, args: { days: number; protectedIds: string[] }) {
- if (![30, 90, 180].includes(args.days) || !Array.isArray(args.protectedIds)
- || args.protectedIds.length > 50000 || args.protectedIds.some(id => typeof id !== 'string' || !safeId(id))) {
- throw new Error('invalid_cleanup_filter');
+export async function preview(uid: string, args: { days: number; protectedIds?: string[]; draftIds?: string[] }) {
+ // Accept the old input field for in-process compatibility, but annotations
+ // no longer exclude explicitly selectable history.
+ for (const ids of [args.protectedIds, args.draftIds]) {
+ if (ids !== undefined && (!Array.isArray(ids) || ids.length > 50000 || ids.some(id => typeof id !== 'string' || !safeId(id)))) throw new Error('invalid_cleanup_filter');
}
+ if (![7, 14, 30, 60, 90, 180].includes(args.days)) throw new Error('invalid_cleanup_filter');
if (previewing.has(uid) || snapshots.get(uid)?.busy) throw new Error('cleanup_busy');
previewing.add(uid);
try {
for (const [owner, s] of snapshots) if (!s.busy && s.expires < Date.now()) snapshots.delete(owner);
const cutoff = Date.now() - args.days * 86400000;
- const protectedIds = new Set(args.protectedIds);
+ const draftIds = new Set(args.draftIds || []);
const rows: Row[] = [];
- const candidates = (await chats.listCleanupConversationRows(uid))
- .filter(c => eligible(c, cutoff) && !protectedIds.has(c.conversation_id));
- // Four bounded readers, no history hydration or per-row IPC. Fail instead
- // of silently truncating an exceptionally large account's preview.
+ const candidates = (await chats.listCleanupConversationRows(uid)).filter(c => eligible(c, cutoff));
if (candidates.length > 50000) throw new Error('cleanup_preview_too_large');
for (let i = 0; i < candidates.length; i += 4) {
await Promise.all(candidates.slice(i, i + 4).map(async c => {
- if (await completed(uid, c.conversation_id, c.project_id || null, cutoff)) rows.push({ cid: c.conversation_id, projectId: c.project_id || null,
- title: c.title.slice(0, 512), activeAt: new Date(activity(c)).toISOString() });
+ const row = await inspect(uid, c, cutoff);
+ if (row) { row.draft ||= draftIds.has(row.cid); rows.push(row); }
}));
}
rows.sort((a, b) => a.activeAt.localeCompare(b.activeAt) || a.cid.localeCompare(b.cid));
- const s: Snapshot = { token: randomUUID(), expires: Date.now() + TTL, cutoff, rows,
- members: new Map(rows.map(r => [r.cid, r.projectId])), remaining: new Set(rows.map(r => r.cid)), busy: false };
+ const projects = new Map<string, Row[]>();
+ for (const row of rows) if (row.projectId) {
+ if (!projects.has(row.projectId)) projects.set(row.projectId, []);
+ projects.get(row.projectId)!.push(row);
+ }
+ const projectRows: ProjectRow[] = [];
+ const ids = [...projects.keys()];
+ for (let i = 0; i < ids.length; i += 4) await Promise.all(ids.slice(i, i + 4).map(async projectId => {
+ const project = await getProject(uid, projectId);
+ const children = projects.get(projectId)!;
+ projectRows.push({ type: 'project', projectId, title: project?.name || projectId,
+ total: children.length, selectableTotal: children.filter(row => row.selectable).length });
+ }));
+ projectRows.sort((a, b) => a.title.localeCompare(b.title, undefined, { numeric: true }) || a.projectId.localeCompare(b.projectId));
+ const entries = [...projectRows, ...rows.filter(row => !row.projectId)];
+ const s: Snapshot = { token: randomUUID(), expires: Date.now() + TTL, cutoff, rows, entries, projects,
+ selectableTotal: rows.filter(row => row.selectable).length,
+ members: new Map(rows.map(row => [row.cid, row])), remaining: new Set(rows.map(row => row.cid)), busy: false, stopped: new Map() };
snapshots.set(uid, s);
- return { token: s.token, ...page(uid, s.token, 0) };
+ return { token: s.token, ...page(uid, s.token, 0), entries: entries.slice(0, PAGE_SIZE),
+ treeTotal: entries.length, treeNextOffset: entries.length > PAGE_SIZE ? PAGE_SIZE : null };
} finally { previewing.delete(uid); }
}
-export function page(uid: string, token: string, offset: number) {
+export function page(uid: string, token: string, offset: number, scope: { tree?: boolean; projectId?: string } = {}) {
const s = snapshot(uid, token);
- if (!Number.isSafeInteger(offset) || offset < 0 || offset > s.rows.length) throw new Error('invalid_cleanup_page');
- const rows = s.rows.slice(offset, offset + PAGE_SIZE);
- return { total: s.rows.length, rows, nextOffset: offset + rows.length < s.rows.length ? offset + rows.length : null };
+ if (scope.tree !== undefined && typeof scope.tree !== 'boolean') throw new Error('invalid_cleanup_page');
+ if (scope.projectId !== undefined && (!safeId(scope.projectId) || !s.projects.has(scope.projectId) || scope.tree)) throw new Error('invalid_cleanup_page');
+ const source = scope.tree ? s.entries : scope.projectId ? s.projects.get(scope.projectId)! : s.rows;
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > source.length) throw new Error('invalid_cleanup_page');
+ const portion = source.slice(offset, offset + PAGE_SIZE);
+ return { total: s.rows.length, selectableTotal: s.selectableTotal, listTotal: source.length,
+ rows: scope.tree ? [] : portion as Row[], entries: scope.tree ? portion : [],
+ offset, nextOffset: offset + portion.length < source.length ? offset + portion.length : null };
}
export async function remove(uid: string, token: string, cid: string) {
const s = snapshot(uid, token);
if (s.busy) throw new Error('cleanup_busy');
- if (!s.members.has(cid)) throw new Error('invalid_cleanup_selection');
- const projectId = s.members.get(cid)!;
- if (!s.remaining.has(cid)) return { status: 'skipped' as const };
+ const original = s.members.get(cid);
+ if (!original) throw new Error('invalid_cleanup_selection');
+ if (!original.selectable || !s.remaining.has(cid)) return { status: 'skipped' as const };
+ const projectId = original.projectId;
s.busy = true;
try {
- const current = await chats.getConversationMetadata(uid, cid, projectId);
- if (!eligible(current, s.cutoff) || (current!.project_id || null) !== projectId
- || !await completed(uid, cid, projectId, s.cutoff)) {
+ let cutoff = s.stopped.get(cid)?.cutoff ?? s.cutoff;
+ let current = await chats.getConversationMetadata(uid, cid, projectId);
+ const row = eligible(current, cutoff) && (current!.project_id || null) === projectId
+ ? await inspect(uid, current!, cutoff) : null;
+ if (!row?.selectable) {
s.remaining.delete(cid); return { status: 'skipped' as const };
}
+ if (row.blocked === 'busy' && !s.stopped.has(cid)) {
+ await abort(uid, cid);
+ if (!isQuiescent(uid, cid)) throw new Error('cleanup_stop_failed');
+ // Stop writes current activity timestamps. Keep that boundary for backup
+ // retries, but never accept later execution writes or another live run.
+ cutoff = Date.now() + 1;
+ s.stopped.set(cid, { cutoff, revision: await executionRevision(uid, cid, projectId) });
+ }
+ const canDelete = async (candidate: chats.Conversation | null) => {
+ if (!eligible(candidate, cutoff) || (candidate!.project_id || null) !== projectId || !isQuiescent(uid, cid)) return false;
+ const checked = await inspect(uid, candidate!, cutoff);
+ if (!checked?.selectable) return false;
+ const stopped = s.stopped.get(cid);
+ // An old queued/running disk record can outlive its process. Only the
+ // explicit, completed Stop above permits deleting that unchanged record.
+ return stopped ? stopped.revision === await executionRevision(uid, cid, projectId) : !checked.blocked;
+ };
+ current = await chats.getConversationMetadata(uid, cid, projectId);
+ if (!await canDelete(current)) { s.remaining.delete(cid); return { status: 'skipped' as const }; }
+ const metadataTime = current!.updated_at;
+ const historyFile = conversationMessageReadFile(uid, cid, projectId);
+ const historyRevision = await indexedJsonlStamp(historyFile);
+ const revision = await attachmentRevision(uid, cid);
const batch = await recycle.createAppRecycleBatchForConversation(uid, cid);
if (!batch?.items?.length) throw new Error('recycle_archive_failed');
- // Re-read the owning index under its write queue, after potentially slow
- // backup I/O, so a pin, project move, or new message invalidates selection.
- const removed = await chats.deleteConversation(uid, cid, projectId,
- async current => eligible(current, s.cutoff) && (current.project_id || null) === projectId
- && await completed(uid, cid, projectId, s.cutoff));
+ const removed = await chats.deleteConversation(uid, cid, projectId, async current =>
+ current.updated_at === metadataTime && await canDelete(current)
+ && historyRevision === await indexedJsonlStamp(historyFile)
+ && revision === await attachmentRevision(uid, cid) && isQuiescent(uid, cid));
s.remaining.delete(cid);
if (!removed) await recycle.deleteRecycleBatch(uid, batch.id);
s.expires = Date.now() + TTL;
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 52c28e7d..fa7d450b 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -1226,7 +1226,7 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
'conversations.cleanup.page': async (args, ctx) => {
if (args.expectedUserId !== ctx.userId) throw new Error('cleanup_account_changed');
- return taskCleanup.page(ctx.userId, args.token, args.offset);
+ return taskCleanup.page(ctx.userId, args.token, args.offset, { tree: args.tree, projectId: args.projectId });
},
'conversations.cleanup.remove': async (args, ctx) => {
if (args.expectedUserId !== ctx.userId) throw new Error('cleanup_account_changed');
@@ -1434,11 +1434,10 @@ const invokeHandlers: Record<string, InvokeHandler> = {
};
},
- // Home page: the most recently updated unfinished to-dos across every scope,
- // plus the total so the page can link to the full list.
- 'projects.tasks.listOpen': async ({ limit } = {}, ctx) => {
+ // Home page: all unfinished to-dos for expansion, or a bounded preview.
+ 'projects.tasks.listOpen': async ({ limit, all } = {}, ctx) => {
const count = Math.min(20, Math.max(1, Math.round(Number(limit) || 3)));
- return projectTasks.listOpenTasks(ctx.userId, count);
+ return projectTasks.listOpenTasks(ctx.userId, all === true ? undefined : count);
},
'projects.tasks.create': async ({ projectId, taskId, content, title, detail, status, owner_agent, owner_agent_id, depends_on } = {}, ctx) => {
diff --git a/src/main/util/cloud-path.ts b/src/main/util/cloud-path.ts
new file mode 100644
index 00000000..c5e20e46
--- /dev/null
+++ b/src/main/util/cloud-path.ts
@@ -0,0 +1,52 @@
+import * as path from 'path';
+import { isPathAllowed, resolveSandboxRoot } from './path-sandbox';
+
+const MAX_CLOUD_REL_PATH = 1024;
+
+export function isSafeCloudRelPath(relPath: unknown): relPath is string {
+ if (typeof relPath !== 'string' || !relPath) return false;
+ if (relPath.length > MAX_CLOUD_REL_PATH) return false;
+ if (!relPath.startsWith('cloud/')) return false;
+ if (relPath.includes('\\') || relPath.includes('\0')) return false;
+ const parts = relPath.split('/');
+ if (parts.length < 2) return false;
+ for (const part of parts) {
+ if (!part || part === '.' || part === '..') return false;
+ if (/^[A-Za-z]:/.test(part)) return false;
+ }
+ return true;
+}
+
+export function assertSafeCloudRelPath(relPath: string): string {
+ if (!isSafeCloudRelPath(relPath)) {
+ throw new Error(`unsafe cloud sync path: ${relPath}`);
+ }
+ return relPath;
+}
+
+/** Realpath a user cloud root once for a pass; see `resolveCloudRelPath`. */
+export function resolveCloudRoot(root: string): string {
+ return resolveSandboxRoot(path.resolve(root));
+}
+
+/**
+ * Absolute on-disk path for a manifest rel_path, or a throw when the path
+ * would leave `root` lexically or through a symlink. `resolvedRoot` is the
+ * `resolveCloudRoot(root)` result; a pass that maps many paths supplies it so
+ * the root's realpath walk is not repeated for every file. The candidate is
+ * always resolved.
+ */
+export function resolveCloudRelPath(root: string, relPath: string, resolvedRoot?: string): string {
+ assertSafeCloudRelPath(relPath);
+ const base = path.resolve(root);
+ const child = relPath.slice('cloud/'.length).split('/').join(path.sep);
+ const abs = path.resolve(base, child);
+ const rel = path.relative(base, abs);
+ const contained = resolvedRoot
+ ? isPathAllowed(abs, [resolvedRoot], { rootsResolved: true })
+ : isPathAllowed(abs, [base]);
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel) || !contained) {
+ throw new Error(`unsafe cloud sync path: ${relPath}`);
+ }
+ return abs;
+}
diff --git a/src/renderer/index.html b/src/renderer/index.html
index fd9b5ac2..bb673693 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -163,11 +163,6 @@
<div class="quick-panel-head">
<span class="quick-panel-title" id="quick-panel-title" data-i18n="new_chat.quick.title">Try one of these tasks — one click to get started</span>
<span class="quick-panel-rule" aria-hidden="true"></span>
- <!-- Opens the marketplace「开源项目」list (wired by modules/oss.js). -->
- <button type="button" class="quick-panel-more" id="quick-panel-oss-more">
- <span data-i18n="new_chat.quick.oss_more">Add more open-source tool capabilities</span>
- <span data-ui-icon="chevron-right" data-ui-icon-class="quick-panel-more-arrow" aria-hidden="true"></span>
- </button>
</div>
<div class="quick-grid" id="new-chat-scenario-grid"></div>
</section>
@@ -192,6 +187,7 @@
avatars + counts + 详情 toggle. Filled in by JS lifecycle hook
`_refreshChatHeader()` in conversation.js. -->
<div class="chat-header" id="chat-header">
+ <button type="button" class="btn btn-sm" id="chat-cleanup-back" data-i18n="common.back" hidden>Back</button>
<div class="chat-header-main">
<div class="chat-header-title-row">
<h1 class="chat-header-title" id="chat-header-title"></h1>
@@ -1169,7 +1165,7 @@
<div class="settings-row">
<div class="settings-row-copy">
<div class="settings-row-title" data-i18n="settings.cleanup.age">Last active</div>
- <div class="settings-row-desc" data-i18n="settings.cleanup.scope">Completed tasks inside and outside projects. Pinned and unread tasks, drafts, and automation runs are kept.</div>
+ <div class="settings-row-desc" data-i18n="settings.cleanup.scope">Filter all task history by age, then clean up by project or task.</div>
</div>
<div class="ai-select" id="settings-task-cleanup-age"></div>
</div>
diff --git a/src/renderer/locales/ar.json b/src/renderer/locales/ar.json
index cbc6b552..b1495fc4 100644
--- a/src/renderer/locales/ar.json
+++ b/src/renderer/locales/ar.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "التعلّم",
"new_chat.quick.ecommerce": "التجارة الإلكترونية",
"new_chat.quick.title": "جرّب إحدى هذه المهام — ابدأ بنقرة واحدة",
- "new_chat.quick.oss_more": "ربط أدوات مفتوحة المصدر",
"new_chat.quick.subtitle": "اختر مهمة محددة وسينسّق القائد الوكلاء المناسبين",
"new_chat.quick.rnd": "التطوير",
"new_chat.quick.creation": "الكتابة",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "مثلًا: ابحث في 3 منتجات متشابهة، وقارن ميزاتها وأسعارها، ثم لخّص ذلك في عرض تقديمي.",
"new_chat.home.explore_title": "لم تقرر بعد؟ دع Orkas يتعرّف عليك أولًا.",
"new_chat.home.explore_body": "تحدّث عن عملك أو تجارتك أو ما يقلقك، وسيساعدك Orkas على إيجاد الأهداف المناسبة ومواصلة التقدّم فيها.",
- "new_chat.home.explore_context": "شارك الملفات عبر + أو {connect} لتمنح Orkas سياقًا أكبر. ابدأ بما ترتاح لمشاركته.",
- "new_chat.home.explore_connect_link": "اربط Feishu / DingTalk / البريد الإلكتروني",
+ "new_chat.home.explore_context": "أضف مواد أو {connect} ليتعرّف Orkas عليك بشكل أفضل. ابدأ بما ترتاح لمشاركته.",
+ "new_chat.home.explore_connect_link": "اربط البريد الإلكتروني والمتاجر والتطبيقات المكتبية وغيرها",
"new_chat.home.input_placeholder": "صف ما تريد إنجازه، أو أرفق الملفات التي تحتاج إلى معالجة",
"new_chat.home.continue_label": "تابع التقدّم في عملك",
"new_chat.home.group.todos": "مهام مطلوبة مهمة",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "المحادثة الخاصة بهذه المهمة لا تزال قيد المعالجة. شغّلها مرة أخرى بعد انتهائها.",
"settings.cleanup.title": "تنظيف المهام القديمة",
"settings.cleanup.age": "آخر نشاط",
- "settings.cleanup.scope": "المهام المكتملة داخل المشاريع وخارجها. تُحفظ المهام المثبتة وغير المقروءة والمسودات وسجلات الأتمتة.",
+ "settings.cleanup.scope": "صفِّ سجل المهام بالكامل حسب المدة، ثم نظّفه حسب المشروع أو المهمة.",
"settings.cleanup.days": "قبل أكثر من {n} يومًا",
"settings.cleanup.result": "نُقلت إلى السلة: {deleted}. تم تخطيها: {skipped}. فشلت: {failed}.",
"settings.cleanup.progress": "جارٍ التنظيف {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "تم تحديد {n} مهمة",
"settings.cleanup.empty": "لا توجد مهام قديمة للتنظيف.",
"settings.cleanup.clean": "تنظيف",
- "settings.cleanup.confirm": "نقل {n} مهمة ومرفقاتها ونتائجها المضمنة إلى سلة المحذوفات. يمكنك استعادتها أدناه. عند تفعيل المزامنة، يسري الحذف على الأجهزة الأخرى أيضًا. تُحرر مساحة القرص بعد إفراغ السلة.",
+ "settings.cleanup.confirm": "نقل {n} من المهام ومرفقاتها ونتائجها المضمّنة إلى سلة المحذوفات. ستُحذف المسودات غير المرسلة. تتوقف المهام الجارية تلقائيًا قبل التنظيف.",
"settings.cleanup.move": "نقل إلى السلة ({n})",
"settings.cleanup.previous": "السابق",
"settings.cleanup.next": "التالي",
"apps.commercial_required": "تتطلب تطبيقات الويب الإصدار التجاري من Orkas. نزّله للمتابعة.",
"apps.commercial_download": "تنزيل الإصدار التجاري",
- "apps.commercial_open_failed": "تعذّر فتح صفحة التنزيل. يُرجى المحاولة مجددًا."
+ "apps.commercial_open_failed": "تعذّر فتح صفحة التنزيل. يُرجى المحاولة مجددًا.",
+ "settings.cleanup.draft": "مسودة",
+ "settings.cleanup.automation": "أتمتة",
+ "settings.cleanup.pinned": "مثبتة",
+ "settings.cleanup.unavailable": "غير متاح",
+ "settings.cleanup.unread": "غير مقروءة"
}
diff --git a/src/renderer/locales/de.json b/src/renderer/locales/de.json
index b01af32a..62cd8614 100644
--- a/src/renderer/locales/de.json
+++ b/src/renderer/locales/de.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Lernen",
"new_chat.quick.ecommerce": "E-Commerce",
"new_chat.quick.title": "Probieren Sie eine dieser Aufgaben aus – ein Klick genügt",
- "new_chat.quick.oss_more": "Open-Source-Tools verbinden",
"new_chat.quick.subtitle": "Wählen Sie eine konkrete Aufgabe. Commander koordiniert die passenden Agenten",
"new_chat.quick.rnd": "Entwicklung",
"new_chat.quick.creation": "Schreiben",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Zum Beispiel: 3 ähnliche Produkte recherchieren, Funktionen und Preise vergleichen und das Ergebnis als Präsentation aufbereiten.",
"new_chat.home.explore_title": "Noch unsicher? Lassen Sie Orkas Sie zuerst kennenlernen.",
"new_chat.home.explore_body": "Erzählen Sie von Ihrer Arbeit, Ihrem Geschäft oder Ihren Herausforderungen – Orkas hilft Ihnen, die richtigen Ziele zu finden und sie voranzubringen.",
- "new_chat.home.explore_context": "Teilen Sie Dateien über + oder {connect}, damit Orkas mehr Hintergrund hat. Beginnen Sie mit dem, was Sie teilen möchten.",
- "new_chat.home.explore_connect_link": "verbinden Sie Feishu / DingTalk / E-Mail",
+ "new_chat.home.explore_context": "Fügen Sie Materialien hinzu oder {connect}, damit Orkas Sie besser kennenlernt. Beginnen Sie mit dem, was Sie teilen möchten.",
+ "new_chat.home.explore_connect_link": "verbinden Sie E-Mail, Shops, Bürosoftware und mehr",
"new_chat.home.input_placeholder": "Beschreiben Sie, was Sie erreichen möchten, oder hängen Sie die zu bearbeitenden Dateien an",
"new_chat.home.continue_label": "Bringen Sie Ihre Arbeit voran",
"new_chat.home.group.todos": "Wichtig zu erledigen",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "Die Unterhaltung dieser Aufgabe läuft noch. Führe sie erneut aus, sobald sie fertig ist.",
"settings.cleanup.title": "Alte Aufgaben bereinigen",
"settings.cleanup.age": "Zuletzt aktiv",
- "settings.cleanup.scope": "Abgeschlossene Aufgaben innerhalb und außerhalb von Projekten. Angeheftete und ungelesene Aufgaben, Entwürfe und Automatisierungsläufe bleiben erhalten.",
+ "settings.cleanup.scope": "Alle bisherigen Aufgaben nach Alter filtern und nach Projekt oder einzeln bereinigen.",
"settings.cleanup.days": "Vor mehr als {n} Tagen",
"settings.cleanup.result": "Im Papierkorb: {deleted}. Übersprungen: {skipped}. Fehlgeschlagen: {failed}.",
"settings.cleanup.progress": "Bereinigung {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} Aufgaben ausgewählt",
"settings.cleanup.empty": "Keine alten Aufgaben zum Bereinigen.",
"settings.cleanup.clean": "Bereinigen",
- "settings.cleanup.confirm": "{n} Aufgaben mit Anhängen und eingebetteten Ergebnissen in den Papierkorb verschieben. Sie können sie unten wiederherstellen. Bei aktivierter Synchronisierung werden sie auch auf anderen Geräten gelöscht. Speicherplatz wird erst beim Leeren des Papierkorbs frei.",
+ "settings.cleanup.confirm": "{n} Aufgaben samt Anhängen und eingebetteten Ergebnissen in den Papierkorb verschieben. Ungesendete Entwürfe werden gelöscht. Laufende Aufgaben werden vor der Bereinigung automatisch gestoppt.",
"settings.cleanup.move": "In den Papierkorb ({n})",
"settings.cleanup.previous": "Zurück",
"settings.cleanup.next": "Weiter",
"apps.commercial_required": "Web-Apps erfordern die kommerzielle Version von Orkas. Laden Sie sie herunter, um fortzufahren.",
"apps.commercial_download": "Kommerzielle Version herunterladen",
- "apps.commercial_open_failed": "Die Downloadseite konnte nicht geöffnet werden. Bitte versuchen Sie es erneut."
+ "apps.commercial_open_failed": "Die Downloadseite konnte nicht geöffnet werden. Bitte versuchen Sie es erneut.",
+ "settings.cleanup.draft": "Entwurf",
+ "settings.cleanup.automation": "Automation",
+ "settings.cleanup.pinned": "Angeheftet",
+ "settings.cleanup.unavailable": "Nicht verfügbar",
+ "settings.cleanup.unread": "Ungelesen"
}
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index f59b28d9..f328c061 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Learning",
"new_chat.quick.ecommerce": "Ecommerce",
"new_chat.quick.title": "Try one of these tasks — one click to get started",
- "new_chat.quick.oss_more": "Connect open-source tools",
"new_chat.quick.subtitle": "Choose a concrete task and Commander will coordinate the right agents",
"new_chat.quick.rnd": "Development",
"new_chat.quick.creation": "Writing",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "For example: research 3 similar products, compare their features and pricing, and turn the findings into a presentation.",
"new_chat.home.explore_title": "Not sure yet? Let Orkas get to know you first.",
"new_chat.home.explore_body": "Talk about your work, your business, or what's on your mind, and Orkas will help you find the right goals and keep them moving.",
- "new_chat.home.explore_context": "Share files with +, or {connect}, to give Orkas more background. Start with whatever you're comfortable sharing.",
- "new_chat.home.explore_connect_link": "connect Feishu / DingTalk / email",
+ "new_chat.home.explore_context": "Add materials or {connect} to help Orkas get to know you better. Start with whatever you're comfortable sharing.",
+ "new_chat.home.explore_connect_link": "connect email, stores, office apps, and more",
"new_chat.home.input_placeholder": "Describe what you want to accomplish, or attach the files to work on",
"new_chat.home.continue_label": "Keep things moving",
"new_chat.home.group.todos": "Important to-dos",
@@ -2624,19 +2623,24 @@
"project.todo.run_busy": "This to-do's conversation is still working. Run it again once it finishes.",
"settings.cleanup.title": "Clean up task history",
"settings.cleanup.age": "Last active",
- "settings.cleanup.scope": "Completed tasks inside and outside projects. Pinned and unread tasks, drafts, and automation runs are kept.",
+ "settings.cleanup.scope": "Filter all task history by age, then clean up by project or task.",
"settings.cleanup.days": "Over {n} days ago",
- "settings.cleanup.result": "Moved to recycle bin: {deleted}. Skipped: {skipped}. Failed: {failed}.",
+ "settings.cleanup.result": "Recycled {deleted} · Skipped {skipped} · Failed {failed}",
"settings.cleanup.progress": "Cleaning {done} / {total}",
- "settings.cleanup.error": "Could not finish loading or cleaning tasks. Refresh and try again.",
+ "settings.cleanup.error": "Could not finish. Refresh to retry.",
"settings.cleanup.count": "Selected tasks: {n}",
- "settings.cleanup.empty": "No historical tasks to clean up.",
+ "settings.cleanup.empty": "No tasks to clean up",
"settings.cleanup.clean": "Clean up",
- "settings.cleanup.confirm": "Move the selected tasks ({n}), their attachments and embedded results to the recycle bin. You can restore them below. With sync enabled, deletion also applies to other devices. Disk space is not freed until the recycle bin is emptied.",
+ "settings.cleanup.confirm": "{n} tasks and files go to the recycle bin; drafts are deleted. Running tasks are stopped automatically before cleanup.",
"settings.cleanup.move": "Move to recycle bin ({n})",
"settings.cleanup.previous": "Previous",
"settings.cleanup.next": "Next",
"apps.commercial_required": "Web apps require the commercial version of Orkas. Download it to continue.",
"apps.commercial_download": "Download commercial version",
- "apps.commercial_open_failed": "Could not open the download page. Please try again."
+ "apps.commercial_open_failed": "Could not open the download page. Please try again.",
+ "settings.cleanup.draft": "Draft",
+ "settings.cleanup.automation": "Automation",
+ "settings.cleanup.pinned": "Pinned",
+ "settings.cleanup.unavailable": "Unavailable",
+ "settings.cleanup.unread": "Unread"
}
diff --git a/src/renderer/locales/es-419.json b/src/renderer/locales/es-419.json
index a1f0927f..c4822751 100644
--- a/src/renderer/locales/es-419.json
+++ b/src/renderer/locales/es-419.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Aprendizaje",
"new_chat.quick.ecommerce": "Comercio electrónico",
"new_chat.quick.title": "Prueba una de estas tareas: un clic para empezar",
- "new_chat.quick.oss_more": "Conectar herramientas de código abierto",
"new_chat.quick.subtitle": "Elige una tarea concreta y Commander coordinará a los agentes adecuados",
"new_chat.quick.rnd": "Desarrollo",
"new_chat.quick.creation": "Redacción",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Por ejemplo: investiga 3 productos similares, compara sus funciones y precios y resúmelo en una presentación.",
"new_chat.home.explore_title": "¿Todavía no lo tienes claro? Deja que Orkas te conozca primero.",
"new_chat.home.explore_body": "Habla de tu trabajo, tu negocio o tus dificultades, y Orkas te ayudará a encontrar los objetivos adecuados y a avanzar en ellos.",
- "new_chat.home.explore_context": "Comparte archivos con + o {connect} para darle más contexto a Orkas. Empieza por lo que te sientas cómodo compartiendo.",
- "new_chat.home.explore_connect_link": "conecta Feishu / DingTalk / tu correo",
+ "new_chat.home.explore_context": "Agrega materiales o {connect} para que Orkas te conozca mejor. Empieza por lo que te sientas cómodo compartiendo.",
+ "new_chat.home.explore_connect_link": "conecta tu correo, tiendas, aplicaciones de oficina y más",
"new_chat.home.input_placeholder": "Describe lo que quieres conseguir o adjunta los archivos que hay que procesar",
"new_chat.home.continue_label": "Sigue avanzando",
"new_chat.home.group.todos": "Pendientes importantes",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "La conversación de esta tarea todavía está en curso. Vuelve a ejecutarla cuando termine.",
"settings.cleanup.title": "Limpiar tareas antiguas",
"settings.cleanup.age": "Última actividad",
- "settings.cleanup.scope": "Tareas completadas dentro y fuera de proyectos. Se conservan las fijadas, no leídas, los borradores y las ejecuciones automatizadas.",
+ "settings.cleanup.scope": "Filtra todo el historial por antigüedad y limpia por proyecto o tarea.",
"settings.cleanup.days": "Hace más de {n} días",
"settings.cleanup.result": "En la papelera: {deleted}. Omitidas: {skipped}. Fallidas: {failed}.",
"settings.cleanup.progress": "Limpiando {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} tareas seleccionadas",
"settings.cleanup.empty": "No hay tareas antiguas para limpiar.",
"settings.cleanup.clean": "Limpiar",
- "settings.cleanup.confirm": "Mover {n} tareas, sus adjuntos y resultados integrados a la papelera. Puedes restaurarlas abajo. Con la sincronización activa, también se eliminan de otros dispositivos. El espacio se libera al vaciar la papelera.",
+ "settings.cleanup.confirm": "Mover {n} tareas, sus adjuntos y resultados integrados a la papelera. Se eliminarán los borradores sin enviar. Las tareas en ejecución se detienen automáticamente antes de la limpieza.",
"settings.cleanup.move": "Mover a la papelera ({n})",
"settings.cleanup.previous": "Anterior",
"settings.cleanup.next": "Siguiente",
"apps.commercial_required": "Las aplicaciones web requieren la versión comercial de Orkas. Descárgala para continuar.",
"apps.commercial_download": "Descargar versión comercial",
- "apps.commercial_open_failed": "No se pudo abrir la página de descarga. Inténtalo de nuevo."
+ "apps.commercial_open_failed": "No se pudo abrir la página de descarga. Inténtalo de nuevo.",
+ "settings.cleanup.draft": "Borrador",
+ "settings.cleanup.automation": "Automatización",
+ "settings.cleanup.pinned": "Fijada",
+ "settings.cleanup.unavailable": "No disponible",
+ "settings.cleanup.unread": "Sin leer"
}
diff --git a/src/renderer/locales/es.json b/src/renderer/locales/es.json
index 30b499b8..341891b1 100644
--- a/src/renderer/locales/es.json
+++ b/src/renderer/locales/es.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Aprendizaje",
"new_chat.quick.ecommerce": "Comercio electrónico",
"new_chat.quick.title": "Prueba una de estas tareas: un clic para empezar",
- "new_chat.quick.oss_more": "Conectar herramientas de código abierto",
"new_chat.quick.subtitle": "Elige una tarea concreta y Commander coordinará a los agentes adecuados",
"new_chat.quick.rnd": "Desarrollo",
"new_chat.quick.creation": "Redacción",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Por ejemplo: investiga 3 productos similares, compara sus funciones y precios y resúmelo en una presentación.",
"new_chat.home.explore_title": "¿Aún no lo tienes claro? Deja que Orkas te conozca primero.",
"new_chat.home.explore_body": "Habla de tu trabajo, tu negocio o tus dificultades, y Orkas te ayudará a encontrar los objetivos adecuados y a avanzar en ellos.",
- "new_chat.home.explore_context": "Comparte archivos con + o {connect} para darle más contexto a Orkas. Empieza por lo que te sientas cómodo compartiendo.",
- "new_chat.home.explore_connect_link": "conecta Feishu / DingTalk / tu correo",
+ "new_chat.home.explore_context": "Agrega materiales o {connect} para que Orkas te conozca mejor. Empieza por lo que te sientas cómodo compartiendo.",
+ "new_chat.home.explore_connect_link": "conecta tu correo, tiendas, aplicaciones de oficina y más",
"new_chat.home.input_placeholder": "Describe lo que quieres conseguir o adjunta los archivos que hay que procesar",
"new_chat.home.continue_label": "Sigue avanzando",
"new_chat.home.group.todos": "Pendientes importantes",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "La conversación de esta tarea todavía está en curso. Vuelve a ejecutarla cuando termine.",
"settings.cleanup.title": "Limpiar tareas antiguas",
"settings.cleanup.age": "Última actividad",
- "settings.cleanup.scope": "Tareas completadas dentro y fuera de proyectos. Se conservan las fijadas, no leídas, los borradores y las ejecuciones automatizadas.",
+ "settings.cleanup.scope": "Filtra todo el historial por antigüedad y limpia por proyecto o tarea.",
"settings.cleanup.days": "Hace más de {n} días",
"settings.cleanup.result": "En la papelera: {deleted}. Omitidas: {skipped}. Fallidas: {failed}.",
"settings.cleanup.progress": "Limpiando {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} tareas seleccionadas",
"settings.cleanup.empty": "No hay tareas antiguas para limpiar.",
"settings.cleanup.clean": "Limpiar",
- "settings.cleanup.confirm": "Mover {n} tareas, sus adjuntos y resultados integrados a la papelera. Puedes restaurarlas abajo. Con la sincronización activa, también se eliminan de otros dispositivos. El espacio se libera al vaciar la papelera.",
+ "settings.cleanup.confirm": "Mover {n} tareas, sus adjuntos y resultados integrados a la papelera. Se eliminarán los borradores sin enviar. Las tareas en ejecución se detienen automáticamente antes de la limpieza.",
"settings.cleanup.move": "Mover a la papelera ({n})",
"settings.cleanup.previous": "Anterior",
"settings.cleanup.next": "Siguiente",
"apps.commercial_required": "Las aplicaciones web requieren la versión comercial de Orkas. Descárgala para continuar.",
"apps.commercial_download": "Descargar versión comercial",
- "apps.commercial_open_failed": "No se pudo abrir la página de descarga. Inténtalo de nuevo."
+ "apps.commercial_open_failed": "No se pudo abrir la página de descarga. Inténtalo de nuevo.",
+ "settings.cleanup.draft": "Borrador",
+ "settings.cleanup.automation": "Automatización",
+ "settings.cleanup.pinned": "Fijada",
+ "settings.cleanup.unavailable": "No disponible",
+ "settings.cleanup.unread": "Sin leer"
}
diff --git a/src/renderer/locales/fr.json b/src/renderer/locales/fr.json
index 09b951bd..7ed7d9cd 100644
--- a/src/renderer/locales/fr.json
+++ b/src/renderer/locales/fr.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Apprentissage",
"new_chat.quick.ecommerce": "Commerce en ligne",
"new_chat.quick.title": "Essayez l’une de ces tâches : un clic suffit pour commencer",
- "new_chat.quick.oss_more": "Connecter des outils open source",
"new_chat.quick.subtitle": "Choisissez une tâche concrète et Commander coordonnera les Agents adaptés",
"new_chat.quick.rnd": "Développement",
"new_chat.quick.creation": "Rédaction",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Par exemple : étudier 3 produits similaires, comparer leurs fonctionnalités et leurs prix, puis en faire une présentation.",
"new_chat.home.explore_title": "Pas encore d’idée précise ? Laissez d’abord Orkas apprendre à vous connaître.",
"new_chat.home.explore_body": "Parlez de votre travail, de votre activité ou de vos difficultés : Orkas vous aide à trouver les bons objectifs et à les faire avancer.",
- "new_chat.home.explore_context": "Partagez des fichiers avec +, ou {connect}, pour donner plus de contexte à Orkas. Commencez par ce que vous êtes prêt à partager.",
- "new_chat.home.explore_connect_link": "connectez Feishu / DingTalk / votre e-mail",
+ "new_chat.home.explore_context": "Ajoutez des documents ou {connect} pour aider Orkas à mieux vous connaître. Commencez par ce que vous êtes prêt à partager.",
+ "new_chat.home.explore_connect_link": "connectez votre messagerie, vos boutiques, vos outils bureautiques et plus encore",
"new_chat.home.input_placeholder": "Décrivez ce que vous voulez accomplir, ou joignez les fichiers à traiter",
"new_chat.home.continue_label": "Faites avancer les choses",
"new_chat.home.group.todos": "À faire en priorité",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "La conversation de cette tâche est encore en cours. Relancez-la une fois terminée.",
"settings.cleanup.title": "Nettoyer les anciennes tâches",
"settings.cleanup.age": "Dernière activité",
- "settings.cleanup.scope": "Tâches terminées dans et hors des projets. Les tâches épinglées, non lues, les brouillons et les exécutions automatisées sont conservés.",
+ "settings.cleanup.scope": "Filtrez tout l’historique par ancienneté, puis nettoyez par projet ou par tâche.",
"settings.cleanup.days": "Il y a plus de {n} jours",
"settings.cleanup.result": "Dans la corbeille : {deleted}. Ignorées : {skipped}. Échecs : {failed}.",
"settings.cleanup.progress": "Nettoyage {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} tâches sélectionnées",
"settings.cleanup.empty": "Aucune ancienne tâche à nettoyer.",
"settings.cleanup.clean": "Nettoyer",
- "settings.cleanup.confirm": "Déplacer {n} tâches, leurs pièces jointes et résultats intégrés dans la corbeille. Vous pourrez les restaurer ci-dessous. Si la synchronisation est activée, la suppression concerne aussi les autres appareils. Videz la corbeille pour libérer l’espace disque.",
+ "settings.cleanup.confirm": "Déplacer {n} tâches, leurs pièces jointes et résultats intégrés dans la corbeille. Les brouillons non envoyés seront supprimés. Les tâches en cours sont arrêtées automatiquement avant le nettoyage.",
"settings.cleanup.move": "Mettre à la corbeille ({n})",
"settings.cleanup.previous": "Précédent",
"settings.cleanup.next": "Suivant",
"apps.commercial_required": "Les applications web nécessitent la version commerciale d’Orkas. Téléchargez-la pour continuer.",
"apps.commercial_download": "Télécharger la version commerciale",
- "apps.commercial_open_failed": "Impossible d’ouvrir la page de téléchargement. Réessayez."
+ "apps.commercial_open_failed": "Impossible d’ouvrir la page de téléchargement. Réessayez.",
+ "settings.cleanup.draft": "Brouillon",
+ "settings.cleanup.automation": "Automatisation",
+ "settings.cleanup.pinned": "Épinglée",
+ "settings.cleanup.unavailable": "Indisponible",
+ "settings.cleanup.unread": "Non lue"
}
diff --git a/src/renderer/locales/hi.json b/src/renderer/locales/hi.json
index cf53214b..a195f943 100644
--- a/src/renderer/locales/hi.json
+++ b/src/renderer/locales/hi.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "सीखना",
"new_chat.quick.ecommerce": "ई-कॉमर्स",
"new_chat.quick.title": "इनमें से कोई कार्य आज़माएँ — एक क्लिक में शुरू करें",
- "new_chat.quick.oss_more": "ओपन-सोर्स टूल जोड़ें",
"new_chat.quick.subtitle": "एक स्पष्ट कार्य चुनें और Commander सही एजेंटों का समन्वय करेगा",
"new_chat.quick.rnd": "डेवलपमेंट",
"new_chat.quick.creation": "लेखन",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "उदाहरण: 3 मिलते-जुलते उत्पादों पर रिसर्च करें, उनकी सुविधाओं और कीमतों की तुलना करें और एक प्रेज़ेंटेशन बनाएँ।",
"new_chat.home.explore_title": "अभी तय नहीं? पहले Orkas को आपको जानने दें।",
"new_chat.home.explore_body": "अपने काम, कारोबार या परेशानियों के बारे में बताएँ — Orkas सही लक्ष्य ढूँढने और उन्हें आगे बढ़ाते रहने में मदद करेगा।",
- "new_chat.home.explore_context": "+ से फ़ाइलें शेयर करें या {connect}, ताकि Orkas को ज़्यादा संदर्भ मिले। वहीं से शुरू करें जो आप शेयर करना चाहें।",
- "new_chat.home.explore_connect_link": "Feishu / DingTalk / ईमेल जोड़ें",
+ "new_chat.home.explore_context": "सामग्री जोड़ें या {connect}, ताकि Orkas आपको बेहतर समझ सके। वहीं से शुरू करें जो आप शेयर करना चाहें।",
+ "new_chat.home.explore_connect_link": "ईमेल, स्टोर, ऑफ़िस ऐप आदि कनेक्ट करें",
"new_chat.home.input_placeholder": "बताएँ कि आप क्या पूरा करना चाहते हैं, या जिन फ़ाइलों पर काम करना है उन्हें अटैच करें",
"new_chat.home.continue_label": "काम आगे बढ़ाते रहें",
"new_chat.home.group.todos": "ज़रूरी करने वाले काम",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "इस कार्य की बातचीत अभी चल रही है। पूरा होने के बाद इसे फिर से चलाएँ।",
"settings.cleanup.title": "पुराने कार्य साफ़ करें",
"settings.cleanup.age": "अंतिम गतिविधि",
- "settings.cleanup.scope": "प्रोजेक्ट के अंदर और बाहर के पूरे हुए कार्य। पिन किए गए, अपठित कार्य, ड्राफ़्ट और स्वचालन का इतिहास रखा जाता है।",
+ "settings.cleanup.scope": "सभी पुराने कार्यों को समय के अनुसार छाँटें और प्रोजेक्ट या कार्य के अनुसार साफ़ करें।",
"settings.cleanup.days": "{n} दिन से पहले",
"settings.cleanup.result": "ट्रैश में भेजे: {deleted}। छोड़े: {skipped}। विफल: {failed}।",
"settings.cleanup.progress": "साफ़ हो रहा है {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} कार्य चुने गए",
"settings.cleanup.empty": "साफ़ करने के लिए कोई पुराना कार्य नहीं है।",
"settings.cleanup.clean": "साफ़ करें",
- "settings.cleanup.confirm": "{n} कार्य, उनके अटैचमेंट और एम्बेड किए गए परिणाम ट्रैश में भेजें। नीचे से इन्हें बहाल कर सकते हैं। सिंक चालू होने पर अन्य डिवाइस से भी हटेंगे। ट्रैश खाली करने पर डिस्क स्थान खाली होगा।",
+ "settings.cleanup.confirm": "{n} कार्यों, उनके अटैचमेंट और एम्बेड किए गए परिणामों को रीसायकल बिन में ले जाएँ। न भेजे गए ड्राफ़्ट हट जाएँगे। सफ़ाई से पहले चल रहे कार्य अपने आप रोक दिए जाते हैं।",
"settings.cleanup.move": "ट्रैश में भेजें ({n})",
"settings.cleanup.previous": "पिछला",
"settings.cleanup.next": "अगला",
"apps.commercial_required": "वेब ऐप्स के लिए Orkas का व्यावसायिक संस्करण आवश्यक है। जारी रखने के लिए इसे डाउनलोड करें।",
"apps.commercial_download": "व्यावसायिक संस्करण डाउनलोड करें",
- "apps.commercial_open_failed": "डाउनलोड पृष्ठ नहीं खुल सका। कृपया फिर प्रयास करें।"
+ "apps.commercial_open_failed": "डाउनलोड पृष्ठ नहीं खुल सका। कृपया फिर प्रयास करें।",
+ "settings.cleanup.draft": "ड्राफ़्ट",
+ "settings.cleanup.automation": "ऑटोमेशन",
+ "settings.cleanup.pinned": "पिन किया",
+ "settings.cleanup.unavailable": "अनुपलब्ध",
+ "settings.cleanup.unread": "अपठित"
}
diff --git a/src/renderer/locales/id.json b/src/renderer/locales/id.json
index 4439593c..d68b6715 100644
--- a/src/renderer/locales/id.json
+++ b/src/renderer/locales/id.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Pembelajaran",
"new_chat.quick.ecommerce": "Perdagangan elektronik",
"new_chat.quick.title": "Coba salah satu tugas ini — satu klik untuk memulai",
- "new_chat.quick.oss_more": "Hubungkan alat sumber terbuka",
"new_chat.quick.subtitle": "Pilih tugas konkret dan Komandan akan mengoordinasikan agen yang tepat",
"new_chat.quick.rnd": "Perkembangan",
"new_chat.quick.creation": "Tulisan",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Misalnya: riset 3 produk sejenis, bandingkan fitur dan harganya, lalu rangkum menjadi presentasi.",
"new_chat.home.explore_title": "Belum yakin? Biarkan Orkas mengenalmu dulu.",
"new_chat.home.explore_body": "Ceritakan pekerjaan, bisnis, atau kendalamu, dan Orkas akan membantumu menemukan tujuan yang tepat serta terus menjalankannya.",
- "new_chat.home.explore_context": "Bagikan file dengan + atau {connect} agar Orkas punya lebih banyak konteks. Mulailah dari hal yang nyaman kamu bagikan.",
- "new_chat.home.explore_connect_link": "hubungkan Feishu / DingTalk / email",
+ "new_chat.home.explore_context": "Tambahkan materi atau {connect} agar Orkas lebih mengenal kamu. Mulailah dari hal yang nyaman kamu bagikan.",
+ "new_chat.home.explore_connect_link": "hubungkan email, toko, aplikasi perkantoran, dan lainnya",
"new_chat.home.input_placeholder": "Ceritakan apa yang ingin kamu capai, atau lampirkan file yang perlu diproses",
"new_chat.home.continue_label": "Lanjutkan pekerjaanmu",
"new_chat.home.group.todos": "Hal penting yang harus dilakukan",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "Percakapan untuk tugas ini masih berjalan. Jalankan lagi setelah selesai.",
"settings.cleanup.title": "Bersihkan tugas lama",
"settings.cleanup.age": "Aktivitas terakhir",
- "settings.cleanup.scope": "Tugas selesai di dalam maupun di luar proyek. Tugas disematkan, belum dibaca, draf, dan riwayat otomatisasi tetap disimpan.",
+ "settings.cleanup.scope": "Filter seluruh riwayat berdasarkan usia, lalu bersihkan per proyek atau tugas.",
"settings.cleanup.days": "Lebih dari {n} hari lalu",
"settings.cleanup.result": "Dipindahkan ke sampah: {deleted}. Dilewati: {skipped}. Gagal: {failed}.",
"settings.cleanup.progress": "Membersihkan {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} tugas dipilih",
"settings.cleanup.empty": "Tidak ada tugas lama untuk dibersihkan.",
"settings.cleanup.clean": "Bersihkan",
- "settings.cleanup.confirm": "Pindahkan {n} tugas, lampiran, dan hasil tertanam ke sampah. Anda dapat memulihkannya di bawah. Jika sinkronisasi aktif, penghapusan juga berlaku di perangkat lain. Ruang disk dibebaskan setelah sampah dikosongkan.",
+ "settings.cleanup.confirm": "Pindahkan {n} tugas, lampiran, dan hasil tertanam ke tempat sampah. Draf yang belum dikirim akan dihapus. Tugas yang berjalan dihentikan otomatis sebelum pembersihan.",
"settings.cleanup.move": "Pindahkan ke sampah ({n})",
"settings.cleanup.previous": "Sebelumnya",
"settings.cleanup.next": "Berikutnya",
"apps.commercial_required": "Aplikasi web memerlukan Orkas versi komersial. Unduh untuk melanjutkan.",
"apps.commercial_download": "Unduh versi komersial",
- "apps.commercial_open_failed": "Halaman unduhan tidak dapat dibuka. Coba lagi."
+ "apps.commercial_open_failed": "Halaman unduhan tidak dapat dibuka. Coba lagi.",
+ "settings.cleanup.draft": "Draf",
+ "settings.cleanup.automation": "Otomatisasi",
+ "settings.cleanup.pinned": "Disematkan",
+ "settings.cleanup.unavailable": "Tidak tersedia",
+ "settings.cleanup.unread": "Belum dibaca"
}
diff --git a/src/renderer/locales/it.json b/src/renderer/locales/it.json
index 80ce1f15..a9d63ea9 100644
--- a/src/renderer/locales/it.json
+++ b/src/renderer/locales/it.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Apprendimento",
"new_chat.quick.ecommerce": "E-commerce",
"new_chat.quick.title": "Prova una di queste attività: basta un clic per iniziare",
- "new_chat.quick.oss_more": "Connetti strumenti open source",
"new_chat.quick.subtitle": "Scegli un'attività concreta e Commander coordinerà gli agenti adatti",
"new_chat.quick.rnd": "Sviluppo",
"new_chat.quick.creation": "Scrittura",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Ad esempio: analizza 3 prodotti simili, confronta funzionalità e prezzi e riassumi tutto in una presentazione.",
"new_chat.home.explore_title": "Non hai ancora le idee chiare? Lascia prima che Orkas ti conosca.",
"new_chat.home.explore_body": "Parla del tuo lavoro, della tua attività o delle tue difficoltà: Orkas ti aiuterà a trovare gli obiettivi giusti e a portarli avanti.",
- "new_chat.home.explore_context": "Condividi file con + oppure {connect} per dare più contesto a Orkas. Inizia da ciò che ti senti di condividere.",
- "new_chat.home.explore_connect_link": "collega Feishu / DingTalk / email",
+ "new_chat.home.explore_context": "Aggiungi materiali o {connect} per aiutare Orkas a conoscerti meglio. Inizia da ciò che ti senti di condividere.",
+ "new_chat.home.explore_connect_link": "collega email, negozi, applicazioni per ufficio e altro",
"new_chat.home.input_placeholder": "Descrivi cosa vuoi realizzare oppure allega i file da elaborare",
"new_chat.home.continue_label": "Porta avanti il lavoro",
"new_chat.home.group.todos": "Da fare importanti",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "La conversazione di questa attività è ancora in corso. Eseguila di nuovo al termine.",
"settings.cleanup.title": "Pulisci le attività precedenti",
"settings.cleanup.age": "Ultima attività",
- "settings.cleanup.scope": "Attività completate dentro e fuori dai progetti. Restano le attività fissate, non lette, le bozze e le esecuzioni automatiche.",
+ "settings.cleanup.scope": "Filtra tutta la cronologia per data e pulisci per progetto o singola attività.",
"settings.cleanup.days": "Più di {n} giorni fa",
"settings.cleanup.result": "Nel cestino: {deleted}. Ignorate: {skipped}. Non riuscite: {failed}.",
"settings.cleanup.progress": "Pulizia {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} attività selezionate",
"settings.cleanup.empty": "Nessuna attività precedente da pulire.",
"settings.cleanup.clean": "Pulisci",
- "settings.cleanup.confirm": "Sposta {n} attività, allegati e risultati incorporati nel cestino. Potrai ripristinarli qui sotto. Con la sincronizzazione attiva, la rimozione si applica anche agli altri dispositivi. Lo spazio viene liberato svuotando il cestino.",
+ "settings.cleanup.confirm": "Sposta {n} attività, allegati e risultati incorporati nel cestino. Le bozze non inviate verranno eliminate. Le attività in esecuzione vengono interrotte automaticamente prima della pulizia.",
"settings.cleanup.move": "Sposta nel cestino ({n})",
"settings.cleanup.previous": "Precedente",
"settings.cleanup.next": "Successivo",
"apps.commercial_required": "Le app web richiedono la versione commerciale di Orkas. Scaricala per continuare.",
"apps.commercial_download": "Scarica la versione commerciale",
- "apps.commercial_open_failed": "Impossibile aprire la pagina di download. Riprova."
+ "apps.commercial_open_failed": "Impossibile aprire la pagina di download. Riprova.",
+ "settings.cleanup.draft": "Bozza",
+ "settings.cleanup.automation": "Automazione",
+ "settings.cleanup.pinned": "Fissata",
+ "settings.cleanup.unavailable": "Non disponibile",
+ "settings.cleanup.unread": "Non letta"
}
diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.json
index 1b2c1996..326ba550 100644
--- a/src/renderer/locales/ja.json
+++ b/src/renderer/locales/ja.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "学習サポート",
"new_chat.quick.ecommerce": "EC",
"new_chat.quick.title": "このタスクを試す — クリックですぐ開始",
- "new_chat.quick.oss_more": "オープンソースツールを接続",
"new_chat.quick.subtitle": "具体的なタスクを選ぶと、司令官が最適なエージェントを手配します",
"new_chat.quick.rnd": "開発",
"new_chat.quick.creation": "執筆",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "例:同類製品を 3 つ調査し、機能と価格を比較して、プレゼン資料にまとめる。",
"new_chat.home.explore_title": "まだ決まっていない? まずは Orkas にあなたのことを伝えましょう。",
"new_chat.home.explore_body": "仕事やビジネス、困っていることを話してください。Orkas が合った目標を見つけ、継続的に進めるお手伝いをします。",
- "new_chat.home.explore_context": "+ で資料を共有するか、{connect}して背景を補うと、Orkas があなたをより深く理解できます。共有してもよい内容から始めてください。",
- "new_chat.home.explore_connect_link": "Feishu / DingTalk / メールを接続",
+ "new_chat.home.explore_context": "資料を追加したり、{connect}して、Orkas にあなたのことをもっと知ってもらいましょう。共有してもよい内容から始めてください。",
+ "new_chat.home.explore_connect_link": "メール・ショップ・オフィスアプリなどを接続",
"new_chat.home.input_placeholder": "達成したいことを書くか、処理したい資料を添付してください",
"new_chat.home.continue_label": "やりかけの仕事を進めましょう",
"new_chat.home.group.todos": "重要な ToDo",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "このタスクの会話はまだ処理中です。終わってからもう一度実行してください。",
"settings.cleanup.title": "過去のタスクを整理",
"settings.cleanup.age": "最終アクティビティ",
- "settings.cleanup.scope": "プロジェクト内外の完了済みタスクが対象です。固定済み・未読・下書きのあるタスクと自動化の実行履歴は保持されます。",
+ "settings.cleanup.scope": "すべてのタスク履歴を期間で絞り込み、プロジェクト単位または個別に整理できます。",
"settings.cleanup.days": "{n} 日より前",
"settings.cleanup.result": "ごみ箱へ移動:{deleted} 件。スキップ:{skipped} 件。失敗:{failed} 件。",
"settings.cleanup.progress": "整理中 {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} 件を選択中",
"settings.cleanup.empty": "整理できる過去のタスクはありません。",
"settings.cleanup.clean": "整理",
- "settings.cleanup.confirm": "{n} 件のタスクと添付ファイル、埋め込み結果をごみ箱へ移動します。下から復元できます。同期が有効な場合、他のデバイスにも削除が反映されます。ディスク容量はごみ箱を空にすると解放されます。",
+ "settings.cleanup.confirm": "{n} 件のタスク、添付ファイル、埋め込み成果物をごみ箱に移動します。未送信の下書きは削除されます。 実行中のタスクは整理前に自動的に停止します。",
"settings.cleanup.move": "ごみ箱へ移動({n})",
"settings.cleanup.previous": "前へ",
"settings.cleanup.next": "次へ",
"apps.commercial_required": "Web アプリには Orkas 商用版が必要です。商用版をダウンロードして続けてください。",
"apps.commercial_download": "商用版をダウンロード",
- "apps.commercial_open_failed": "ダウンロードページを開けませんでした。もう一度お試しください。"
+ "apps.commercial_open_failed": "ダウンロードページを開けませんでした。もう一度お試しください。",
+ "settings.cleanup.draft": "下書き",
+ "settings.cleanup.automation": "自動化",
+ "settings.cleanup.pinned": "固定",
+ "settings.cleanup.unavailable": "利用不可",
+ "settings.cleanup.unread": "未読"
}
diff --git a/src/renderer/locales/ko.json b/src/renderer/locales/ko.json
index 22725f28..b48e84f6 100644
--- a/src/renderer/locales/ko.json
+++ b/src/renderer/locales/ko.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "학습",
"new_chat.quick.ecommerce": "전자상거래",
"new_chat.quick.title": "클릭 한 번으로 이 작업들을 시작해 보세요",
- "new_chat.quick.oss_more": "오픈 소스 도구 연결",
"new_chat.quick.subtitle": "구체적인 작업을 선택하면 지휘 에이전트가 적절한 에이전트들을 조율합니다",
"new_chat.quick.rnd": "개발",
"new_chat.quick.creation": "글쓰기",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "예: 비슷한 제품 3개를 조사해 기능과 가격을 비교하고 프레젠테이션으로 정리하기.",
"new_chat.home.explore_title": "아직 정하지 못했나요? 먼저 Orkas가 당신을 알게 해 주세요.",
"new_chat.home.explore_body": "하는 일, 사업, 고민을 이야기해 주세요. Orkas가 알맞은 목표를 찾고 꾸준히 진행하도록 돕습니다.",
- "new_chat.home.explore_context": "+로 자료를 공유하거나 {connect}해 배경을 더해 주면 Orkas가 당신을 더 잘 이해합니다. 공유해도 괜찮은 것부터 시작하세요.",
- "new_chat.home.explore_connect_link": "Feishu / DingTalk / 이메일 연결",
+ "new_chat.home.explore_context": "자료를 추가하거나 {connect}해 Orkas가 당신을 더 잘 이해하도록 도와주세요. 공유해도 괜찮은 내용부터 시작하세요.",
+ "new_chat.home.explore_connect_link": "이메일, 쇼핑몰, 업무용 앱 등을 연결",
"new_chat.home.input_placeholder": "이루고 싶은 일을 적거나 처리할 자료를 첨부하세요",
"new_chat.home.continue_label": "하던 일을 이어서 진행하세요",
"new_chat.home.group.todos": "중요한 할 일",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "이 작업의 대화가 아직 진행 중입니다. 끝난 후 다시 실행하세요.",
"settings.cleanup.title": "이전 작업 정리",
"settings.cleanup.age": "마지막 활동",
- "settings.cleanup.scope": "프로젝트 안팎의 완료된 작업을 정리합니다. 고정된 작업, 읽지 않은 작업, 초안과 자동화 실행 기록은 유지됩니다.",
+ "settings.cleanup.scope": "모든 작업 기록을 기간으로 필터링하고 프로젝트별 또는 개별로 정리하세요.",
"settings.cleanup.days": "{n}일 이전",
"settings.cleanup.result": "휴지통으로 이동: {deleted}개. 건너뜀: {skipped}개. 실패: {failed}개.",
"settings.cleanup.progress": "정리 중 {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "작업 {n}개 선택됨",
"settings.cleanup.empty": "정리할 이전 작업이 없습니다.",
"settings.cleanup.clean": "정리",
- "settings.cleanup.confirm": "작업 {n}개와 첨부 파일, 내장 결과를 휴지통으로 이동합니다. 아래에서 복원할 수 있습니다. 동기화가 켜져 있으면 다른 기기에서도 삭제됩니다. 휴지통을 비워야 디스크 공간이 확보됩니다.",
+ "settings.cleanup.confirm": "작업 {n}개와 첨부파일, 포함된 결과를 휴지통으로 이동합니다. 보내지 않은 초안은 삭제됩니다. 실행 중인 작업은 정리 전에 자동으로 중지됩니다.",
"settings.cleanup.move": "휴지통으로 이동({n})",
"settings.cleanup.previous": "이전",
"settings.cleanup.next": "다음",
"apps.commercial_required": "웹 앱을 사용하려면 Orkas 상용 버전이 필요합니다. 다운로드하여 계속하세요.",
"apps.commercial_download": "상용 버전 다운로드",
- "apps.commercial_open_failed": "다운로드 페이지를 열 수 없습니다. 다시 시도하세요."
+ "apps.commercial_open_failed": "다운로드 페이지를 열 수 없습니다. 다시 시도하세요.",
+ "settings.cleanup.draft": "초안",
+ "settings.cleanup.automation": "자동화",
+ "settings.cleanup.pinned": "고정",
+ "settings.cleanup.unavailable": "정리 불가",
+ "settings.cleanup.unread": "읽지 않음"
}
diff --git a/src/renderer/locales/pt-pt.json b/src/renderer/locales/pt-pt.json
index c9f82225..3b9499a4 100644
--- a/src/renderer/locales/pt-pt.json
+++ b/src/renderer/locales/pt-pt.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Aprendizagem",
"new_chat.quick.ecommerce": "Comércio eletrónico",
"new_chat.quick.title": "Experimente uma destas tarefas — um clique para começar",
- "new_chat.quick.oss_more": "Ligar ferramentas de código aberto",
"new_chat.quick.subtitle": "Escolha uma tarefa concreta e o Commander coordenará os agentes certos",
"new_chat.quick.rnd": "Desenvolvimento",
"new_chat.quick.creation": "Escrita",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Por exemplo: pesquise 3 produtos semelhantes, compare funcionalidades e preços e organize tudo numa apresentação.",
"new_chat.home.explore_title": "Ainda não sabe? Deixe primeiro o Orkas conhecê-lo.",
"new_chat.home.explore_body": "Fale sobre o seu trabalho, o seu negócio ou as suas dificuldades, e o Orkas ajuda-o a encontrar os objetivos certos e a fazê-los avançar.",
- "new_chat.home.explore_context": "Partilhe ficheiros com + ou {connect} para dar mais contexto ao Orkas. Comece pelo que se sentir à vontade para partilhar.",
- "new_chat.home.explore_connect_link": "ligue o Feishu / DingTalk / e-mail",
+ "new_chat.home.explore_context": "Adicione materiais ou {connect} para ajudar o Orkas a conhecê-lo melhor. Comece pelo que se sentir à vontade para partilhar.",
+ "new_chat.home.explore_connect_link": "ligue o e-mail, lojas, aplicações de escritório e muito mais",
"new_chat.home.input_placeholder": "Descreva o que pretende fazer ou anexe os ficheiros a tratar",
"new_chat.home.continue_label": "Continue a avançar",
"new_chat.home.group.todos": "A fazer importantes",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "A conversa desta tarefa ainda está em curso. Execute-a novamente quando terminar.",
"settings.cleanup.title": "Limpar tarefas antigas",
"settings.cleanup.age": "Última atividade",
- "settings.cleanup.scope": "Tarefas concluídas dentro e fora de projetos. São mantidas as tarefas afixadas, não lidas, os rascunhos e as execuções de automatizações.",
+ "settings.cleanup.scope": "Filtre todo o histórico por antiguidade e limpe por projeto ou tarefa.",
"settings.cleanup.days": "Há mais de {n} dias",
"settings.cleanup.result": "Na reciclagem: {deleted}. Ignoradas: {skipped}. Falhas: {failed}.",
"settings.cleanup.progress": "A limpar {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} tarefas selecionadas",
"settings.cleanup.empty": "Não há tarefas antigas para limpar.",
"settings.cleanup.clean": "Limpar",
- "settings.cleanup.confirm": "Mover {n} tarefas, anexos e resultados incorporados para a reciclagem. Pode restaurá-los abaixo. Com a sincronização ativa, a eliminação também se aplica a outros dispositivos. O espaço é libertado ao esvaziar a reciclagem.",
+ "settings.cleanup.confirm": "Mover {n} tarefas, anexos e resultados incorporados para a reciclagem. Os rascunhos não enviados serão eliminados. As tarefas em execução são interrompidas automaticamente antes da limpeza.",
"settings.cleanup.move": "Mover para a reciclagem ({n})",
"settings.cleanup.previous": "Anterior",
"settings.cleanup.next": "Seguinte",
"apps.commercial_required": "As aplicações Web requerem a versão comercial do Orkas. Transfira-a para continuar.",
"apps.commercial_download": "Transferir versão comercial",
- "apps.commercial_open_failed": "Não foi possível abrir a página de transferência. Tente novamente."
+ "apps.commercial_open_failed": "Não foi possível abrir a página de transferência. Tente novamente.",
+ "settings.cleanup.draft": "Rascunho",
+ "settings.cleanup.automation": "Automatização",
+ "settings.cleanup.pinned": "Afixada",
+ "settings.cleanup.unavailable": "Indisponível",
+ "settings.cleanup.unread": "Não lida"
}
diff --git a/src/renderer/locales/pt.json b/src/renderer/locales/pt.json
index 12d78cc1..b648a96a 100644
--- a/src/renderer/locales/pt.json
+++ b/src/renderer/locales/pt.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Aprendizagem",
"new_chat.quick.ecommerce": "Ecommerce",
"new_chat.quick.title": "Experimente uma destas tarefas — um clique para começar",
- "new_chat.quick.oss_more": "Conectar ferramentas de código aberto",
"new_chat.quick.subtitle": "Escolha uma tarefa concreta e o Comandante coordenará os agentes certos",
"new_chat.quick.rnd": "Desenvolvimento",
"new_chat.quick.creation": "Escrita",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Por exemplo: pesquise 3 produtos semelhantes, compare recursos e preços e organize tudo em uma apresentação.",
"new_chat.home.explore_title": "Ainda não sabe? Deixe o Orkas conhecer você primeiro.",
"new_chat.home.explore_body": "Fale sobre seu trabalho, seu negócio ou suas dificuldades, e o Orkas ajuda você a encontrar os objetivos certos e a avançar com eles.",
- "new_chat.home.explore_context": "Compartilhe arquivos com + ou {connect} para dar mais contexto ao Orkas. Comece pelo que você se sentir à vontade para compartilhar.",
- "new_chat.home.explore_connect_link": "conecte Feishu / DingTalk / e-mail",
+ "new_chat.home.explore_context": "Adicione materiais ou {connect} para ajudar o Orkas a conhecer você melhor. Comece pelo que se sentir à vontade para compartilhar.",
+ "new_chat.home.explore_connect_link": "conecte e-mail, lojas, aplicativos de escritório e mais",
"new_chat.home.input_placeholder": "Descreva o que você quer realizar ou anexe os arquivos a serem trabalhados",
"new_chat.home.continue_label": "Continue avançando",
"new_chat.home.group.todos": "A fazer importantes",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "A conversa desta tarefa ainda está em andamento. Execute-a novamente quando terminar.",
"settings.cleanup.title": "Limpar tarefas antigas",
"settings.cleanup.age": "Última atividade",
- "settings.cleanup.scope": "Tarefas concluídas dentro e fora de projetos. Tarefas fixadas, não lidas, rascunhos e execuções de automações são mantidos.",
+ "settings.cleanup.scope": "Filtre todo o histórico por tempo e limpe por projeto ou tarefa.",
"settings.cleanup.days": "Há mais de {n} dias",
"settings.cleanup.result": "Na lixeira: {deleted}. Ignoradas: {skipped}. Falhas: {failed}.",
"settings.cleanup.progress": "Limpando {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} tarefas selecionadas",
"settings.cleanup.empty": "Nenhuma tarefa antiga para limpar.",
"settings.cleanup.clean": "Limpar",
- "settings.cleanup.confirm": "Mover {n} tarefas, anexos e resultados incorporados para a lixeira. Você pode restaurá-los abaixo. Com a sincronização ativa, a exclusão também se aplica a outros dispositivos. O espaço é liberado ao esvaziar a lixeira.",
+ "settings.cleanup.confirm": "Mover {n} tarefas, anexos e resultados incorporados para a lixeira. Rascunhos não enviados serão excluídos. As tarefas em execução são interrompidas automaticamente antes da limpeza.",
"settings.cleanup.move": "Mover para a lixeira ({n})",
"settings.cleanup.previous": "Anterior",
"settings.cleanup.next": "Próxima",
"apps.commercial_required": "Os aplicativos web exigem a versão comercial do Orkas. Baixe-a para continuar.",
"apps.commercial_download": "Baixar versão comercial",
- "apps.commercial_open_failed": "Não foi possível abrir a página de download. Tente novamente."
+ "apps.commercial_open_failed": "Não foi possível abrir a página de download. Tente novamente.",
+ "settings.cleanup.draft": "Rascunho",
+ "settings.cleanup.automation": "Automação",
+ "settings.cleanup.pinned": "Fixada",
+ "settings.cleanup.unavailable": "Indisponível",
+ "settings.cleanup.unread": "Não lida"
}
diff --git a/src/renderer/locales/ru.json b/src/renderer/locales/ru.json
index 2a74744e..2fe2edb7 100644
--- a/src/renderer/locales/ru.json
+++ b/src/renderer/locales/ru.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Обучение",
"new_chat.quick.ecommerce": "Электронная торговля",
"new_chat.quick.title": "Попробуйте одну из этих задач — начните одним нажатием",
- "new_chat.quick.oss_more": "Подключить инструменты с открытым кодом",
"new_chat.quick.subtitle": "Выберите конкретную задачу, и командир скоординирует подходящих агентов",
"new_chat.quick.rnd": "Разработка",
"new_chat.quick.creation": "Тексты",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Например: изучить 3 похожих продукта, сравнить функции и цены и оформить всё в презентацию.",
"new_chat.home.explore_title": "Пока не решили? Сначала позвольте Orkas узнать вас.",
"new_chat.home.explore_body": "Расскажите о своей работе, бизнесе или трудностях — Orkas поможет найти подходящие цели и продвигаться к ним.",
- "new_chat.home.explore_context": "Поделитесь файлами через + или {connect}, чтобы дать Orkas больше контекста. Начните с того, чем готовы поделиться.",
- "new_chat.home.explore_connect_link": "подключите Feishu / DingTalk / почту",
+ "new_chat.home.explore_context": "Добавьте материалы или {connect}, чтобы Orkas лучше вас узнал. Начните с того, чем готовы поделиться.",
+ "new_chat.home.explore_connect_link": "подключите почту, магазины, офисные приложения и другие сервисы",
"new_chat.home.input_placeholder": "Опишите, чего хотите добиться, или приложите файлы для обработки",
"new_chat.home.continue_label": "Продолжим начатое",
"new_chat.home.group.todos": "Важные дела",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "Беседа этой задачи ещё выполняется. Запустите её снова, когда она завершится.",
"settings.cleanup.title": "Очистить старые задачи",
"settings.cleanup.age": "Последняя активность",
- "settings.cleanup.scope": "Завершённые задачи внутри и вне проектов. Закреплённые, непрочитанные задачи, черновики и запуски автоматизаций сохраняются.",
+ "settings.cleanup.scope": "Фильтруйте всю историю по давности и очищайте по проектам или отдельным задачам.",
"settings.cleanup.days": "Более {n} дней назад",
"settings.cleanup.result": "В корзине: {deleted}. Пропущено: {skipped}. Ошибки: {failed}.",
"settings.cleanup.progress": "Очистка {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "Выбрано задач: {n}",
"settings.cleanup.empty": "Нет старых задач для очистки.",
"settings.cleanup.clean": "Очистить",
- "settings.cleanup.confirm": "Переместить {n} задач, вложения и встроенные результаты в корзину. Их можно восстановить ниже. При включённой синхронизации удаление затронет другие устройства. Место освободится после очистки корзины.",
+ "settings.cleanup.confirm": "Переместить {n} задач, вложения и встроенные результаты в корзину. Неотправленные черновики будут удалены. Выполняемые задачи автоматически останавливаются перед очисткой.",
"settings.cleanup.move": "В корзину ({n})",
"settings.cleanup.previous": "Назад",
"settings.cleanup.next": "Далее",
"apps.commercial_required": "Для веб-приложений нужна коммерческая версия Orkas. Скачайте её, чтобы продолжить.",
"apps.commercial_download": "Скачать коммерческую версию",
- "apps.commercial_open_failed": "Не удалось открыть страницу загрузки. Повторите попытку."
+ "apps.commercial_open_failed": "Не удалось открыть страницу загрузки. Повторите попытку.",
+ "settings.cleanup.draft": "Черновик",
+ "settings.cleanup.automation": "Автоматизация",
+ "settings.cleanup.pinned": "Закреплено",
+ "settings.cleanup.unavailable": "Недоступно",
+ "settings.cleanup.unread": "Не прочитано"
}
diff --git a/src/renderer/locales/th.json b/src/renderer/locales/th.json
index fc832ff8..aff705d0 100644
--- a/src/renderer/locales/th.json
+++ b/src/renderer/locales/th.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "การเรียนรู้",
"new_chat.quick.ecommerce": "อีคอมเมิร์ซ",
"new_chat.quick.title": "ลองงานเหล่านี้ — คลิกเดียวก็เริ่มได้",
- "new_chat.quick.oss_more": "เชื่อมต่อเครื่องมือโอเพนซอร์ส",
"new_chat.quick.subtitle": "เลือกงานที่ชัดเจน แล้วผู้บัญชาการจะประสานเอเจนต์ที่เหมาะสม",
"new_chat.quick.rnd": "การพัฒนา",
"new_chat.quick.creation": "การเขียน",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "เช่น: สำรวจผลิตภัณฑ์ที่คล้ายกัน 3 ตัว เปรียบเทียบฟีเจอร์และราคา แล้วสรุปเป็นงานนำเสนอ",
"new_chat.home.explore_title": "ยังไม่แน่ใจ? ให้ Orkas ได้รู้จักคุณก่อน",
"new_chat.home.explore_body": "เล่าเรื่องงาน ธุรกิจ หรือปัญหาที่เจออยู่ แล้ว Orkas จะช่วยหาเป้าหมายที่เหมาะสมและผลักดันต่อไปอย่างต่อเนื่อง",
- "new_chat.home.explore_context": "แชร์ไฟล์ด้วย + หรือ{connect} เพื่อให้ Orkas เข้าใจบริบทของคุณมากขึ้น เริ่มจากสิ่งที่คุณสะดวกใจจะแชร์",
- "new_chat.home.explore_connect_link": "เชื่อมต่อ Feishu / DingTalk / อีเมล",
+ "new_chat.home.explore_context": "เพิ่มเอกสารหรือ{connect} เพื่อให้ Orkas รู้จักคุณมากขึ้น เริ่มจากสิ่งที่คุณสะดวกใจจะแชร์",
+ "new_chat.home.explore_connect_link": "เชื่อมต่ออีเมล ร้านค้า แอปสำนักงาน และอื่นๆ",
"new_chat.home.input_placeholder": "บอกสิ่งที่คุณอยากทำให้สำเร็จ หรือแนบไฟล์ที่ต้องจัดการ",
"new_chat.home.continue_label": "ทำงานต่อให้คืบหน้า",
"new_chat.home.group.todos": "สิ่งที่ต้องทำที่สำคัญ",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "บทสนทนาของงานนี้ยังทำงานอยู่ เรียกใช้อีกครั้งเมื่อเสร็จแล้ว",
"settings.cleanup.title": "ล้างงานเก่า",
"settings.cleanup.age": "ใช้งานล่าสุด",
- "settings.cleanup.scope": "งานที่เสร็จแล้วทั้งในและนอกโครงการ โดยเก็บงานที่ปักหมุด ยังไม่อ่าน ฉบับร่าง และประวัติระบบอัตโนมัติไว้",
+ "settings.cleanup.scope": "กรองประวัติงานทั้งหมดตามเวลา แล้วล้างตามโครงการหรือทีละงาน",
"settings.cleanup.days": "มากกว่า {n} วันที่แล้ว",
"settings.cleanup.result": "ย้ายไปถังขยะ {deleted} รายการ ข้าม {skipped} รายการ ล้มเหลว {failed} รายการ",
"settings.cleanup.progress": "กำลังล้าง {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "เลือก {n} งาน",
"settings.cleanup.empty": "ไม่มีงานเก่าที่ล้างได้",
"settings.cleanup.clean": "ล้าง",
- "settings.cleanup.confirm": "ย้าย {n} งาน พร้อมไฟล์แนบและผลลัพธ์ที่ฝังไว้ไปยังถังขยะ โดยกู้คืนได้ด้านล่าง หากเปิดการซิงค์ การลบจะมีผลกับอุปกรณ์อื่นด้วย พื้นที่ดิสก์จะว่างเมื่อเทถังขยะ",
+ "settings.cleanup.confirm": "ย้าย {n} งาน ไฟล์แนบ และผลลัพธ์ที่ฝังไว้ไปยังถังรีไซเคิล ฉบับร่างที่ยังไม่ส่งจะถูกลบ งานที่กำลังทำงานจะหยุดโดยอัตโนมัติก่อนล้าง",
"settings.cleanup.move": "ย้ายไปถังขยะ ({n})",
"settings.cleanup.previous": "ก่อนหน้า",
"settings.cleanup.next": "ถัดไป",
"apps.commercial_required": "แอปเว็บต้องใช้ Orkas เวอร์ชันเชิงพาณิชย์ ดาวน์โหลดเพื่อดำเนินการต่อ",
"apps.commercial_download": "ดาวน์โหลดเวอร์ชันเชิงพาณิชย์",
- "apps.commercial_open_failed": "เปิดหน้าดาวน์โหลดไม่ได้ โปรดลองอีกครั้ง"
+ "apps.commercial_open_failed": "เปิดหน้าดาวน์โหลดไม่ได้ โปรดลองอีกครั้ง",
+ "settings.cleanup.draft": "ฉบับร่าง",
+ "settings.cleanup.automation": "อัตโนมัติ",
+ "settings.cleanup.pinned": "ปักหมุด",
+ "settings.cleanup.unavailable": "ยังล้างไม่ได้",
+ "settings.cleanup.unread": "ยังไม่อ่าน"
}
diff --git a/src/renderer/locales/tr.json b/src/renderer/locales/tr.json
index d759fc75..a067ef4e 100644
--- a/src/renderer/locales/tr.json
+++ b/src/renderer/locales/tr.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Öğrenme",
"new_chat.quick.ecommerce": "E-ticaret",
"new_chat.quick.title": "Bu görevlerden birini deneyin; tek tıkla başlayın",
- "new_chat.quick.oss_more": "Açık kaynak araçlarını bağla",
"new_chat.quick.subtitle": "Somut bir görev seçin; Commander doğru ajanları koordine etsin",
"new_chat.quick.rnd": "Geliştirme",
"new_chat.quick.creation": "Yazı",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Örneğin: 3 benzer ürünü araştır, özelliklerini ve fiyatlarını karşılaştır ve bir sunuma dönüştür.",
"new_chat.home.explore_title": "Henüz emin değil misiniz? Önce Orkas sizi tanısın.",
"new_chat.home.explore_body": "İşinizden, şirketinizden veya zorluklarınızdan bahsedin; Orkas doğru hedefleri bulmanıza ve ilerletmenize yardımcı olsun.",
- "new_chat.home.explore_context": "+ ile dosya paylaşın veya {connect}; böylece Orkas sizi daha iyi anlasın. Paylaşmaktan rahatsız olmadığınız şeylerle başlayın.",
- "new_chat.home.explore_connect_link": "Feishu / DingTalk / e-postanızı bağlayın",
+ "new_chat.home.explore_context": "Materyal ekleyin veya {connect}; böylece Orkas sizi daha iyi tanısın. Paylaşmaktan rahatsız olmadığınız şeylerle başlayın.",
+ "new_chat.home.explore_connect_link": "e-posta, mağaza, ofis uygulamaları ve daha fazlasını bağlayın",
"new_chat.home.input_placeholder": "Neyi başarmak istediğinizi yazın veya işlenecek dosyaları ekleyin",
"new_chat.home.continue_label": "İşleri ilerletmeye devam edin",
"new_chat.home.group.todos": "Önemli yapılacaklar",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "Bu görevin sohbeti hâlâ çalışıyor. Bittiğinde tekrar çalıştırın.",
"settings.cleanup.title": "Eski görevleri temizle",
"settings.cleanup.age": "Son etkinlik",
- "settings.cleanup.scope": "Projelerin içindeki ve dışındaki tamamlanmış görevler. Sabitlenen, okunmamış görevler, taslaklar ve otomasyon geçmişi korunur.",
+ "settings.cleanup.scope": "Tüm geçmişi tarihe göre filtreleyip proje veya görev bazında temizleyin.",
"settings.cleanup.days": "{n} günden önce",
"settings.cleanup.result": "Çöp kutusuna taşınan: {deleted}. Atlanan: {skipped}. Başarısız: {failed}.",
"settings.cleanup.progress": "Temizleniyor {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "{n} görev seçildi",
"settings.cleanup.empty": "Temizlenecek eski görev yok.",
"settings.cleanup.clean": "Temizle",
- "settings.cleanup.confirm": "{n} görevi, eklerini ve gömülü sonuçlarını çöp kutusuna taşıyın. Aşağıdan geri yükleyebilirsiniz. Eşitleme açıksa silme diğer cihazlara da uygulanır. Disk alanı çöp kutusu boşaltıldığında açılır.",
+ "settings.cleanup.confirm": "{n} görevi, eklerini ve gömülü sonuçlarını geri dönüşüm kutusuna taşıyın. Gönderilmemiş taslaklar silinir. Çalışan görevler temizlemeden önce otomatik olarak durdurulur.",
"settings.cleanup.move": "Çöp kutusuna taşı ({n})",
"settings.cleanup.previous": "Önceki",
"settings.cleanup.next": "Sonraki",
"apps.commercial_required": "Web uygulamaları için Orkas’ın ticari sürümü gerekir. Devam etmek için indirin.",
"apps.commercial_download": "Ticari sürümü indir",
- "apps.commercial_open_failed": "İndirme sayfası açılamadı. Lütfen tekrar deneyin."
+ "apps.commercial_open_failed": "İndirme sayfası açılamadı. Lütfen tekrar deneyin.",
+ "settings.cleanup.draft": "Taslak",
+ "settings.cleanup.automation": "Otomasyon",
+ "settings.cleanup.pinned": "Sabitlenmiş",
+ "settings.cleanup.unavailable": "Kullanılamıyor",
+ "settings.cleanup.unread": "Okunmamış"
}
diff --git a/src/renderer/locales/vi.json b/src/renderer/locales/vi.json
index 740c6d7f..bdb77e56 100644
--- a/src/renderer/locales/vi.json
+++ b/src/renderer/locales/vi.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "Học tập",
"new_chat.quick.ecommerce": "Thương mại điện tử",
"new_chat.quick.title": "Thử một tác vụ dưới đây — một lần nhấn để bắt đầu",
- "new_chat.quick.oss_more": "Kết nối công cụ mã nguồn mở",
"new_chat.quick.subtitle": "Chọn tác vụ cụ thể, Commander sẽ điều phối tác tử phù hợp",
"new_chat.quick.rnd": "Phát triển",
"new_chat.quick.creation": "Viết lách",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "Ví dụ: nghiên cứu 3 sản phẩm tương tự, so sánh tính năng và giá, rồi tổng hợp thành một bài thuyết trình.",
"new_chat.home.explore_title": "Chưa nghĩ ra? Hãy để Orkas hiểu bạn trước.",
"new_chat.home.explore_body": "Hãy chia sẻ về công việc, việc kinh doanh hay khó khăn của bạn; Orkas sẽ giúp bạn tìm mục tiêu phù hợp và tiếp tục thúc đẩy.",
- "new_chat.home.explore_context": "Chia sẻ tài liệu bằng + hoặc {connect} để Orkas có thêm bối cảnh. Hãy bắt đầu từ những gì bạn sẵn sàng chia sẻ.",
- "new_chat.home.explore_connect_link": "kết nối Feishu / DingTalk / email",
+ "new_chat.home.explore_context": "Thêm tài liệu hoặc {connect} để Orkas hiểu bạn hơn. Hãy bắt đầu từ những gì bạn sẵn sàng chia sẻ.",
+ "new_chat.home.explore_connect_link": "kết nối email, cửa hàng, ứng dụng văn phòng và các dịch vụ khác",
"new_chat.home.input_placeholder": "Mô tả điều bạn muốn hoàn thành, hoặc đính kèm tài liệu cần xử lý",
"new_chat.home.continue_label": "Tiếp tục đẩy công việc",
"new_chat.home.group.todos": "Việc cần làm quan trọng",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "Cuộc trò chuyện của tác vụ này vẫn đang chạy. Hãy chạy lại khi hoàn tất.",
"settings.cleanup.title": "Dọn dẹp tác vụ cũ",
"settings.cleanup.age": "Hoạt động gần nhất",
- "settings.cleanup.scope": "Tác vụ đã hoàn thành trong và ngoài dự án. Giữ lại tác vụ đã ghim, chưa đọc, bản nháp và lịch sử tự động hóa.",
+ "settings.cleanup.scope": "Lọc toàn bộ lịch sử theo thời gian, rồi dọn theo dự án hoặc từng tác vụ.",
"settings.cleanup.days": "Hơn {n} ngày trước",
"settings.cleanup.result": "Đã chuyển vào thùng rác: {deleted}. Bỏ qua: {skipped}. Lỗi: {failed}.",
"settings.cleanup.progress": "Đang dọn dẹp {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "Đã chọn {n} tác vụ",
"settings.cleanup.empty": "Không có tác vụ cũ để dọn dẹp.",
"settings.cleanup.clean": "Dọn dẹp",
- "settings.cleanup.confirm": "Chuyển {n} tác vụ, tệp đính kèm và kết quả nhúng vào thùng rác. Có thể khôi phục bên dưới. Khi bật đồng bộ, thao tác xóa cũng áp dụng trên thiết bị khác. Dung lượng được giải phóng sau khi dọn sạch thùng rác.",
+ "settings.cleanup.confirm": "Chuyển {n} tác vụ, tệp đính kèm và kết quả nhúng vào thùng rác. Bản nháp chưa gửi sẽ bị xóa. Tác vụ đang chạy sẽ tự động dừng trước khi dọn.",
"settings.cleanup.move": "Chuyển vào thùng rác ({n})",
"settings.cleanup.previous": "Trước",
"settings.cleanup.next": "Tiếp",
"apps.commercial_required": "Ứng dụng web yêu cầu phiên bản thương mại của Orkas. Hãy tải xuống để tiếp tục.",
"apps.commercial_download": "Tải phiên bản thương mại",
- "apps.commercial_open_failed": "Không thể mở trang tải xuống. Vui lòng thử lại."
+ "apps.commercial_open_failed": "Không thể mở trang tải xuống. Vui lòng thử lại.",
+ "settings.cleanup.draft": "Bản nháp",
+ "settings.cleanup.automation": "Tự động hóa",
+ "settings.cleanup.pinned": "Đã ghim",
+ "settings.cleanup.unavailable": "Không khả dụng",
+ "settings.cleanup.unread": "Chưa đọc"
}
diff --git a/src/renderer/locales/zh-tw.json b/src/renderer/locales/zh-tw.json
index c6400f94..2241a136 100644
--- a/src/renderer/locales/zh-tw.json
+++ b/src/renderer/locales/zh-tw.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "學習輔導",
"new_chat.quick.ecommerce": "電商",
"new_chat.quick.title": "試試這些任務,點一下就能開始",
- "new_chat.quick.oss_more": "接入開源工具能力",
"new_chat.quick.subtitle": "選一個具體任務,指揮官會安排合適的智慧代理完成",
"new_chat.quick.rnd": "開發",
"new_chat.quick.creation": "寫作",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "例如:調研 3 款同類產品,比較功能與定價,整理成一份簡報。",
"new_chat.home.explore_title": "還沒想好?先讓 Orkas 了解你。",
"new_chat.home.explore_body": "聊聊你的工作、生意或困擾,讓 Orkas 幫你找到合適的目標,並持續推進。",
- "new_chat.home.explore_context": "用 + 分享資料,或{connect},補充背景,讓 Orkas 更了解你。從你願意分享的內容開始。",
- "new_chat.home.explore_connect_link": "連接飛書 / 釘釘 / 電子郵件",
+ "new_chat.home.explore_context": "新增資料或{connect},讓 Orkas 更了解你。從你願意分享的內容開始。",
+ "new_chat.home.explore_connect_link": "連接電子郵件/店鋪/辦公軟體等",
"new_chat.home.input_placeholder": "說說你想完成什麼,或附上需要處理的資料",
"new_chat.home.continue_label": "接著把事情推進",
"new_chat.home.group.todos": "重要待辦",
@@ -2624,7 +2623,7 @@
"project.todo.run_busy": "這個待辦所在的對話仍在處理中,結束後再執行。",
"settings.cleanup.title": "清理歷史任務",
"settings.cleanup.age": "最後活動時間",
- "settings.cleanup.scope": "清理專案內外的已完成任務。保留置頂、未讀、有草稿的任務和自動化執行記錄。",
+ "settings.cleanup.scope": "按時間篩選所有歷史任務,支援按專案或逐項清理。",
"settings.cleanup.days": "{n} 天以前",
"settings.cleanup.result": "已移入資源回收筒 {deleted} 項,略過 {skipped} 項,失敗 {failed} 項。",
"settings.cleanup.progress": "正在清理 {done} / {total}",
@@ -2632,11 +2631,16 @@
"settings.cleanup.count": "已選 {n} 項任務",
"settings.cleanup.empty": "暫無可清理的歷史任務。",
"settings.cleanup.clean": "清理",
- "settings.cleanup.confirm": "將 {n} 項任務及其附件、內嵌產物移入資源回收筒,可在下方還原。啟用同步後,刪除也會同步至其他裝置。清空資源回收筒後才會釋放相應磁碟空間。",
+ "settings.cleanup.confirm": "將 {n} 項任務、附件及內嵌產物移入資源回收筒,未傳送的草稿一併刪除。 執行中的任務會在清理前自動停止。",
"settings.cleanup.move": "移入資源回收筒({n})",
"settings.cleanup.previous": "上一頁",
"settings.cleanup.next": "下一頁",
"apps.commercial_required": "網頁應用需要 Orkas 商業版。下載商業版即可繼續。",
"apps.commercial_download": "下載商業版",
- "apps.commercial_open_failed": "無法開啟下載頁面,請重試。"
+ "apps.commercial_open_failed": "無法開啟下載頁面,請重試。",
+ "settings.cleanup.draft": "有草稿",
+ "settings.cleanup.automation": "自動化",
+ "settings.cleanup.pinned": "置頂",
+ "settings.cleanup.unavailable": "暫不可清理",
+ "settings.cleanup.unread": "未讀"
}
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 7c40d07e..bc8d5418 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -313,7 +313,6 @@
"new_chat.quick.education": "学习辅导",
"new_chat.quick.ecommerce": "电商",
"new_chat.quick.title": "试试这些任务,点一下就能跑",
- "new_chat.quick.oss_more": "接入开源工具能力",
"new_chat.quick.subtitle": "选一个具体任务,指挥官会安排合适的智能体完成",
"new_chat.quick.rnd": "开发",
"new_chat.quick.creation": "写作",
@@ -2521,8 +2520,8 @@
"new_chat.home.goal_example": "例如:调研 3 款同类产品,对比功能与定价,整理成一份演示文稿。",
"new_chat.home.explore_title": "还没想好?先让 Orkas 了解你。",
"new_chat.home.explore_body": "聊聊你的工作、生意或困扰,让 Orkas 帮你找到合适的目标,并持续推进。",
- "new_chat.home.explore_context": "用 + 分享资料,或{connect},补充背景,让 Orkas 更了解你。从你愿意分享的内容开始。",
- "new_chat.home.explore_connect_link": "连接飞书 / 钉钉 / 邮箱",
+ "new_chat.home.explore_context": "添加资料或{connect},让 Orkas 更了解你。从你愿意分享的内容开始。",
+ "new_chat.home.explore_connect_link": "连接邮箱/店铺/办公软件等",
"new_chat.home.input_placeholder": "说说你想完成什么,或附上需要处理的资料",
"new_chat.home.continue_label": "接着把事情推进",
"new_chat.home.group.todos": "重要待办",
@@ -2624,19 +2623,24 @@
"project.todo.run_busy": "这个待办所在的对话还在处理中,结束后再执行。",
"settings.cleanup.title": "清理历史任务",
"settings.cleanup.age": "最后活动时间",
- "settings.cleanup.scope": "清理项目内外的已完成任务。保留置顶、未读、有草稿的任务和自动化运行记录。",
+ "settings.cleanup.scope": "按时间筛选所有历史任务,支持按项目或逐项清理。",
"settings.cleanup.days": "{n} 天以前",
- "settings.cleanup.result": "已移入回收站 {deleted} 项,跳过 {skipped} 项,失败 {failed} 项。",
+ "settings.cleanup.result": "已回收 {deleted} · 跳过 {skipped} · 失败 {failed}",
"settings.cleanup.progress": "正在清理 {done} / {total}",
- "settings.cleanup.error": "未能完成任务加载或清理,请刷新后重试。",
+ "settings.cleanup.error": "未完成,请刷新重试。",
"settings.cleanup.count": "已选 {n} 项任务",
- "settings.cleanup.empty": "暂无可清理的历史任务。",
+ "settings.cleanup.empty": "暂无可清理任务",
"settings.cleanup.clean": "清理",
- "settings.cleanup.confirm": "将 {n} 项任务及其附件、内嵌产物移入回收站,可在下方恢复。开启同步后,删除也会同步到其他设备。清空回收站后才会释放相应磁盘空间。",
+ "settings.cleanup.confirm": "{n} 项任务及文件移入回收站,草稿删除。 运行中的任务会在清理前自动停止。",
"settings.cleanup.move": "移入回收站({n})",
"settings.cleanup.previous": "上一页",
"settings.cleanup.next": "下一页",
"apps.commercial_required": "网页应用需要 Orkas 商业版。下载商业版即可继续。",
"apps.commercial_download": "下载商业版",
- "apps.commercial_open_failed": "无法打开下载页面,请重试。"
+ "apps.commercial_open_failed": "无法打开下载页面,请重试。",
+ "settings.cleanup.draft": "有草稿",
+ "settings.cleanup.automation": "自动化",
+ "settings.cleanup.pinned": "置顶",
+ "settings.cleanup.unavailable": "暂不可清理",
+ "settings.cleanup.unread": "未读"
}
diff --git a/src/renderer/modules/connectors.js b/src/renderer/modules/connectors.js
index 4eecd2e9..aa9ad57f 100644
--- a/src/renderer/modules/connectors.js
+++ b/src/renderer/modules/connectors.js
@@ -842,9 +842,8 @@ window.focusConnectorById = async function focusConnectorById(id) {
// open_app_view/connectors/configure route arrive here. For an unconfigured
// catalog connector, continue into the same protected setup form as a card click.
// Healthy/degraded/custom connectors keep the historical focus-only behavior;
-// a reconnectable error re-enters the guided setup path. The home's connect
-// chooser passes `entryPoint='form'`: the user picked the connector there, so
-// it counts as their own connect click rather than a Commander-opened form.
+// a reconnectable error re-enters the guided setup path. Explicit form entries
+// count as user connect clicks rather than Commander-opened forms.
window.openConnectorSetupById = async function openConnectorSetupById(id, entryPoint = 'agent') {
const targetId = String(id || '').trim();
if (!targetId) return false;
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index b26217ca..8770e647 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -2272,8 +2272,6 @@ function onEnterNewChatView() {
// Keep the empty-state heading aligned with the current locale.
_refreshEmptyStateAll();
_initEmptyStateScenarios();
- // The open-source marketplace entry is rendered as one Quick task card.
- if (typeof initOssQuickTask === 'function') initOssQuickTask();
// Work to pick up (open to-dos, finished runs not yet opened); home.js.
if (typeof homeOnEnter === 'function') homeOnEnter();
}
@@ -2534,7 +2532,6 @@ function _refreshQuickStartConfig(row) {
_setQuickStartItems(items, res && res.source);
_renderQuickStartScenarios();
_bindEmptyStateScenarioButtons(row);
- if (typeof initOssQuickTask === 'function') initOssQuickTask();
})
.catch((err) => {
_convLog.warn('Commander quick-start config load failed; using open defaults', {
@@ -2814,7 +2811,6 @@ function _initEmptyStateScenarios() {
const grid = document.getElementById('new-chat-scenario-grid');
if (grid && !grid.children.length) _renderQuickStartScenarios();
_bindEmptyStateScenarioButtons(row);
- if (typeof initOssQuickTask === 'function') initOssQuickTask();
_refreshQuickStartConfig(row);
}
function onEnterConversationView() {
@@ -5563,6 +5559,8 @@ function _initNewChatAttachInput() {
let _loadConversationsInFlight = null;
let _loadConversationsMode = '';
+let _conversationRemovalRevision = 0;
+let _conversationRemovalRenderPending = false;
const _loadedConversationProjectIds = new Set();
const _conversationProjectPages = new Map();
const _projectConversationLoads = new Map();
@@ -5652,11 +5650,12 @@ async function loadConversations(options = {}) {
// explicitly when its UI genuinely needs every conversation.
const startup = !(options && options.full === true);
if (_loadConversationsInFlight) {
- if (startup || _loadConversationsMode === 'full') return _loadConversationsInFlight;
+ if (!options?.fresh && (startup || _loadConversationsMode === 'full')) return _loadConversationsInFlight;
await _loadConversationsInFlight;
return loadConversations(options);
}
_loadConversationsMode = startup ? 'startup' : 'full';
+ const removalRevision = _conversationRemovalRevision;
_loadConversationsInFlight = (async () => {
try {
const url = startup
@@ -5664,6 +5663,7 @@ async function loadConversations(options = {}) {
: '/api/conversations/list';
const res = await apiFetch(url);
const data = await res.json();
+ if (removalRevision !== _conversationRemovalRevision) return;
if (data.ok) {
_replaceConversationSlice(data.conversations, () => true);
_loadedConversationProjectIds.clear();
@@ -5733,10 +5733,12 @@ async function loadConversationProject(projectId, options = {}) {
await existing;
return loadConversationProject(pid, options);
}
+ const removalRevision = _conversationRemovalRevision;
const run = (async () => {
const offset = append ? currentPage.nextOffset : 0;
const res = await apiFetch(`/api/conversations/list?mode=project&project_id=${encodeURIComponent(pid)}&offset=${offset}`);
const data = await res.json();
+ if (removalRevision !== _conversationRemovalRevision) return;
if (!data.ok) throw new Error(data.error || 'project conversation list failed');
if (append) _appendConversationSlice(data.conversations);
else _replaceConversationSlice(data.conversations, (c) => c && c.project_id === pid);
@@ -5768,9 +5770,11 @@ async function loadUnprojectedConversations(options = {}) {
}
_unprojectedConversationPage.loading = true;
const offset = append ? _unprojectedConversationPage.nextOffset : 0;
+ const removalRevision = _conversationRemovalRevision;
const run = (async () => {
const res = await apiFetch(`/api/conversations/list?mode=unprojected&offset=${offset}`);
const data = await res.json();
+ if (removalRevision !== _conversationRemovalRevision) return;
if (!data.ok) throw new Error(data.error || 'unprojected conversation list failed');
if (append) _appendConversationSlice(data.conversations);
else _replaceConversationSlice(data.conversations, (c) => c && !c.project_id);
@@ -6262,13 +6266,38 @@ function _cancelConversationHeaderRename(cid) {
_refreshChatHeader();
}
+// All sidebar mirrors share this cache. Invalidate older in-flight list reads
+// before repainting so a successful deletion cannot be undone by a late reply.
+function _removeConversationFromSidebar(cid, { deferRender = false } = {}) {
+ _conversationRemovalRevision++;
+ const conversation = (Array.isArray(conversations) ? conversations : [])
+ .find((item) => item && item.conversation_id === cid);
+ // Most cleanup candidates are old history outside the loaded sidebar.
+ // Still invalidate older reads, but do not allocate/sort/repaint unchanged UI.
+ if (!conversation) return;
+ conversations = (Array.isArray(conversations) ? conversations : [])
+ .filter((item) => item && item.conversation_id !== cid);
+ const page = conversation.project_id ? _conversationProjectPages.get(conversation.project_id) : _unprojectedConversationPage;
+ if (page) {
+ page.total = Math.max(0, (Number(page.total) || 0) - 1);
+ if (page.nextOffset !== null) page.nextOffset = Math.max(0, page.nextOffset - 1);
+ }
+ _clearConversationInlineRenameState(cid);
+ const paint = () => {
+ _conversationRemovalRenderPending = false;
+ renderConversationList();
+ };
+ if (deferRender && typeof requestAnimationFrame === 'function') {
+ if (_conversationRemovalRenderPending) return;
+ _conversationRemovalRenderPending = true;
+ requestAnimationFrame(paint);
+ } else renderConversationList();
+}
+
async function _deleteConversationWithConfirm(cid, opts = {}) {
if (!cid) return;
if (!(await uiConfirm(t('chat.conv_del_confirm')))) return;
const startedAt = Date.now();
- const conversation = Array.isArray(conversations)
- ? conversations.find((item) => item && item.conversation_id === cid)
- : null;
abortConvStream(cid);
const projectId = _projectIdForConversation(cid);
try {
@@ -6289,26 +6318,9 @@ async function _deleteConversationWithConfirm(cid, opts = {}) {
await uiAlert(t('chat.message_delete_failed', { reason: t('chat.unknown_error') }));
return false;
}
+ _removeConversationFromSidebar(cid);
_forgetConvLocal(cid);
if (currentCid === cid) setView('new-chat');
- conversations = (Array.isArray(conversations) ? conversations : [])
- .filter((item) => item && item.conversation_id !== cid);
- if (conversation?.project_id) {
- const page = _conversationProjectPages.get(conversation.project_id);
- if (page) {
- page.total = Math.max(0, (Number(page.total) || 0) - 1);
- if (page.nextOffset !== null) page.nextOffset = Math.max(0, page.nextOffset - 1);
- }
- } else if (conversation) {
- _unprojectedConversationPage.total = Math.max(
- 0,
- (Number(_unprojectedConversationPage.total) || 0) - 1,
- );
- if (_unprojectedConversationPage.nextOffset !== null) {
- _unprojectedConversationPage.nextOffset = Math.max(0, _unprojectedConversationPage.nextOffset - 1);
- }
- }
- renderConversationList();
_logConversationManageResult('delete', startedAt, 'success');
if (typeof opts.afterDelete === 'function') {
try { await opts.afterDelete(cid); } catch (err) {
@@ -7489,6 +7501,14 @@ async function loadConversationHistory(cid, opts = {}) {
// last safe point before replacing the transcript DOM.
if (preserveScroll) scrollSnapshot = _captureHistoryReloadScroll(container);
const convMeta = data.conversation || {};
+ // Cleanup, search and Home can open history outside the loaded sidebar
+ // slice. Its history receipt already carries the persisted identity; seed
+ // the shared cache without overwriting a newer cached rename or live state.
+ if (convMeta.conversation_id === cid
+ && !conversations.some((conversation) => conversation?.conversation_id === cid)) {
+ _appendConversationSlice([convMeta]);
+ _refreshChatHeader();
+ }
if (Array.isArray(data.live_display?.active_turns)) {
convMeta.active_turns = data.live_display.active_turns;
if (convMeta.active_turns.length) {
diff --git a/src/renderer/modules/home.js b/src/renderer/modules/home.js
index f61cc556..c6a41288 100644
--- a/src/renderer/modules/home.js
+++ b/src/renderer/modules/home.js
@@ -15,8 +15,6 @@
const _homeLog = createLogger('home');
const _HOME_VISIBLE_ROWS = 3;
-// Unread runs folded under the first three; older ones stay in the sidebar.
-const _HOME_MAX_FOLDED_ROWS = 20;
// Unread runs missing from the sidebar cache are looked up by id, in batches
// of what `conversations.getMany` accepts, enough to fill both run groups.
const _HOME_LOOKUP_BATCH = 25;
@@ -24,14 +22,6 @@ const _HOME_LOOKUP_LIMIT = 50;
const _HOME_REFRESH_DEBOUNCE_MS = 500;
// A slow first lookup must not keep the greeting and Quick start invisible.
const _HOME_FIRST_PAINT_FALLBACK_MS = 1500;
-// "Connect Feishu / DingTalk / email": the connectors that hold the user's
-// work context. A legacy Lark connection counts as Feishu.
-const _HOME_CONNECT_TARGETS = [
- { id: 'feishu', instanceIds: ['feishu', 'lark'] },
- { id: 'dingtalk', instanceIds: ['dingtalk'] },
- { id: 'gmail', instanceIds: ['gmail'] },
- { id: 'm365-mail', instanceIds: ['m365-mail'] },
-];
// 'pending' only until the first visit's lookups settle; later visits keep
// the last painted state until the new lookup replaces it.
@@ -62,9 +52,9 @@ function _homeIcon(name, className) {
async function _homeLoadTodos() {
try {
- const res = await window.orkas.invoke('projects.tasks.listOpen', { limit: _HOME_VISIBLE_ROWS });
+ const res = await window.orkas.invoke('projects.tasks.listOpen', { all: true });
if (!res || res.ok === false || !Array.isArray(res.tasks)) throw new Error('invalid_response');
- const tasks = res.tasks.slice(0, _HOME_VISIBLE_ROWS);
+ const tasks = res.tasks;
return { tasks, total: Math.max(tasks.length, Math.round(Number(res.total) || 0)) };
} catch (err) {
_homeLog.warn('open to-dos unavailable for the home', { error_type: _homeErrorType(err) });
@@ -281,6 +271,9 @@ function _homeTodoRowHtml(task, index) {
}
function _homeRunRowHtml(run, section, index) {
+ // Legacy unread records default to completed for presentation only.
+ const displayStatus = ['completed', 'failed', 'waiting_input', 'stopped'].includes(run.status)
+ ? run.status : 'completed';
let source = t('new_chat.home.source.global_task');
if (section === 'automations') source = t('new_chat.home.source.automation');
else if (run.projectId) source = t('new_chat.home.source.project_task', { project: _homeProjectName(run.projectId) });
@@ -291,11 +284,11 @@ function _homeRunRowHtml(run, section, index) {
'data-home-status': run.status || 'unknown',
'data-home-position': index + 1,
},
- status: run.status,
+ status: displayStatus,
title: run.title || t('new_chat.home.untitled'),
source,
- details: [_homeResultLabel(run.status), _homeRelativeTime(run.finishedAt)],
- action: _homeRunActionLabel(run.status),
+ details: [_homeResultLabel(displayStatus), _homeRelativeTime(run.finishedAt)],
+ action: _homeRunActionLabel(displayStatus),
});
}
@@ -321,8 +314,8 @@ function _homeSectionHtml(section) {
}
let fold = '';
let footer = '';
- if (!isTodos && items.length > _HOME_VISIBLE_ROWS) {
- const folded = items.slice(_HOME_VISIBLE_ROWS, _HOME_VISIBLE_ROWS + _HOME_MAX_FOLDED_ROWS);
+ if (items.length > _HOME_VISIBLE_ROWS) {
+ const folded = items.slice(_HOME_VISIBLE_ROWS);
const expanded = _homeExpanded.has(section);
const foldId = `home-fold-${section}`;
fold = `<div class="home-list-fold" id="${foldId}"${expanded ? '' : ' hidden'}>`
@@ -360,7 +353,7 @@ function _homeRender() {
_homeApplyState(sections.length ? 'populated' : 'empty');
}
-/** The empty state's "share files, or connect Feishu / DingTalk / email" line;
+/** The empty state's "add materials or connect your services" line;
* the connect phrase is a button inside the translated sentence. */
function _homeRenderExploreContext() {
const el = document.getElementById('home-explore-context');
@@ -457,51 +450,6 @@ function _homeOnGroupsClick(event) {
else if (row.dataset.homeCid) _homeOpenRun(row);
}
-/** Context menus open below their trigger, or above it near the window bottom. */
-function _homeMenuAnchor(el) {
- const rect = el.getBoundingClientRect();
- const below = window.innerHeight - rect.bottom > 320;
- return { clientX: rect.left, clientY: below ? rect.bottom + 4 : rect.top - 4 };
-}
-
-function _homeConnect(id) {
- setView('connectors', null, { entryPoint: 'home' });
- if (typeof window.openConnectorSetupById !== 'function') return;
- Promise.resolve(window.openConnectorSetupById(id, 'form')).catch((err) => {
- _homeLog.warn('connector setup from the home failed', { error_type: _homeErrorType(err) });
- });
-}
-
-async function _homeOpenConnectChooser(button) {
- if (typeof showContextMenu !== 'function') return;
- const anchor = _homeMenuAnchor(button);
- const connected = new Set();
- try {
- const res = await window.orkas.invoke('connectors.list', {});
- for (const inst of (res && Array.isArray(res.instances) ? res.instances : [])) {
- if (inst && inst.status && inst.status.kind === 'connected') connected.add(inst.id);
- }
- } catch (err) {
- _homeLog.warn('connector states unavailable for the home', { error_type: _homeErrorType(err) });
- }
- const items = [];
- for (const target of _HOME_CONNECT_TARGETS) {
- let name = target.id;
- try {
- const nav = typeof window.loadConnectorNavTarget === 'function'
- ? await window.loadConnectorNavTarget(target.id)
- : null;
- if (nav && nav.name) name = nav.name;
- } catch (_) {}
- const isConnected = target.instanceIds.some((id) => connected.has(id));
- items.push({
- label: isConnected ? `${name} · ${t('connectors.group.connected')}` : name,
- onClick: () => _homeConnect(target.id),
- });
- }
- showContextMenu(anchor, items);
-}
-
// ── Lifecycle ───────────────────────────────────────────────────────────
function _homeBind() {
@@ -512,7 +460,9 @@ function _homeBind() {
const link = event.target && typeof event.target.closest === 'function'
? event.target.closest('[data-home-connect]')
: null;
- if (link) void _homeOpenConnectChooser(link);
+ if (link) {
+ setView('connectors', null, { entryPoint: 'home' });
+ }
});
window.addEventListener('task-unread-change', homeRefresh);
window.addEventListener('i18n-change', () => {
diff --git a/src/renderer/modules/oss.js b/src/renderer/modules/oss.js
index ab088a6f..cc4eb025 100644
--- a/src/renderer/modules/oss.js
+++ b/src/renderer/modules/oss.js
@@ -388,36 +388,7 @@ function _ossPromptForComposer(p, input) {
return `${prompt}\n\n${existing}`;
}
-function _openOssMarketplace() {
- const load = typeof loadRendererFeature === 'function' ? loadRendererFeature : window.loadRendererFeature;
- if (typeof load !== 'function') {
- _ossLog.warn('Commander OSS quick task failed: marketplace loader unavailable');
- return;
- }
- load('marketplace').then(() => openMarketplace('oss', {
- returnView: 'new-chat',
- preserveReturnTab: true,
- })).catch((err) => {
- _ossLog.warn('Commander OSS quick task failed to load marketplace', {
- error: err && err.message ? err.message : String(err || ''),
- });
- });
-}
-
-/** Bind the quick-start header's open-source entry — the single path from the
- * landing page into the marketplace「开源项目」list. */
-function initOssQuickTask() {
- const link = document.getElementById('quick-panel-oss-more');
- if (!link || link.dataset.bound === '1') return;
- link.dataset.bound = '1';
- link.addEventListener('click', _openOssMarketplace);
-}
-
-window.addEventListener('i18n-change', () => {
- initOssQuickTask();
-});
-
-// Exposed for marketplace.js rendering + conversation.js Quick task init.
+// Exposed for marketplace rendering.
window.loadOssCatalog = loadOssCatalog;
window.ossCatalogCacheKey = ossCatalogCacheKey;
window.OSS_MARKETPLACE_PAGE_SIZE = OSS_MARKETPLACE_PAGE_SIZE;
@@ -434,4 +405,3 @@ window.ossInstallPromptFor = ossInstallPromptFor;
window.ossOpenRepo = ossOpenRepo;
window.prefillCommander = prefillCommander;
window.unresolvedOssTemplatePlaceholder = unresolvedOssTemplatePlaceholder;
-window.initOssQuickTask = initOssQuickTask;
diff --git a/src/renderer/modules/task-cleanup.js b/src/renderer/modules/task-cleanup.js
index bc82b762..2fbdf339 100644
--- a/src/renderer/modules/task-cleanup.js
+++ b/src/renderer/modules/task-cleanup.js
@@ -1,48 +1,80 @@
-/* Inline Settings > Data cleanup. Preview receipts belong to one account;
- * selection stays frozen while confirming and executing. */
+/* Settings-only history cleanup. Selection belongs to a frozen account receipt;
+ * project-wide choices include unloaded pages without hydrating task history. */
(() => {
- let owner = '', days = 90, token = '', total = 0, rows = [], offset = 0, nextOffset = null;
+ let owner = '', days = 30, token = '', total = 0, selectableTotal = 0;
+ let entries = [], offset = 0, nextOffset = null, treeTotal = 0;
let expanded = false, confirming = false, busy = false, loading = false, stopped = false;
- let allSelected = true, excluded = new Set(), result = null, failed = [], error = false, picker = null, bound = false;
+ let allSelected = false, result = null, failed = [], error = false, picker = null, bound = false;
+ let returnTarget = null;
+ const projectChoices = new Map(), itemChoices = new Map(), projects = new Map(), knownRows = new Map(), projectViews = new Map();
+ const removed = new Set(), removedByProject = new Map();
const log = createLogger('task-cleanup');
const user = () => typeof currentUserId === 'string' ? currentUserId : '';
const body = () => document.getElementById('settings-task-cleanup-body');
- const selectedCount = () => allSelected ? total - excluded.size : excluded.size;
- const isSelected = cid => allSelected !== excluded.has(cid);
+ const backButton = () => document.getElementById('chat-cleanup-back');
+ window.TaskCleanupNavigation = {
+ beforeNavigate(view, cid, opts = {}) {
+ const valid = returnTarget && returnTarget.owner === user();
+ const restore = !!(valid && opts.restoreTaskCleanup && view === 'settings'
+ && currentView === 'conversation' && currentCid === returnTarget.cid);
+ if (!valid || view !== 'conversation' || cid !== returnTarget.cid) returnTarget = null;
+ if (backButton()) backButton().hidden = !returnTarget;
+ return restore;
+ },
+ back() {
+ const saved = returnTarget;
+ if (!saved || saved.owner !== user() || currentView !== 'conversation' || currentCid !== saved.cid) {
+ returnTarget = null;
+ if (backButton()) backButton().hidden = true;
+ return;
+ }
+ setView('settings', null, { restoreTaskCleanup: true });
+ // Reuse the mounted receipt: revisiting Settings normally refreshes it,
+ // which would discard the user's selection, expanded projects and page.
+ for (const { element, top } of saved.scroll) element.scrollTop = top;
+ const buttons = body()?.querySelectorAll?.('[data-cleanup-action="open"]') || [];
+ for (const button of buttons) if (button.dataset.cleanupOwner === saved.cid) {
+ button.focus({ preventScroll: true }); break;
+ }
+ },
+ };
+ const baseSelected = row => projectChoices.get(row.projectId)?.selected ?? allSelected;
+ const isSelected = row => !removed.has(row.cid) && !!row.selectable && (itemChoices.get(row.cid)?.selected ?? baseSelected(row));
+ function selectionCounts() {
+ let count = allSelected ? selectableTotal : 0;
+ const perProject = new Map();
+ for (const [pid, p] of projects) perProject.set(pid, (projectChoices.get(pid)?.selected ?? allSelected) ? p.selectableTotal : 0);
+ for (const choice of projectChoices.values()) count += (Number(choice.selected) - Number(allSelected)) * choice.total;
+ for (const { row, selected } of itemChoices.values()) {
+ const delta = Number(selected) - Number(baseSelected(row));
+ count += delta;
+ if (row.projectId) perProject.set(row.projectId, (perProject.get(row.projectId) || 0) + delta);
+ }
+ return { count, perProject };
+ }
+ const selectedCount = () => selectionCounts().count;
const aliases = { retry: 'chat.retry_btn', stop: 'chat.task_stop', loading: 'common.loading', refresh: 'common.refresh', view: 'settings.recycle.view', collapse: 'settings.recycle.collapse', cancel: 'common.cancel', confirm_title: 'settings.cleanup.title' };
const tr = (key, values) => key === 'all' ? `${t('chat.message_select_all')} (${values.n})`
- : key === 'page' ? `${values.from}–${values.to} / ${values.n}`
- : t(aliases[key] || `settings.cleanup.${key}`, values);
+ : key === 'page' ? `${values.from}–${values.to} / ${values.n}` : t(aliases[key] || `settings.cleanup.${key}`, values);
const esc = value => escapeHtml(String(value));
- const button = (action, label, disabled = false, danger = false) =>
- `<button type="button" class="btn btn-sm${danger ? ' btn-danger' : ''}" data-cleanup-action="${action}"${disabled ? ' disabled' : ''}>${esc(label)}</button>`;
- const options = () => [30, 90, 180].map(n => ({ value: String(n), label: tr('days', { n }) }));
- function protectedIds() {
- const ids = new Set((window.TaskUnread?.list?.() || []).map(row => row.cid));
- // Drafts are owned by the composer and may belong to unloaded task pages.
- // Storage failure blocks cleanup rather than treating unknown as empty.
+ const button = (action, label, disabled = false, danger = false, projectId = '') =>
+ `<button type="button" class="btn btn-sm${danger ? ' btn-danger' : ''}" data-cleanup-action="${action}" data-cleanup-owner="${esc(projectId)}"${disabled ? ' disabled' : ''}>${esc(label)}</button>`;
+ const options = () => [7, 14, 30, 60, 90, 180].map(n => ({ value: String(n), label: tr('days', { n }) }));
+ function draftIds() {
+ const ids = new Set();
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const match = /^draft_([A-Za-z0-9_-]+)(:queue-edit)?$/.exec(key || '');
if (!match) continue;
- const raw = localStorage.getItem(key);
- if (!raw) continue;
+ const raw = localStorage.getItem(key); if (!raw) continue;
let draft;
try { draft = JSON.parse(raw); } catch (_) { ids.add(match[1]); continue; }
- if (match[2] || draft?.text?.trim() || draft?.references?.length) ids.add(match[1]);
- }
- if (typeof _chatAttachments !== 'undefined') {
- for (const [cid, items] of _chatAttachments) if (items.length) ids.add(cid);
+ if (match[2] || draft?.text?.trim() || draft?.references?.length || draft?.attachments?.length) ids.add(match[1]);
}
- if (typeof currentCid === 'string' && currentCid && typeof _composerHoldsUnsentInput === 'function'
- && _composerHoldsUnsentInput(currentCid)) ids.add(currentCid);
+ if (typeof _chatAttachments !== 'undefined') for (const [cid, items] of _chatAttachments) if (items.length) ids.add(cid);
+ if (typeof currentCid === 'string' && currentCid && typeof _composerHoldsUnsentInput === 'function' && _composerHoldsUnsentInput(currentCid)) ids.add(currentCid);
return [...ids].filter(cid => /^[A-Za-z0-9_-]+$/.test(cid));
}
- function protectedNow(cid) {
- return window.TaskUnread?.isUnread?.(cid)
- || (typeof _composerHoldsUnsentInput === 'function' && _composerHoldsUnsentInput(cid))
- || (typeof _chatAttachList === 'function' && _chatAttachList(cid).length);
- }
async function invoke(action, payload) {
if (!owner || owner !== user()) throw new Error('cleanup_account_changed');
const expectedOwner = owner;
@@ -51,31 +83,85 @@
if (!response || response.ok !== true) throw new Error('cleanup_failed');
return response;
}
+ function remember(items) {
+ for (const row of items) {
+ if (row.type === 'project') {
+ const count = removedByProject.get(row.projectId) || 0;
+ projects.set(row.projectId, { ...row, total: row.total - count, selectableTotal: row.selectableTotal - count });
+ } else if (!removed.has(row.cid)) knownRows.set(row.cid, row);
+ }
+ }
+ function forgetCompleted(cid) {
+ const row = knownRows.get(cid);
+ if (!row || removed.has(cid)) return;
+ removed.add(cid); knownRows.delete(cid); itemChoices.delete(cid);
+ total--; selectableTotal--;
+ if (row.projectId) {
+ removedByProject.set(row.projectId, (removedByProject.get(row.projectId) || 0) + 1);
+ const project = projects.get(row.projectId), choice = projectChoices.get(row.projectId);
+ if (project) { project.total--; project.selectableTotal--; }
+ if (choice) choice.total--;
+ }
+ }
+ function resetSelection() { allSelected = false; projectChoices.clear(); itemChoices.clear(); }
+ function checkbox(attr, count, available, disabled = false, label = '') {
+ return `<input type="checkbox" ${attr} aria-label="${esc(label)}"${count && count === available ? ' checked' : ''}${count && count < available ? ' data-cleanup-mixed' : ''}${disabled || !available ? ' disabled' : ''}>`;
+ }
+ function taskRow(row, nested, drafts) {
+ if (removed.has(row.cid)) return '';
+ const labels = [];
+ if (row.pinned) labels.push(tr('pinned'));
+ if (window.TaskUnread?.isUnread?.(row.cid)) labels.push(tr('unread'));
+ if (row.draft || drafts.has(row.cid)) labels.push(tr('draft'));
+ if (row.automation) labels.push(tr('automation'));
+ return `<label class="settings-cleanup-item${nested ? ' is-nested' : ''}">${checkbox(`data-cleanup-cid="${esc(row.cid)}"`, Number(isSelected(row)), Number(row.selectable), confirming, row.title)}<span class="settings-cleanup-copy"><span class="settings-cleanup-title" title="${esc(row.title)}">${esc(row.title)}</span>${labels.map(label => `<span class="settings-cleanup-tag">${esc(label)}</span>`).join('')}</span><span class="settings-cleanup-meta">${row.blocked === 'unknown' ? `<span>${esc(tr('unavailable'))}</span>` : ''}<button type="button" class="settings-link-btn settings-cleanup-open" data-cleanup-action="open" data-cleanup-owner="${esc(row.cid)}"${confirming ? ' disabled' : ''}>${esc(tr('view'))}</button><time>${esc(new Date(row.activeAt).toLocaleDateString())}</time></span></label>`;
+ }
+ function pagination(start, length, size, next, projectId = '') {
+ if (start === 0 && next === null) return '';
+ return `<div class="settings-sheet-foot"><span>${esc(tr('page', { from: start + 1, to: start + length, n: size }))}</span><div class="settings-cleanup-actions">${button('previous', tr('previous'), start === 0 || confirming, false, projectId)}${button('next', tr('next'), next === null || confirming, false, projectId)}</div></div>`;
+ }
function render() {
const host = body(); if (!host) return;
- picker?.setOptions(options(), { value: String(days) });
- picker?.setAriaLabel(tr('age'));
+ const scroll = host.querySelector?.('.settings-cleanup-list')?.scrollTop || 0;
+ const focused = document.activeElement;
+ const focusAttr = ['data-cleanup-cid', 'data-cleanup-project', 'data-cleanup-action'].find(key => focused?.hasAttribute?.(key));
+ const focusValue = focusAttr ? focused.getAttribute(focusAttr) : null;
+ const focusOwner = focused?.getAttribute?.('data-cleanup-owner') || '';
+ picker?.setOptions(options(), { value: String(days) }); picker?.setAriaLabel(tr('age'));
const trigger = document.getElementById('settings-task-cleanup-age')?.querySelector?.('.ai-select-trigger');
if (trigger) trigger.disabled = busy || loading || confirming;
- const selected = Math.max(0, selectedCount());
+ const { count: selected, perProject } = selectionCounts();
let html = '';
- if (result && !busy) html += `<div class="settings-row" role="status"><span class="settings-row-desc">${esc(tr('result', result))}</span>${failed.length && !busy ? button('retry', tr('retry')) : ''}</div>`;
- if (busy) {
- html += `<div class="settings-row" role="status"><span>${esc(tr('progress', { done: result.done, total: result.total }))}</span>${button('stop', tr('stop'), stopped)}</div>`;
- } else if (loading) {
- html += `<div class="settings-row" role="status">${esc(tr('loading'))}</div>`;
- } else if (error) {
- html += `<div class="settings-row" role="alert"><span class="settings-row-desc">${esc(tr('error'))}</span>${button('refresh', tr('refresh'))}</div>`;
- } else {
- html += `<div class="settings-row"><span class="settings-row-desc" role="status">${esc(total ? tr('count', { n: selected }) : tr('empty'))}</span><div class="settings-cleanup-actions">${total ? button('view', tr(expanded ? 'collapse' : 'view'), confirming) : ''}${button('prepare', tr('clean'), !selected || confirming, true)}</div></div>`;
+ if (busy) html += `<div class="settings-row" role="status"><span class="settings-row-desc">${esc(tr('progress', { done: result.done, total: result.total }))}</span>${button('stop', tr('stop'), stopped)}</div>`;
+ else if (loading) html += `<div class="settings-row" role="status">${esc(tr('loading'))}</div>`;
+ else if (error) html += `<div class="settings-row" role="alert"><span class="settings-row-desc">${esc(tr('error'))}${result ? ' ' + esc(tr('result', result)) : ''}</span><div class="settings-cleanup-actions">${failed.length ? button('retry', tr('retry')) : ''}${button('refresh', tr('refresh'))}</div></div>`;
+ else {
+ if (confirming) html += `<div class="settings-row" role="group" aria-label="${esc(tr('confirm_title'))}"><span class="settings-row-desc">${esc(tr('confirm', { n: selected }))}</span><div class="settings-cleanup-actions">${button('cancel', tr('cancel'))}${button('confirm', tr('move', { n: selected }), !selected, true)}</div></div>`;
+ else html += `<div class="settings-row"><div class="settings-cleanup-copy">${total ? `<label class="settings-cleanup-select-all">${checkbox('data-cleanup-all', selected, selectableTotal, false, tr('all', { n: total }))}<span>${esc(tr('all', { n: total }))}</span></label>` : ''}${result || !total ? `<span class="settings-row-desc" role="status">${esc(result ? tr('result', result) : tr('empty'))}</span>` : ''}</div><div class="settings-cleanup-actions">${failed.length ? button('retry', tr('retry')) : ''}${total ? button('view', tr(expanded ? 'collapse' : 'view')) : ''}${button('prepare', `${tr('clean')} (${selected})`, !selected, true)}</div></div>`;
if (expanded && total) {
- html += `<div class="settings-cleanup-list"><label class="settings-cleanup-item"><input type="checkbox" data-cleanup-all${selectedCount() === total ? ' checked' : ''}${confirming ? ' disabled' : ''}><span>${esc(tr('all', { n: total }))}</span></label>`;
- for (const row of rows) html += `<label class="settings-cleanup-item"><input type="checkbox" data-cleanup-cid="${esc(row.cid)}"${isSelected(row.cid) ? ' checked' : ''}${confirming ? ' disabled' : ''}><span class="settings-cleanup-title">${esc(row.title)}</span><time class="settings-row-desc">${esc(new Date(row.activeAt).toLocaleDateString())}</time></label>`;
- html += `</div><div class="settings-sheet-foot"><span>${esc(tr('page', { from: offset + 1, to: offset + rows.length, n: total }))}</span><div class="settings-cleanup-actions">${button('previous', tr('previous'), offset === 0 || confirming)}${button('next', tr('next'), nextOffset === null || confirming)}</div></div>`;
+ const drafts = new Set(draftIds());
+ html += '<div class="settings-cleanup-list">';
+ for (const item of entries) {
+ if (item.type !== 'project') { html += taskRow(item, false, drafts); continue; }
+ const pid = item.projectId, entry = projects.get(pid);
+ if (!entry.total) continue;
+ const view = projectViews.get(pid);
+ const icon = 'folder';
+ html += `<div class="settings-cleanup-project" data-cleanup-group="${esc(pid)}"><div class="settings-cleanup-project-head">${checkbox(`data-cleanup-project="${esc(pid)}"`, perProject.get(pid) || 0, entry.selectableTotal, confirming, entry.title)}<button type="button" class="settings-cleanup-project-toggle" data-cleanup-action="project" data-cleanup-owner="${esc(pid)}" aria-expanded="${!!view?.open}"${confirming ? ' disabled' : ''}><span data-ui-icon="${icon}" aria-hidden="true"></span><span class="settings-cleanup-title">${esc(entry.title)}</span><span data-ui-icon="${view?.open ? 'chevron-down' : 'chevron-right'}" aria-hidden="true"></span></button><span class="settings-row-desc">${esc(perProject.get(pid) ? `${perProject.get(pid)} / ${entry.total}` : entry.total)}</span></div>`;
+ if (view?.open) html += view.rows.map(row => taskRow(row, true, drafts)).join('') + pagination(view.offset, view.rows.length, entry.total, view.nextOffset, pid);
+ html += '</div>';
+ }
+ html += '</div>' + pagination(offset, entries.length, treeTotal, nextOffset);
}
- if (confirming) html += `<div class="settings-row settings-row-stack" role="group" aria-label="${esc(tr('confirm_title'))}"><p class="settings-row-desc">${esc(tr('confirm', { n: selected }))}</p><div class="settings-cleanup-actions">${button('cancel', tr('cancel'))}${button('confirm', tr('move', { n: selected }), !selected, true)}</div></div>`;
}
host.innerHTML = html;
+ window.hydrateUiIcons?.(host);
+ host.querySelectorAll?.('[data-cleanup-mixed]').forEach(el => { el.indeterminate = true; });
+ const list = host.querySelector?.('.settings-cleanup-list'); if (list) list.scrollTop = scroll;
+ if (focusAttr) {
+ const candidates = host.querySelectorAll?.(`[${focusAttr}]`) || [];
+ for (const el of candidates) if (el.getAttribute(focusAttr) === focusValue && (el.getAttribute('data-cleanup-owner') || '') === focusOwner) { el.focus({ preventScroll: true }); break; }
+ }
}
async function refresh(keepResult = false) {
if (busy || loading) return;
@@ -83,44 +169,47 @@
if (!keepResult) { result = null; failed = []; }
render();
try {
- const p = await invoke('preview', { days, protectedIds: protectedIds() });
- if (!Array.isArray(p.rows) || !Number.isSafeInteger(p.total) || typeof p.token !== 'string') throw new Error('invalid_preview');
- token = p.token; total = p.total; rows = p.rows; offset = 0; nextOffset = p.nextOffset; excluded = new Set(); allSelected = true;
- } catch (_) { error = true; token = ''; total = 0; rows = []; }
+ const p = await invoke('preview', { days, draftIds: draftIds() });
+ if (!Array.isArray(p.entries) || !Number.isSafeInteger(p.total) || !Number.isSafeInteger(p.selectableTotal) || typeof p.token !== 'string') throw new Error('invalid_preview');
+ token = p.token; total = p.total; selectableTotal = p.selectableTotal; entries = p.entries; offset = 0;
+ nextOffset = p.treeNextOffset; treeTotal = p.treeTotal;
+ projects.clear(); knownRows.clear(); projectViews.clear(); removed.clear(); removedByProject.clear(); resetSelection(); remember(entries);
+ } catch (_) { error = true; token = ''; total = 0; selectableTotal = 0; entries = []; resetSelection(); }
finally { loading = false; render(); }
}
- async function changePage(next) {
+ async function changePage(next, projectId = '') {
if (loading || busy || confirming) return;
- loading = true; render();
+ loading = true;
try {
- const p = await invoke('page', { token, offset: next });
- rows = p.rows; offset = next; nextOffset = p.nextOffset;
+ const p = await invoke('page', { token, offset: next, ...(projectId ? { projectId } : { tree: true }) });
+ if (projectId) { remember(p.rows); projectViews.set(projectId, { rows: p.rows, offset: next, nextOffset: p.nextOffset, open: true }); }
+ else { entries = p.entries; remember(entries); offset = next; nextOffset = p.nextOffset; treeTotal = p.listTotal; }
} catch (_) { error = true; }
finally { loading = false; render(); }
}
async function run(retry = false) {
if (busy || loading || owner !== user() || (!retry && !confirming)) return;
busy = true; confirming = false; stopped = false; error = false;
- const operationOwner = owner;
- const retryIds = failed.slice(); failed = [];
- result = { deleted: 0, skipped: 0, failed: 0, done: 0, total: retry ? retryIds.length : selectedCount() };
- render();
+ const operationOwner = owner, retryIds = failed.slice(); failed = [];
+ result = { deleted: 0, skipped: 0, failed: 0, done: 0, total: retry ? retryIds.length : selectedCount() }; render();
try {
- // Page the frozen receipt, never a live query that could add new tasks.
let next = 0;
do {
- const p = retry ? { rows: retryIds.map(cid => ({ cid })), nextOffset: null }
- : await invoke('page', { token, offset: next });
+ const p = retry ? { rows: retryIds.map(cid => ({ cid })), nextOffset: null } : await invoke('page', { token, offset: next });
for (const row of p.rows) {
if (stopped || operationOwner !== user()) break;
- if (!retry && !isSelected(row.cid)) continue;
+ if (!retry && !isSelected(row)) continue;
+ if (!retry) knownRows.set(row.cid, row);
try {
- if (protectedNow(row.cid)) { result.skipped++; }
- else {
- const response = await invoke('remove', { token, cid: row.cid });
- if (!['deleted', 'skipped'].includes(response.status)) throw new Error('invalid_cleanup_result');
- result[response.status]++;
- if (response.status === 'deleted' && typeof _forgetConvLocal === 'function') _forgetConvLocal(row.cid);
+ const response = await invoke('remove', { token, cid: row.cid });
+ if (!['deleted', 'skipped'].includes(response.status)) throw new Error('invalid_cleanup_result');
+ result[response.status]++;
+ if (response.status === 'deleted') {
+ forgetCompleted(row.cid);
+ _removeConversationFromSidebar(row.cid, { deferRender: true });
+ if (typeof _chatAttachClear === 'function') await _chatAttachClear(row.cid);
+ if (typeof _forgetConvLocal === 'function') _forgetConvLocal(row.cid);
+ if (typeof _forgetUnreadConversation === 'function') _forgetUnreadConversation(row.cid);
}
} catch (_) { result.failed++; failed.push(row.cid); }
result.done++; render();
@@ -132,50 +221,62 @@
busy = false;
if (operationOwner === user()) {
window.initRecycleBin?.();
- if (typeof loadConversations === 'function') {
- try { await loadConversations(); } catch (_) { log.warn('cleanup navigation refresh failed'); }
- }
- // Preserve the receipt for failed-only retries. A fresh filter or
- // explicit refresh creates a new receipt after the user sees results.
- if (!failed.length && !error) await refresh(true);
- else render();
- } else { owner = ''; token = ''; total = 0; rows = []; result = null; failed = []; render(); }
+ if (typeof loadConversations === 'function') try { await loadConversations({ fresh: true }); } catch (_) { log.warn('cleanup navigation refresh failed'); }
+ if (!failed.length && !error) await refresh(true); else render();
+ } else { owner = ''; token = ''; total = 0; selectableTotal = 0; entries = []; result = null; failed = []; resetSelection(); render(); }
}
}
async function click(event) {
- const action = event.target.closest('[data-cleanup-action]')?.dataset.cleanupAction;
+ const target = event.target.closest('[data-cleanup-action]');
+ const action = target?.dataset.cleanupAction, pid = target?.dataset.cleanupOwner || '';
if (action === 'stop') { stopped = true; render(); return; }
if (busy || loading) return;
+ if (action === 'cancel') { confirming = false; render(); body().querySelector('[data-cleanup-action="prepare"]')?.focus(); return; }
+ if (action === 'confirm') { await run(); return; }
+ if (confirming) return;
+ if (action === 'open') {
+ event.preventDefault();
+ if (owner === user() && knownRows.has(pid)) {
+ const scroll = [document.querySelector('#panel-settings .settings-body'), body()?.querySelector('.settings-cleanup-list')]
+ .filter(Boolean).map(element => ({ element, top: element.scrollTop }));
+ returnTarget = { owner, cid: pid, scroll };
+ setView('conversation', pid);
+ }
+ return;
+ }
if (action === 'view') { expanded = !expanded; render(); }
+ if (action === 'project' && projects.has(pid)) {
+ const view = projectViews.get(pid);
+ if (view) { view.open = !view.open; render(); } else await changePage(0, pid);
+ }
if (action === 'prepare' && token && selectedCount() > 0) { confirming = true; render(); body().querySelector('[data-cleanup-action="cancel"]')?.focus(); }
- if (action === 'cancel') { confirming = false; render(); body().querySelector('[data-cleanup-action="prepare"]')?.focus(); }
- if (action === 'confirm') await run();
if (action === 'retry') await run(true);
if (action === 'refresh') await refresh();
- if (action === 'previous') await changePage(Math.max(0, offset - 20));
- if (action === 'next' && nextOffset !== null) await changePage(nextOffset);
+ if (action === 'previous') await changePage(Math.max(0, (pid ? projectViews.get(pid)?.offset || 0 : offset) - 20), pid);
+ const next = pid ? projectViews.get(pid)?.nextOffset : nextOffset;
+ if (action === 'next' && next != null) await changePage(next, pid);
}
- async function change(event) {
+ function change(event) {
if (busy || loading || confirming) return;
- const cid = event.target.getAttribute('data-cleanup-cid');
+ const el = event.target, cid = el.getAttribute('data-cleanup-cid'), pid = el.getAttribute('data-cleanup-project');
if (cid) {
- if (event.target.checked === allSelected) excluded.delete(cid); else excluded.add(cid);
- } else if (event.target.hasAttribute('data-cleanup-all')) {
- allSelected = event.target.checked; excluded.clear();
- }
+ const row = knownRows.get(cid); if (!row?.selectable) return;
+ if (el.checked === baseSelected(row)) itemChoices.delete(cid); else itemChoices.set(cid, { row, selected: el.checked });
+ } else if (pid && projects.has(pid)) {
+ projectChoices.set(pid, { selected: el.checked, total: projects.get(pid).selectableTotal });
+ for (const [id, choice] of itemChoices) if (choice.row.projectId === pid) itemChoices.delete(id);
+ } else if (el.hasAttribute('data-cleanup-all')) { allSelected = el.checked; projectChoices.clear(); itemChoices.clear(); }
render();
}
-
window.initTaskCleanup = async function () {
if (!body() || !user()) return;
if (!bound) {
body().addEventListener('click', click); body().addEventListener('change', change); bound = true;
- picker = _aiSelectMount(document.getElementById('settings-task-cleanup-age'), {
- options: options(), value: String(days), ariaLabel: tr('age'),
- });
+ backButton()?.addEventListener('click', () => window.TaskCleanupNavigation.back());
+ picker = _aiSelectMount(document.getElementById('settings-task-cleanup-age'), { options: options(), value: String(days), ariaLabel: tr('age') });
picker.onChange(value => { if (!busy && !loading && !confirming) { days = Number(value); refresh(); } });
}
- if (owner !== user()) { owner = user(); token = ''; excluded.clear(); result = null; failed = []; confirming = false; }
+ if (owner !== user()) { owner = user(); token = ''; resetSelection(); result = null; failed = []; confirming = false; }
if (!busy && !loading && !confirming) await refresh();
};
window.addEventListener('i18n-change', render);
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 1c7b13cf..777cca31 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -5261,26 +5261,6 @@ html[dir="rtl"] .home-row-action-icon { transform: scaleX(-1); }
flex: 1;
background: var(--border);
}
-.quick-panel-more {
- min-height: 26px;
- padding: 0 5px 0 7px;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 2px;
- flex: none;
- white-space: nowrap;
- font-size: 11px;
- font-weight: 500;
- color: var(--text-2);
- background: transparent;
- border: none;
- border-radius: 7px;
- cursor: pointer;
-}
-.quick-panel-more:hover { background: var(--surface-2); color: var(--text); }
-.quick-panel-more-arrow,
-.quick-panel-more-arrow svg { width: 13px; height: 13px; }
.quick-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
@@ -5378,14 +5358,6 @@ html[dir="rtl"] .home-row-action-icon { transform: scaleX(-1); }
font-weight: 600;
}
#panel-new-chat .new-chat-scenarios { padding-top: 8px; }
-#panel-new-chat .quick-panel-more {
- min-height: 28px;
- padding: 4px 0 4px 8px;
-}
-#panel-new-chat .quick-panel-more:hover {
- background: transparent;
- color: var(--primary-text);
-}
#panel-new-chat .quick-grid {
gap: 12px;
margin-top: 12px;
@@ -5540,6 +5512,8 @@ html[dir="rtl"] .home-row-action-icon { transform: scaleX(-1); }
flex: 1;
min-width: 0;
}
+#chat-cleanup-back { flex-shrink: 0; }
+#chat-cleanup-back[hidden] { display: none; }
.chat-header-title-row {
display: flex;
align-items: center;
@@ -11411,7 +11385,13 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.contexts-project-select .ai-select-label > span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#contexts-project-select-listbox { min-width: 220px; }
.contexts-project-select .ai-select-option-icon,
+#auto-project-select .ai-select-option-icon,
+#project-todo-project .ai-select-option-icon,
+#auto-project-select-listbox .ai-select-option-icon,
+#project-todo-project-listbox .ai-select-option-icon,
#contexts-project-select-listbox .ai-select-option-icon { color: var(--muted); }
+#auto-project-select-listbox .ai-select-item.active .ai-select-option-icon,
+#project-todo-project-listbox .ai-select-item.active .ai-select-option-icon,
#contexts-project-select-listbox .ai-select-item.active .ai-select-option-icon { color: var(--primary-text); }
.contexts-tree .skill-tree-node {
font-size: 13px;
@@ -14548,7 +14528,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.settings-project-usage-item:hover:not(:disabled) { background: var(--surface-2); border-color: var(--border-strong); }
.settings-project-usage-item:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
.settings-project-usage-item:disabled { cursor: default; }
-.settings-project-usage-icon { display: flex; flex: 0 0 auto; color: var(--primary); font-size: 17px; }
+.settings-project-usage-icon { display: flex; flex: 0 0 auto; color: var(--text-2); font-size: 17px; }
.settings-project-usage-name { flex: 1; min-width: 0; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.settings-project-usage-count { flex: 0 0 auto; color: var(--text-2); font-size: 12px; font-variant-numeric: tabular-nums; }
.settings-recycle-body {
@@ -14771,17 +14751,37 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
#settings-task-cleanup-age { flex: 0 0 160px; }
#settings-task-cleanup-body > .settings-row,
#settings-task-cleanup-body > .settings-cleanup-list { border-top: 1px solid var(--border); }
-.settings-cleanup-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
-.settings-cleanup-list { max-height: 300px; overflow-y: auto; padding: 8px 18px; }
-.settings-cleanup-item { display: flex; align-items: center; gap: 10px; padding: 10px 0; font-size: 13px; }
-.settings-cleanup-item + .settings-cleanup-item { border-top: 1px solid var(--border); }
-.settings-cleanup-item input { flex: 0 0 auto; accent-color: var(--primary); }
-.settings-cleanup-title { flex: 1; min-width: 0; overflow-wrap: anywhere; font-size: 13px; }
-.settings-cleanup-item time { flex: 0 0 auto; }
+#settings-task-cleanup-body > .settings-row { flex-wrap: nowrap; }
+#settings-task-cleanup-body > .settings-row > .settings-row-desc { flex: 1; min-width: 0; }
+.settings-cleanup-actions { display: flex; flex: 0 0 auto; justify-content: flex-end; gap: 8px; }
+.settings-cleanup-list { max-height: 420px; overflow-y: auto; padding: 0 18px; }
+.settings-cleanup-item, .settings-cleanup-project-head { display: flex; align-items: center; gap: 10px; padding: 10px 0; font-size: 13px; min-width: 0; }
+.settings-cleanup-item + .settings-cleanup-item,
+.settings-cleanup-list > * + * { border-top: 1px solid var(--border); }
+.settings-cleanup-item.is-nested { margin-inline-start: 28px; }
+.settings-cleanup-select-all { flex: 0 0 auto; white-space: nowrap; display: inline-flex; align-items: center; gap: 10px; font-size: 13px; }
+.settings-cleanup-item input, .settings-cleanup-project-head input,
+.settings-cleanup-select-all input { flex: 0 0 auto; accent-color: var(--primary); }
+.settings-cleanup-copy { display: flex; align-items: center; gap: 6px; flex: 1; min-width: 0; }
+.settings-cleanup-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; }
+.settings-cleanup-tag { flex: 0 0 auto; padding: 2px 6px; border-radius: var(--radius-sm); background: var(--surface-2); color: var(--text-2); font-size: 11px; white-space: nowrap; }
+.settings-cleanup-meta { display: inline-flex; align-items: center; gap: 8px; flex: 0 0 auto; color: var(--text-2); font-size: 12px; }
+.settings-cleanup-meta time { white-space: nowrap; font-variant-numeric: tabular-nums; }
+.settings-cleanup-open { opacity: 0; pointer-events: none; }
+.settings-cleanup-item:hover .settings-cleanup-open,
+.settings-cleanup-item:focus-within .settings-cleanup-open { opacity: 1; pointer-events: auto; }
+.settings-cleanup-project-toggle { display: flex; align-items: center; gap: 6px; min-width: 0; flex: 1; padding: 0; border: 0; background: transparent; color: var(--text); text-align: start; cursor: pointer; }
+.settings-cleanup-project-toggle .settings-cleanup-title { font-weight: 600; }
+.settings-cleanup-project-toggle svg { width: 14px; height: 14px; flex: 0 0 auto; }
+.settings-cleanup-project-head > .settings-row-desc { flex: 0 0 auto; font-variant-numeric: tabular-nums; }
+.settings-cleanup-project-toggle:disabled { cursor: default; }
@media (max-width: 700px) {
#settings-task-cleanup .settings-row { flex-wrap: wrap; gap: 12px; }
#settings-task-cleanup-age { flex-basis: 100%; }
#settings-task-cleanup .settings-cleanup-actions { margin-inline-start: auto; }
+ .settings-cleanup-item { flex-wrap: wrap; }
+ .settings-cleanup-copy { flex-basis: calc(100% - 28px); }
+ .settings-cleanup-meta { margin-inline-start: auto; }
}
.settings-mode-list { display: flex; flex-direction: column; gap: 4px; margin: -2px 0 0; }
.settings-mode-opt {
@@ -17108,7 +17108,7 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.auto-list,
#project-auto-list { container: automation-list / inline-size; }
#project-auto-list { gap: 12px; }
-.auto-scope-switcher { margin-bottom: 12px; }
+.auto-scope-switcher { flex: 0 0 auto; margin: 0 0 12px; }
.auto-scope-group { min-width: 0; }
.auto-scope-cards { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; align-items: start; }
.auto-scope-empty { padding: 36px 12px; text-align: center; }
@@ -18557,7 +18557,6 @@ body.is-task-side-panel-resizing * { cursor: col-resize !important; }
.quick-grid { grid-template-columns: 1fr; }
.quick-panel-head { flex-wrap: wrap; row-gap: 4px; }
.quick-panel-title { min-width: 0; flex: 1 1 100%; white-space: normal; }
- .quick-panel-more { margin-left: auto; }
.new-chat-scenario-chip,
#panel-new-chat .new-chat-scenario-chip { min-height: 88px; }
.new-chat-input-area .chat-input-mirror { font-size: 16px; }
diff --git a/test/e2e/composer_e2e_interactions.spec.ts b/test/e2e/composer_e2e_interactions.spec.ts
index 6180a166..d215e65f 100644
--- a/test/e2e/composer_e2e_interactions.spec.ts
+++ b/test/e2e/composer_e2e_interactions.spec.ts
@@ -863,9 +863,9 @@ test.describe('new chat composer', () => {
}
});
- test('keeps the wider landing scale and puts the OSS entry on the quick-start header', async ({ appPage }) => {
+ test('keeps the wider landing scale without an OSS entry', async ({ appPage }, testInfo) => {
await expect(appPage.locator('#new-chat-scenarios')).toBeVisible();
- await expect(appPage.locator('#quick-panel-oss-more')).toBeVisible();
+ await expect(appPage.locator('#quick-panel-oss-more')).toHaveCount(0);
const layout = await appPage.evaluate(() => {
const rect = (selector: string) => document.querySelector(selector)!.getBoundingClientRect();
@@ -924,15 +924,6 @@ test.describe('new chat composer', () => {
&& box.top >= card.top && box.bottom <= card.bottom;
});
}),
- // The entry belongs to the header row, not to the grid of runnable tasks.
- ossEntryOnHeaderRow: (() => {
- const link = document.querySelector('#quick-panel-oss-more');
- const title = rect('#quick-panel-title');
- const grid = rect('.quick-grid');
- if (!link || link.closest('.quick-grid')) return false;
- const box = link.getBoundingClientRect();
- return box.left > title.right && box.bottom <= grid.top + 0.5;
- })(),
landingStartsInBounds: header.top >= landing.top,
flexShrink: landingChildren.map((selector) => getComputedStyle(document.querySelector(selector)!).flexShrink),
};
@@ -955,7 +946,6 @@ test.describe('new chat composer', () => {
expect(layout.quickTileSizes).toEqual(Array(9).fill('36x36'));
expect(layout.quickIconSizes).toEqual(Array(9).fill('18x18'));
expect(layout.quickCardContentFits).toBe(true);
- expect(layout.ossEntryOnHeaderRow).toBe(true);
expect(layout.landingStartsInBounds).toBe(true);
// The region below the composer is the one block that gives way in a
// short window (P15).
@@ -989,20 +979,38 @@ test.describe('new chat composer', () => {
await appPage.setViewportSize({ width: 600, height: 800 });
const narrowLayout = await appPage.evaluate(() => {
const landing = document.querySelector('.new-chat-center')!;
- const more = document.querySelector('#quick-panel-oss-more')!.getBoundingClientRect();
- const landingRect = landing.getBoundingClientRect();
return {
columns: getComputedStyle(document.querySelector('.quick-grid')!).gridTemplateColumns
.split(' ').length,
noHorizontalOverflow: landing.scrollWidth <= landing.clientWidth + 1,
- moreEntryInBounds: more.left >= landingRect.left && more.right <= landingRect.right,
};
});
expect(narrowLayout).toEqual({
columns: 1,
noHorizontalOverflow: true,
- moreEntryInBounds: true,
});
+ for (const locale of ['en', 'zh']) {
+ await appPage.evaluate(async (lang) => (window as any).setLang(lang), locale);
+ for (const width of [1280, 600]) {
+ await appPage.setViewportSize({ width, height: 800 });
+ await appPage.locator('.home-below').evaluate((element) => { element.scrollTop = 0; });
+ await expect(appPage.locator('#home-explore-context')).toHaveText(locale === 'zh'
+ ? '添加资料或连接邮箱/店铺/办公软件等,让 Orkas 更了解你。从你愿意分享的内容开始。'
+ : "Add materials or connect email, stores, office apps, and more to help Orkas get to know you better. Start with whatever you're comfortable sharing.");
+ await appPage.screenshot({ path: testInfo.outputPath(`home-${locale}-${width}.png`) });
+ }
+ }
+ await appPage.setViewportSize({ width: 1280, height: 800 });
+ await appPage.locator('[data-home-connect]').click();
+ await expect(appPage.locator('#panel-connectors')).toHaveClass(/\bactive\b/);
+ await expect(appPage.locator('#connectors-btn')).toHaveClass(/\bactive\b/);
+ await appPage.screenshot({ path: testInfo.outputPath('home-connectors-tab.png') });
+ await appPage.locator('#new-chat-btn').click();
+ // Wait for the home entry's deferred composer focus before keyboard navigation.
+ await expect(appPage.locator('#new-chat-input')).toBeFocused();
+ await appPage.locator('[data-home-connect]').focus();
+ await appPage.keyboard.press('Enter');
+ await expect(appPage.locator('#panel-connectors')).toHaveClass(/\bactive\b/);
});
test('prefills a quick scenario and keeps modified Enter as a newline', async ({ appPage }) => {
diff --git a/test/e2e/home_e2e_continuation.spec.ts b/test/e2e/home_e2e_continuation.spec.ts
index c513430b..511548e9 100644
--- a/test/e2e/home_e2e_continuation.spec.ts
+++ b/test/e2e/home_e2e_continuation.spec.ts
@@ -8,6 +8,70 @@ import { expect, test } from './fixtures/orkas';
// The empty state's layout is covered by the landing case in
// composer_e2e_interactions.spec.ts.
test.describe('Commander home continuation', () => {
+
+ test('expands all remaining work with accurate counts and preserves expansion on refresh', async ({ orkas, appPage }, testInfo) => {
+ await appPage.setViewportSize({ width: 1280, height: 720 });
+ for (let i = 0; i < 11; i += 1) {
+ await orkas.invoke('projects.tasks.create', { content: `Follow-up ${i + 1}: ${'Review the customer feedback and confirm the next step. '.repeat(3)}` });
+ }
+ const records: Array<{ cid: string; entryPoint: string }> = [];
+ for (const [entryPoint, total] of [['automation', 46], ['chat_send', 4]] as const) {
+ for (let i = 0; i < total; i += 1) {
+ const created = await orkas.invoke<{ conversation: { conversation_id: string } }>('conversations.create', { title: `${entryPoint} result ${i + 1}` });
+ records.push({ cid: created.conversation.conversation_id, entryPoint });
+ }
+ }
+ await appPage.evaluate((rows) => {
+ for (const [i, row] of rows.entries()) (window as any)._markConversationUnread(row.cid, {
+ // Legacy unread records have no stored outcome or result body.
+ finishedAt: Date.now() - i * 1000, ...(i < 3 ? { status: 'completed' } : {}), entryPoint: row.entryPoint,
+ });
+ }, records);
+
+ for (const [section, total] of [['todos', 11], ['automations', 46], ['tasks', 4]] as const) {
+ const group = appPage.locator(`.home-group[data-section="${section}"]`);
+ await expect(group.locator('.home-group-count')).toHaveText(String(total));
+ await expect(group.locator('.home-row:visible')).toHaveCount(3);
+ const toggle = group.locator('[data-home-toggle]');
+ await expect(toggle).toHaveText(`Show ${total - 3} more`);
+ await toggle.focus();
+ await appPage.keyboard.press('Enter');
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ await expect(group.locator('.home-row:visible')).toHaveCount(total);
+ if (section !== 'todos') {
+ await expect(group.locator('.home-row-status.is-completed')).toHaveCount(total);
+ await expect(group.locator('.home-row-status.is-unknown')).toHaveCount(0);
+ }
+ await group.locator('.home-row').last().scrollIntoViewIfNeeded();
+ await expect(group.locator('.home-row').last()).toBeInViewport();
+ if (section === 'automations') await appPage.screenshot({ path: testInfo.outputPath('home-legacy-results-completed-en.png') });
+ await toggle.click();
+ await expect(group.locator('.home-row:visible')).toHaveCount(3);
+ await expect(toggle).toHaveText(`Show ${total - 3} more`);
+ }
+
+ const todos = appPage.locator('.home-group[data-section="todos"]');
+ await todos.locator('[data-home-toggle]').click();
+ await orkas.invoke('projects.tasks.create', { content: 'A follow-up added while the list is expanded' });
+ await expect(todos.locator('.home-group-count')).toHaveText('12');
+ await expect(todos.locator('[data-home-toggle]')).toHaveAttribute('aria-expanded', 'true');
+ await expect(todos.locator('.home-row:visible')).toHaveCount(12);
+ await todos.locator('[data-home-toggle]').click();
+ await todos.scrollIntoViewIfNeeded();
+ await appPage.screenshot({ path: testInfo.outputPath('home-folded-en-1280.png') });
+
+ await appPage.evaluate(async () => (window as any).setLang('zh'));
+ await appPage.setViewportSize({ width: 960, height: 640 });
+ await expect(todos.locator('[data-home-toggle]')).toHaveText('展开其余 9 条');
+ await todos.locator('[data-home-toggle]').click();
+ await todos.scrollIntoViewIfNeeded();
+ await appPage.screenshot({ path: testInfo.outputPath('home-expanded-zh-960.png') });
+ await todos.locator('.home-row').last().scrollIntoViewIfNeeded();
+ await appPage.screenshot({ path: testInfo.outputPath('home-expanded-zh-footer.png') });
+ await todos.locator('[data-home-toggle]').click();
+ await expect(todos.locator('.home-row:visible')).toHaveCount(3);
+ });
+
test('lists open work below a composer that keeps its place, and drops a run once it is opened', async ({ orkas, appPage }) => {
await appPage.setViewportSize({ width: 1280, height: 720 });
const panel = appPage.locator('#panel-new-chat');
diff --git a/test/e2e/task_cleanup_e2e_history.spec.ts b/test/e2e/task_cleanup_e2e_history.spec.ts
index 44e837ac..48a59fab 100644
--- a/test/e2e/task_cleanup_e2e_history.spec.ts
+++ b/test/e2e/task_cleanup_e2e_history.spec.ts
@@ -1,10 +1,272 @@
-import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from 'node:fs';
import path from 'node:path';
import { test, expect } from './fixtures/orkas';
test.describe('inline historical task cleanup', () => {
+ test('uses sidebar timestamps and retains tasks renamed before preview or confirmation', async ({ orkas }, testInfo) => {
+ const cids: string[] = [];
+ for (const title of ['Old task metadata', 'Rename before preview', 'Rename before confirmation']) {
+ cids.push((await orkas.invoke<any>('conversations.create', { title })).conversation.conversation_id);
+ }
+ const root = path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chats');
+ const indexFile = path.join(root, '_index.json');
+ const rows = JSON.parse(readFileSync(indexFile, 'utf8'));
+ const old = new Date(Date.now() - 37 * 86400000).toISOString();
+ for (const cid of cids) {
+ const row = rows.find((r: any) => r.conversation_id === cid);
+ row.created_at = old; row.updated_at = old;
+ writeFileSync(path.join(root, cid, 'meta.json'), JSON.stringify(row));
+ writeFileSync(path.join(root, cid, 'state.json'), JSON.stringify({ status: 'idle', in_flight: [], last_active_at: old }));
+ // Real rename IPC below advances metadata without changing these old messages.
+ writeFileSync(path.join(root, `${cid}.jsonl`), [
+ { id: 'reply', from: 'commander', content: 'Preserved response', ts: old },
+ { id: 'request', from: 'user', content: 'Historical request', ts: old },
+ ].map(row => JSON.stringify(row)).join('\n'));
+ }
+ writeFileSync(indexFile, JSON.stringify(rows));
+ const original = cids.map(cid => readFileSync(path.join(root, `${cid}.jsonl`), 'utf8'));
+ const page = await orkas.relaunch();
+ const renamed = await orkas.invoke<any>('conversations.rename', { cid: cids[1], title: 'Updated before preview' });
+ const sidebar = await orkas.invoke<any>('conversations.list', { mode: 'unprojected', offset: 0 });
+ const sidebarTasks = sidebar.conversations.filter((row: any) => cids.includes(row.conversation_id));
+ expect(sidebarTasks[0].conversation_id).toBe(cids[1]);
+ // Legacy timestamps omit a zone; parse in the app's timezone, not the test host's.
+ const renamedAt = await orkas.electronApp!.evaluate((_, ts) => Date.parse(ts), renamed.conversation.updated_at);
+ expect(Date.parse(sidebarTasks[0].last_active_at)).toBe(renamedAt);
+ await page.locator('#settings-btn').click();
+ await page.locator('[data-settings-tab="data"]').click();
+ const section = page.locator('#settings-task-cleanup');
+ await section.getByRole('combobox').click();
+ await page.getByRole('option', { name: 'Over 14 days ago', exact: true }).click();
+ await section.locator('[data-cleanup-action="view"]').click();
+ await expect(section.locator('[data-cleanup-cid]')).toHaveCount(2);
+ await expect(section.locator(`[data-cleanup-cid="${cids[0]}"]`)).toBeEnabled();
+ await expect(section.locator(`[data-cleanup-cid="${cids[1]}"]`)).toHaveCount(0);
+ await section.screenshot({ path: testInfo.outputPath('cleanup-14-day-metadata-age.png') });
+ await section.locator('[data-cleanup-all]').check();
+ await section.locator('[data-cleanup-action="prepare"]').click();
+ await orkas.invoke<any>('conversations.rename', { cid: cids[2], title: 'Updated while confirming' });
+ await section.locator('[data-cleanup-action="confirm"]').click();
+ await expect(section).toContainText('Recycled 1 · Skipped 1 · Failed 0');
+ await expect(section.locator(`[data-cleanup-cid="${cids[0]}"]`)).toHaveCount(0);
+ expect(existsSync(path.join(root, `${cids[0]}.jsonl`))).toBe(false);
+ expect(readFileSync(path.join(root, `${cids[1]}.jsonl`), 'utf8')).toBe(original[1]);
+ expect(readFileSync(path.join(root, `${cids[2]}.jsonl`), 'utf8')).toBe(original[2]);
+ expect((await orkas.invoke<any>('conversations.get', { cid: cids[2] })).conversation.title).toBe('Updated while confirming');
+ const { batches } = await orkas.invoke<any>('recycle.list');
+ expect(batches).toHaveLength(1);
+ expect(await orkas.invoke<any>('recycle.restore', { id: batches[0].id })).toMatchObject({ ok: true, failed: 0, reactivated: 1 });
+ expect(readFileSync(path.join(root, `${cids[0]}.jsonl`), 'utf8')).toBe(original[0]);
+ });
+ test('keeps only failed tasks selected after partial cleanup and cleans them without duplicate skips', async ({ orkas }, testInfo) => {
+ const pid = (await orkas.invoke<any>('projects.create', { name: 'Partial cleanup project' })).project.project_id;
+ const cids: string[] = [];
+ for (const title of ['Completed cleanup', 'Retry cleanup']) {
+ cids.push((await orkas.invoke<any>('conversations.create', { title, projectId: pid })).conversation.conversation_id);
+ }
+ const root = path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'projects', pid, 'chats');
+ const indexFile = path.join(root, '_index.json');
+ const rows = JSON.parse(readFileSync(indexFile, 'utf8'));
+ for (const row of rows) {
+ row.created_at = row.updated_at = '2020-01-01T00:00:00Z';
+ writeFileSync(path.join(root, row.conversation_id, 'meta.json'), JSON.stringify(row));
+ writeFileSync(path.join(root, `${row.conversation_id}.jsonl`), JSON.stringify({ from: 'user', content: row.title, ts: row.created_at }) + '\n');
+ }
+ writeFileSync(indexFile, JSON.stringify(rows));
+ const page = await orkas.relaunch();
+ await orkas.electronApp!.evaluate(({ ipcMain }, failedCid) => {
+ const original = (ipcMain as any)._invokeHandlers.get('orkas.invoke');
+ let failed = false;
+ ipcMain.removeHandler('orkas.invoke');
+ ipcMain.handle('orkas.invoke', (event, request) => {
+ if (request.channel === 'conversations.cleanup.remove' && request.payload.cid === failedCid && !failed) {
+ failed = true;
+ return { ok: false, error: 'cleanup_failed' };
+ }
+ return original(event, request);
+ });
+ }, cids[1]);
+ await page.locator('#settings-btn').click();
+ await page.locator('[data-settings-tab="data"]').click();
+ const section = page.locator('#settings-task-cleanup');
+ await section.locator('[data-cleanup-action="view"]').click();
+ await section.locator('[data-cleanup-action="project"]').click();
+ await section.locator('[data-cleanup-project]').check();
+ await section.locator('[data-cleanup-action="prepare"]').click();
+ await section.locator('[data-cleanup-action="confirm"]').click();
+ await expect(section).toContainText('Recycled 1 · Skipped 0 · Failed 1');
+ await expect(section.locator('[data-cleanup-action="prepare"]')).toHaveText('Clean up (1)');
+ await expect(section.locator(`[data-cleanup-cid="${cids[0]}"]`)).toHaveCount(0);
+ await expect(section.locator(`[data-cleanup-cid="${cids[1]}"]`)).toBeChecked();
+ await expect(section.locator('.settings-cleanup-project-head')).toContainText('1 / 1');
+ await section.screenshot({ path: testInfo.outputPath('cleanup-partial-success.png') });
+ await section.locator('[data-cleanup-action="prepare"]').click();
+ await section.locator('[data-cleanup-action="confirm"]').click();
+ await expect(section).toContainText('Recycled 1 · Skipped 0 · Failed 0');
+ await expect(section.locator('[data-cleanup-cid]')).toHaveCount(0);
+ expect((await orkas.invoke<any>('recycle.list')).batches).toHaveLength(2);
+ });
+ test('opens personal and active project history from hover and keyboard actions without changing selection', async ({ orkas }, testInfo) => {
+ const projectId = (await orkas.invoke<any>('projects.create', { name: 'Fixture project' })).project.project_id;
+ const tasks: { cid: string; root: string; projectId: string; title: string }[] = [];
+ const old = '2020-01-01T00:00:00Z';
+ for (const pid of ['', projectId]) {
+ const { conversation } = await orkas.invoke<any>('conversations.create', {
+ title: pid ? '一个很长的项目任务标题,需要查看历史对话来确认任务为何无法选择'.repeat(3) : 'Personal task with a long title '.repeat(5), projectId: pid,
+ });
+ const cid = conversation.conversation_id;
+ const root = path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', ...(pid ? ['projects', pid] : []), 'chats');
+ const indexFile = path.join(root, '_index.json');
+ const rows = JSON.parse(readFileSync(indexFile, 'utf8'));
+ const row = rows.find((item: any) => item.conversation_id === cid);
+ row.created_at = old; row.updated_at = old;
+ const dir = path.join(root, cid); mkdirSync(dir, { recursive: true });
+ writeFileSync(indexFile, JSON.stringify(rows));
+ writeFileSync(path.join(dir, 'meta.json'), JSON.stringify(row));
+ writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ version: 1, status: 'idle', in_flight: [], last_active_at: old }));
+ writeFileSync(path.join(root, `${cid}.jsonl`), JSON.stringify({ id: 'source', from: 'user', text: pid ? 'Project history to inspect' : 'Personal history to inspect', ts: old }) + '\n');
+ tasks.push({ cid, root, projectId: pid, title: row.title });
+ }
+ const page = await orkas.relaunch();
+ // Preserve an old queued record to exercise automatic stopping independently
+ // of startup recovery; no model execution is started by this fixture.
+ const blocked = tasks[1];
+ writeFileSync(path.join(blocked.root, blocked.cid, 'tasks.json'), JSON.stringify([
+ { task_id: 'queued', cid: blocked.cid, assignee: 'commander', instruction: 'Fixture only', status: 'queued', created_at: old },
+ ]));
+ await page.evaluate(cid => localStorage.setItem(`draft_${cid}`, JSON.stringify({ text: 'Unsent draft stays intact' })), blocked.cid);
+ const section = page.locator('#settings-task-cleanup');
+ const openSettings = async () => {
+ await page.locator('#settings-btn').click();
+ await page.locator('[data-settings-tab="data"]').click();
+ await expect(section).toContainText('Clean up (0)');
+ if (!await section.locator('[data-cleanup-project]').count()) await section.locator('[data-cleanup-action="view"]').click();
+ };
+ await openSettings();
+ const personalOpen = section.locator(`[data-cleanup-action="open"][data-cleanup-owner="${tasks[0].cid}"]`);
+ await expect(personalOpen).toHaveCount(1);
+ await page.mouse.move(0, 0);
+ await expect(personalOpen).toHaveCSS('opacity', '0');
+ await personalOpen.locator('xpath=ancestor::*[contains(@class,"settings-cleanup-item")]').hover();
+ await expect(personalOpen).toHaveCSS('opacity', '1');
+ await personalOpen.click();
+ await expect(page.locator('#panel-conversation')).toHaveClass(/active/);
+ await expect(page.locator('#chat-history')).toContainText('Personal history to inspect');
+ await expect(page.locator('#chat-header-title')).toHaveText(tasks[0].title);
+ await expect(section.locator(`[data-cleanup-cid="${tasks[0].cid}"]`)).not.toBeChecked();
+ const back = page.locator('#chat-cleanup-back');
+ await expect(back).toBeVisible();
+ await back.click();
+ await expect(page.locator('#panel-settings')).toHaveClass(/active/);
+ await expect(section.locator('[data-cleanup-action="view"]')).toHaveText('Collapse');
+ await section.locator('[data-cleanup-action="project"]').click();
+ const projectCheck = section.locator(`[data-cleanup-cid="${blocked.cid}"]`);
+ const projectOpen = section.locator(`[data-cleanup-action="open"][data-cleanup-owner="${blocked.cid}"]`);
+ await expect(projectCheck).toBeEnabled();
+ await expect(section).not.toContainText('Stops on cleanup');
+ await page.mouse.move(0, 0);
+ await expect(projectOpen).toHaveCSS('opacity', '0');
+ await projectOpen.focus();
+ await expect(projectOpen).toHaveCSS('opacity', '1');
+ for (const [lang, width, height] of [['en', 1280, 900], ['zh', 1000, 720], ['zh', 620, 780]] as const) {
+ await page.setViewportSize({ width, height });
+ await page.evaluate(async lang => { await (window as any).setLang(lang); }, lang);
+ await projectOpen.focus();
+ const fits = await projectOpen.evaluate(el => {
+ const row = el.closest('.settings-cleanup-item')!.getBoundingClientRect();
+ const button = el.getBoundingClientRect();
+ const time = el.nextElementSibling!.getBoundingClientRect();
+ return button.left >= row.left && button.right <= time.left && time.right <= row.right;
+ });
+ expect(fits).toBe(true);
+ await section.screenshot({ path: testInfo.outputPath(`cleanup-view-${lang}-${width}.png`) });
+ }
+ await projectCheck.check();
+ const settingsScroll = await section.evaluate(el => el.closest('.settings-body')!.scrollTop);
+ expect(await page.evaluate(cid => window.eval('conversations').some((row: any) => row.conversation_id === cid), blocked.cid)).toBe(false);
+ await projectOpen.press('Enter');
+ await expect(page.locator('#panel-conversation')).toHaveClass(/active/);
+ await expect(page.locator('#chat-history')).toContainText('Project history to inspect');
+ await expect(page.locator('#chat-header-title')).toHaveText(blocked.title);
+ await expect(page.locator('#chat-header-meta')).toContainText('Fixture project');
+ await expect(projectCheck).toBeChecked();
+ await expect(back).toBeVisible();
+ await expect(back).toHaveText('返回');
+ await page.locator('#chat-header').screenshot({ path: testInfo.outputPath('cleanup-return-header-zh.png') });
+ await back.click();
+ await expect(page.locator('#panel-settings')).toHaveClass(/active/);
+ await expect(page.locator('[data-settings-tab="data"]')).toHaveClass(/is-active/);
+ await expect(projectCheck).toBeChecked();
+ await expect(section).toContainText('清理 (1)');
+ expect(await section.evaluate(el => el.closest('.settings-body')!.scrollTop)).toBe(settingsScroll);
+ await page.evaluate(cid => window.eval(`setView('conversation', ${JSON.stringify(cid)})`), tasks[0].cid);
+ await expect(back).toBeHidden();
+ expect(await page.evaluate(cid => localStorage.getItem(`draft_${cid}`), blocked.cid)).toContain('Unsent draft stays intact');
+ for (const task of tasks) expect(existsSync(path.join(task.root, `${task.cid}.jsonl`))).toBe(true);
+ });
+ test('stops a live model turn before recycling and can restore its stopped history', async ({ modelOrkas }, testInfo) => {
+ const app = modelOrkas, page = app.page!;
+ app.setModelMode('controlled-slow');
+ await page.locator('#new-chat-input').fill('Write a short task cleanup fixture.');
+ await page.locator('#new-chat-send-btn').click();
+ await expect.poll(() => app.modelRequests.length).toBeGreaterThan(0);
+ const cid = await page.evaluate(() => window.eval('currentCid'));
+ expect((await app.invoke<any>('groupChat.runtimeStatus', { cid })).processing).toBe(true);
+ const root = path.join(app.workspaceRoot, 'account-e2e', 'cloud', 'chats');
+ const old = '2020-01-01T00:00:00Z';
+ // Age all persisted activity while its real bus/model turn stays live.
+ for (const file of [path.join(root, '_index.json'), path.join(root, cid, 'meta.json'), path.join(root, cid, 'state.json'), path.join(root, cid, 'tasks.json')]) {
+ const data = JSON.parse(readFileSync(file, 'utf8'));
+ const rows = Array.isArray(data) ? data : [data];
+ for (const row of rows) {
+ if (row.conversation_id && row.conversation_id !== cid) continue;
+ for (const field of ['created_at', 'updated_at', 'last_active_at', 'started_at', 'ended_at']) if (row[field]) row[field] = old;
+ }
+ writeFileSync(file, JSON.stringify(data));
+ }
+ const messageFile = path.join(root, `${cid}.jsonl`);
+ writeFileSync(messageFile, readFileSync(messageFile, 'utf8').trim().split('\n')
+ .map(line => JSON.stringify({ ...JSON.parse(line), ts: old })).join('\n') + '\n');
+ await app.electronApp!.evaluate((_, chatsModule) => {
+ (process as any).mainModule.require(chatsModule).invalidateConversationCaches('account-e2e');
+ }, path.resolve(__dirname, '../../src/main/features/chats.ts'));
+ await page.locator('#settings-btn').click();
+ await page.locator('[data-settings-tab="data"]').click();
+ const section = page.locator('#settings-task-cleanup');
+ await section.locator('[data-cleanup-action="view"]').click();
+ await section.locator(`[data-cleanup-cid="${cid}"]`).check();
+ await section.locator('[data-cleanup-action="prepare"]').click();
+ await expect(section).toContainText('Running tasks are stopped automatically before cleanup.');
+ await section.screenshot({ path: testInfo.outputPath('cleanup-stop-confirm.png') });
+ await section.locator('[data-cleanup-action="confirm"]').click();
+ await expect(section).toContainText('Recycled 1');
+ expect(existsSync(path.join(root, `${cid}.jsonl`))).toBe(false);
+ // A polling request can overlap the tombstone commit. Absence is the
+ // required history result until the user explicitly restores this task.
+ const missing = await app.invoke<any>('conversations.history', { cid });
+ expect(missing).toMatchObject({ ok: false, error: 'conversation not found' });
+ await testInfo.attach('deleted-history-receipt', {
+ body: Buffer.from(JSON.stringify({ expectedAbsent: true, code: missing.code, deletedFileAbsent: true })),
+ contentType: 'application/json',
+ });
+ app.releaseControlledModelChunk(); app.finishControlledModelStream();
+ const { batches } = await app.invoke<any>('recycle.list');
+ const batch = batches.find((entry: any) => entry.items.some((item: any) => item.path === `cloud/chats/${cid}.jsonl`));
+ expect(batch).toBeTruthy();
+ expect((await app.invoke<any>('recycle.restore', { id: batch.id })).failed).toBe(0);
+ const history = readFileSync(path.join(root, `${cid}.jsonl`), 'utf8');
+ expect(history).toContain('Write a short task cleanup fixture.');
+ const restored = await app.invoke<any>('conversations.history', { cid });
+ expect(restored.ok).toBe(true);
+ expect(JSON.stringify(restored.history)).toContain('Write a short task cleanup fixture.');
+ expect((await app.invoke<any>('groupChat.runtimeStatus', { cid })).processing).toBe(false);
+ });
for (const inProject of [false, true]) test(`previews, cancels, excludes, cleans and restores ${inProject ? 'project' : 'personal'} history using real IPC and storage`, async ({ orkas }, testInfo) => {
const projectId = inProject ? (await orkas.invoke<any>('projects.create', { name: 'Cleanup project' })).project.project_id : '';
+ const { task: automation } = await orkas.invoke<any>('autoTasks.create', {
+ title: 'Keep automation configuration', content: 'Fixture only', enabled: false,
+ schedule: { type: 'daily', hour: 9, minute: 0 }, ...(projectId ? { project_id: projectId } : {}),
+ });
const dataRoot = path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', ...(projectId ? ['projects', projectId] : []));
const root = path.join(dataRoot, 'chats');
const cids: string[] = [];
@@ -19,6 +281,7 @@ test.describe('inline historical task cleanup', () => {
const row = index.find((r: any) => r.conversation_id === cid);
row.created_at = old; row.updated_at = old;
if (i === 3) row.pinned_at = old;
+ if (i === 2) row.origin_auto_task_id = automation.id;
const dir = path.join(root, cid); mkdirSync(dir, { recursive: true });
writeFileSync(path.join(dir, 'meta.json'), JSON.stringify(row));
writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ version: 1, status: 'idle', in_flight: [], last_active_at: old }));
@@ -27,27 +290,63 @@ test.describe('inline historical task cleanup', () => {
}
const projectBefore = projectId ? readFileSync(path.join(dataRoot, 'project.json'), 'utf8') : '';
const attachment = (cid: string) => path.join(dataRoot, 'chat_attachments', cid, 'notes.txt');
+ const nestedAttachment = path.join(dataRoot, 'chat_attachments', cids[6], 'folder', 'draft.txt');
+ mkdirSync(path.dirname(nestedAttachment), { recursive: true });
+ writeFileSync(nestedAttachment, 'Nested unsent attachment');
for (const cid of [cids[0], cids[6]]) {
mkdirSync(path.dirname(attachment(cid)), { recursive: true });
writeFileSync(attachment(cid), 'Attachment contents');
}
writeFileSync(path.join(root, `${cids[0]}.jsonl`), JSON.stringify({ id: 'source', from: 'user', content: 'Preserved history', attachments: ['notes.txt'], ts: old }) + '\n');
writeFileSync(indexFile, JSON.stringify(index));
+ let standalone = '';
+ const standaloneRoot = path.join(orkas.workspaceRoot, 'account-e2e', 'cloud', 'chats');
+ if (projectId) {
+ standalone = (await orkas.invoke<any>('conversations.create', { title: 'Top-level task' })).conversation.conversation_id;
+ const standaloneIndex = path.join(standaloneRoot, '_index.json');
+ const rows = JSON.parse(readFileSync(standaloneIndex, 'utf8'));
+ const row = rows.find((item: any) => item.conversation_id === standalone);
+ row.created_at = old; row.updated_at = old;
+ writeFileSync(standaloneIndex, JSON.stringify(rows));
+ const dir = path.join(standaloneRoot, standalone); mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, 'meta.json'), JSON.stringify(row));
+ writeFileSync(path.join(dir, 'state.json'), JSON.stringify({ version: 1, status: 'idle', in_flight: [], last_active_at: old }));
+ writeFileSync(path.join(standaloneRoot, `${standalone}.jsonl`), JSON.stringify({ id: 'personal', from: 'user', content: 'Keep top-level history', ts: old }) + '\n');
+ }
const page = await orkas.relaunch();
+ // Create the missing-transcript shape after startup's one-time ghost
+ // migration, matching unsent tasks encountered during an active session.
+ rmSync(path.join(root, `${cids[6]}.jsonl`));
await page.evaluate(([unread, draft, pid]) => {
localStorage.setItem('task_unread_v1_account-e2e', JSON.stringify({ unread: [{ cid: unread, projectId: pid || null, finishedAt: Date.now(), status: 'completed' }], read: [] }));
localStorage.setItem(`draft_${draft}`, JSON.stringify({ text: 'Keep this unsent draft' }));
}, [cids[4], cids[5], projectId]);
await page.reload();
+ await page.evaluate(cid => {
+ window.eval('_chatAttachments').set(cid, [{ name: 'notes.txt', dataUrl: URL.createObjectURL(new Blob(['Draft preview'])), status: 'ready' }]);
+ }, cids[6]);
await page.locator('#settings-btn').click();
await page.locator('[data-settings-tab="data"]').click();
const section = page.locator('#settings-task-cleanup');
- await expect(section).toContainText('Selected tasks: 2');
+ await expect(section).toContainText('Clean up (0)');
+ await expect(section.getByRole('combobox')).toContainText('30');
await expect(page.locator('#settings-section-local h2')).toHaveText('Data directory');
await expect(page.locator('#settings-section-local .settings-row-title')).toHaveCount(0);
await section.screenshot({ path: testInfo.outputPath('cleanup-preview.png') });
await section.locator('[data-cleanup-action="view"]').click();
- await expect(section.locator('[data-cleanup-cid]')).toHaveCount(2);
+ if (projectId) {
+ await expect(section.locator('[data-cleanup-project]')).toHaveCount(1);
+ await section.locator('[data-cleanup-action="project"]').click();
+ await expect(section.locator('.settings-cleanup-project-toggle [data-ui-icon]')).toHaveCount(2);
+ await expect(section.locator(`.settings-cleanup-list > .settings-cleanup-item [data-cleanup-cid="${standalone}"]`)).toHaveCount(1);
+ await expect(section.locator('.settings-cleanup-project .settings-cleanup-item.is-nested')).toHaveCount(7);
+ } else await expect(section.locator('[data-cleanup-project]')).toHaveCount(0);
+ await expect(section.locator('[data-cleanup-cid]')).toHaveCount(projectId ? 8 : 7);
+ await expect(section.locator('.settings-cleanup-tag').filter({ hasText: 'Automation' })).toHaveCount(1);
+ await section.locator('[data-cleanup-all]').check();
+ if (standalone) await section.locator(`[data-cleanup-cid="${standalone}"]`).uncheck();
+ await expect(section.locator(`[data-cleanup-cid="${cids[3]}"]`)).toBeChecked();
+ await expect(section.locator(`[data-cleanup-cid="${cids[5]}"]`)).toBeChecked();
await section.locator('[data-cleanup-action="prepare"]').click();
await expect(section.locator('[data-cleanup-action="confirm"]')).toBeVisible();
await section.locator('[data-cleanup-action="cancel"]').click();
@@ -55,44 +354,93 @@ test.describe('inline historical task cleanup', () => {
await section.locator(`[data-cleanup-cid="${cids[1]}"]`).uncheck();
await section.locator('[data-cleanup-action="prepare"]').click();
await page.setViewportSize({ width: 1000, height: 900 });
+ expect(await section.locator('[data-cleanup-action="confirm"]').evaluate(el => {
+ const row = el.closest('.settings-row')!.getBoundingClientRect();
+ const button = el.getBoundingClientRect();
+ return button.left >= row.left && button.right <= row.right;
+ })).toBe(true);
await section.screenshot({ path: testInfo.outputPath('cleanup-en.png') });
await page.evaluate(async () => { await (window as any).setLang('zh'); });
+ await section.screenshot({ path: testInfo.outputPath('cleanup-zh.png') });
await page.setViewportSize({ width: 620, height: 780 });
- await expect(section.locator('[data-cleanup-action="confirm"]')).toHaveText('移入回收站(1)');
- await expect(section.getByRole('combobox')).toContainText('90 天以前');
+ await expect(section.locator('[data-cleanup-action="confirm"]')).toHaveText('移入回收站(6)');
+ await expect(section.getByRole('combobox')).toContainText('30 天以前');
const geometry = await section.evaluate(el => ({ width: el.clientWidth, scroll: el.scrollWidth }));
expect(geometry.scroll).toBeLessThanOrEqual(geometry.width);
await section.screenshot({ path: testInfo.outputPath('cleanup-zh-narrow.png') });
- // Hold the real deletion at IPC so the in-flight UI can be inspected
- // deterministically, then release it to exercise storage and restoration.
+ // Cleanup is maintenance, not task activity. Observe the real old history
+ // throughout deletion so a transient promotion into Recent is not missed.
+ await page.evaluate(async ({ ids, pid }) => {
+ if (pid) await (window as any).loadConversationProject(pid, { reset: true });
+ const recent = document.getElementById('today-list')!;
+ const promoted = new Set<string>();
+ const observer = new MutationObserver(() => {
+ for (const row of recent.querySelectorAll<HTMLElement>('[data-cid]')) {
+ if (ids.includes(row.dataset.cid!)) promoted.add(row.dataset.cid!);
+ }
+ });
+ observer.observe(recent, { childList: true, subtree: true });
+ (window as any).__cleanupRecentObservation = { promoted, observer };
+ }, { ids: cids, pid: projectId });
+ await expect(page.locator('#today-list [data-cid]')).toHaveCount(0);
+ // Hold the second real deletion at IPC to inspect the first completed one.
await orkas.electronApp!.evaluate(({ ipcMain }) => {
const original = (ipcMain as any)._invokeHandlers.get('orkas.invoke');
+ let removals = 0;
ipcMain.removeHandler('orkas.invoke');
ipcMain.handle('orkas.invoke', async (event, request) => {
- if (request.channel === 'conversations.cleanup.remove') {
+ if (request.channel === 'conversations.cleanup.remove' && ++removals === 2) {
ipcMain.removeHandler('orkas.invoke');
ipcMain.handle('orkas.invoke', original);
await new Promise<void>(resolve => ipcMain.once('cleanup-test-resume', () => resolve()));
}
- return original(event, request);
+ const response = await original(event, request);
+ if (request.channel === 'conversations.cleanup.remove' && removals === 1 && response.status === 'deleted') {
+ (globalThis as any).__cleanupFirstRemovedCid = request.payload.cid;
+ }
+ return response;
});
});
await section.locator('[data-cleanup-action="confirm"]').click();
try {
await expect(section.getByRole('status')).toHaveCount(1);
- await expect(section.getByRole('status')).toContainText('正在清理 0 / 1');
+ await expect(section.getByRole('status')).toContainText('正在清理 1 / 6');
+ const removed = await orkas.electronApp!.evaluate(() => (globalThis as any).__cleanupFirstRemovedCid);
+ expect(cids).toContain(removed);
+ await expect(page.locator(`.conv-item[data-cid="${removed}"]`)).toHaveCount(0);
+ expect(await page.evaluate(cid => window.eval('conversations').some((row: any) => row.conversation_id === cid), removed)).toBe(false);
+ await expect(page.locator('#today-list [data-cid]')).toHaveCount(0);
await expect(section.locator('[data-cleanup-action="stop"]')).toBeEnabled();
await section.screenshot({ path: testInfo.outputPath('cleanup-progress-zh.png') });
} finally {
await orkas.electronApp!.evaluate(({ ipcMain }) => { ipcMain.emit('cleanup-test-resume'); });
}
- await expect(section).toContainText('已移入回收站 1 项');
+ await expect(section).toContainText('已回收 6');
+ expect(await page.evaluate(() => {
+ const { observer, promoted } = (window as any).__cleanupRecentObservation;
+ observer.disconnect();
+ return Array.from(promoted);
+ })).toEqual([]);
expect(existsSync(path.join(root, `${cids[0]}.jsonl`))).toBe(false);
expect(existsSync(attachment(cids[0]))).toBe(false);
- expect(readFileSync(attachment(cids[6]), 'utf8')).toBe('Attachment contents');
- for (const cid of cids.slice(1)) expect(existsSync(path.join(root, `${cid}.jsonl`))).toBe(true);
+ expect(existsSync(attachment(cids[6]))).toBe(false);
+ expect(existsSync(path.join(root, `${cids[1]}.jsonl`))).toBe(true);
+ for (const cid of cids.slice(2)) expect(existsSync(path.join(root, `${cid}.jsonl`))).toBe(false);
+ expect(await page.evaluate(cid => localStorage.getItem(`draft_${cid}`), cids[5])).toBeNull();
+ expect(await page.evaluate(cid => window.eval('_chatAttachments').has(cid), cids[6])).toBe(false);
+ expect(await page.evaluate(cid => (window as any).TaskUnread.isUnread(cid), cids[4])).toBe(false);
+ if (standalone) expect(existsSync(path.join(standaloneRoot, `${standalone}.jsonl`))).toBe(true);
+ expect((await orkas.invoke<any>('autoTasks.list', { projectId: projectId || null })).tasks.some((task: any) => task.id === automation.id)).toBe(true);
if (projectId) expect(readFileSync(path.join(dataRoot, 'project.json'), 'utf8')).toBe(projectBefore);
const { batches } = await orkas.invoke<any>('recycle.list');
+ expect(existsSync(nestedAttachment)).toBe(false);
+ const draftBatch = batches.find((b: any) => b.display_items?.some((item: any) => item.id === cids[6]));
+ expect(draftBatch).toBeTruthy();
+ expect(draftBatch.display_items).toEqual([expect.objectContaining({ category: 'conversation', id: cids[6], title: 'Attachment-only draft' })]);
+ expect(await orkas.invoke<any>('recycle.restore', { id: draftBatch.id })).toMatchObject({ ok: true, failed: 0, reactivated: 1 });
+ expect(readFileSync(nestedAttachment, 'utf8')).toBe('Nested unsent attachment');
+ expect(readFileSync(attachment(cids[6]), 'utf8')).toBe('Attachment contents');
+ expect((await orkas.invoke<any>('conversations.get', { cid: cids[6] })).conversation).toMatchObject({ title: 'Attachment-only draft' });
const prefix = projectId ? `cloud/projects/${projectId}` : 'cloud';
const batch = batches.find((b: any) => b.items.some((item: any) => item.path === `${prefix}/chats/${cids[0]}.jsonl`));
expect(batch).toBeTruthy();
diff --git a/test/main/features/chat_attachments.test.ts b/test/main/features/chat_attachments.test.ts
index f6f67beb..55c48a37 100644
--- a/test/main/features/chat_attachments.test.ts
+++ b/test/main/features/chat_attachments.test.ts
@@ -813,6 +813,19 @@ describe('chat_attachments › deleteAttachment', () => {
});
describe('chat_attachments › purgeByCid', () => {
+ it('removes nested files and empty directories without following symlinks', async () => {
+ const m = await loadMod();
+ const nested = path.join(attDir(), 'folder', 'inner');
+ fs.mkdirSync(nested, { recursive: true });
+ fs.mkdirSync(path.join(nested, 'empty'));
+ fs.writeFileSync(path.join(nested, 'draft.txt'), 'Nested attachment');
+ const outside = path.join(tmpDir, 'outside');
+ fs.mkdirSync(outside); fs.writeFileSync(path.join(outside, 'keep.txt'), 'Keep');
+ fs.symlinkSync(outside, path.join(attDir(), 'link'), process.platform === 'win32' ? 'junction' : 'dir');
+ expect(await m.purgeByCid(UID, CID)).toBeGreaterThan(0);
+ expect(fs.existsSync(attDir())).toBe(false);
+ expect(fs.readFileSync(path.join(outside, 'keep.txt'), 'utf8')).toBe('Keep');
+ });
it('wipes the entire <cid>/ dir', async () => {
const m = await loadMod();
await m.uploadAttachment(UID, CID, 'a.txt', Buffer.from('x'));
diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.ts
index 8ca99621..5f12509f 100644
--- a/test/main/features/chats.test.ts
+++ b/test/main/features/chats.test.ts
@@ -56,6 +56,36 @@ async function loadChats() {
return import('../../../src/main/features/chats');
}
+describe('local deletion ownership and explicit restoration', () => {
+ it('keeps neighboring task sessions while removing every owned sidecar', async () => {
+ const chats = await loadChats();
+ await chats.createConversation(TEST_UID, { conversationId: 'task-a', title: 'Remove' });
+ await chats.createConversation(TEST_UID, { conversationId: 'task-a-extra', title: 'Keep' });
+ const dir = path.join(tmpDir, TEST_UID, 'cloud', 'sessions');
+ fs.mkdirSync(dir, { recursive: true });
+ const own = ['gmember-task-a-agent-a.jsonl', 'gmember-task-a-agent-a.tool-results'];
+ const neighbor = ['gmember-task-a-extra-agent-a.jsonl', 'gmember-task-a-extra-agent-a.tool-results'];
+ for (const name of [...own, ...neighbor]) fs.writeFileSync(path.join(dir, name), name);
+ expect(await chats.deleteConversation(TEST_UID, 'task-a')).toBe(true);
+ for (const name of own) expect(fs.existsSync(path.join(dir, name)), name).toBe(false);
+ for (const name of neighbor) expect(fs.readFileSync(path.join(dir, name), 'utf8')).toBe(name);
+ expect((await chats.listConversations(TEST_UID)).map(c => c.conversation_id)).toEqual(['task-a-extra']);
+ });
+
+ it('keeps an explicitly deleted task hidden when payload bytes reappear with a newer mtime', async () => {
+ const chats = await loadChats();
+ await chats.createConversation(TEST_UID, { conversationId: 'deleted-local', title: 'Deleted' });
+ const file = path.join(tmpDir, TEST_UID, 'cloud', 'chats', 'deleted-local.jsonl');
+ expect(await chats.deleteConversation(TEST_UID, 'deleted-local')).toBe(true);
+ fs.writeFileSync(file, JSON.stringify({ from: 'user', content: 'Reappeared old payload' }) + '\n');
+ const future = new Date(Date.now() + 10000); fs.utimesSync(file, future, future);
+ await chats.repairConversationIndex(TEST_UID);
+ expect(await chats.listConversations(TEST_UID)).toEqual([]);
+ const rows = JSON.parse(fs.readFileSync(path.join(path.dirname(file), '_index.json'), 'utf8'));
+ expect(rows.find((row: any) => row.conversation_id === 'deleted-local').deleted_at).toBeTruthy();
+ });
+});
+
describe('chats › createConversation', () => {
it('generates a 12-hex cid and writes it to _index.json', async () => {
const chats = await loadChats();
diff --git a/test/main/features/recycle_bin.test.ts b/test/main/features/recycle_bin.test.ts
index 2775d53f..0e5cf6cf 100644
--- a/test/main/features/recycle_bin.test.ts
+++ b/test/main/features/recycle_bin.test.ts
@@ -80,6 +80,69 @@ afterEach(async () => {
});
describe('global recycle bin', () => {
+ it.each([false, true])('archives and restores metadata and drafts without a transcript (project=%s)', async project => {
+ const paths = await import('../../../src/main/paths');
+ const recycle = await import('../../../src/main/features/recycle_bin');
+ const cid = 'unsent-task', pid = 'draft-project';
+ const root = path.join(paths.userCloudRoot(UID), ...(project ? ['projects', pid] : []));
+ const group = path.join(root, 'chats', cid);
+ const draftDir = path.join(root, 'chat_attachments', cid);
+ const draft = path.join(draftDir, 'folder', 'draft.txt');
+ const index = path.join(root, 'chats', '_index.json');
+ const row = { conversation_id: cid, kind: 'normal', title: 'Unsent draft', session_id: `gconv-${cid}`,
+ created_at: '2020-01-01', updated_at: '2020-01-01', ...(project ? { project_id: pid } : {}) };
+ await fsp.mkdir(group, { recursive: true });
+ await fsp.mkdir(path.dirname(draft), { recursive: true });
+ await fsp.writeFile(path.join(group, 'meta.json'), JSON.stringify(row));
+ await fsp.writeFile(index, JSON.stringify([row]));
+ await fsp.writeFile(draft, 'Unsent attachment');
+ if (project) await fsp.writeFile(paths.projectMetaFile(UID, pid), JSON.stringify({ project_id: pid, name: 'Draft project' }));
+ const batch = project ? await recycle.createAppRecycleBatchForConversations(UID, [cid])
+ : await recycle.createAppRecycleBatchForConversation(UID, cid);
+ expect(batch?.items).toHaveLength(2);
+ expect(batch?.display_items).toEqual([expect.objectContaining({ category: 'conversation', id: cid, title: 'Unsent draft' })]);
+ await fsp.rm(group, { recursive: true });
+ await fsp.rm(draftDir, { recursive: true });
+ await fsp.writeFile(index, '[]');
+ const restored = await recycle.restoreRecycleBatch(UID, batch!.id);
+ expect(restored.restored_paths).toHaveLength(2);
+ expect(restored.reactivated_paths).toHaveLength(1);
+ expect(restored.failed_paths).toEqual([]);
+ expect(await fsp.readFile(draft, 'utf8')).toBe('Unsent attachment');
+ const [restoredRow] = JSON.parse(await fsp.readFile(index, 'utf8'));
+ expect(restoredRow).toMatchObject({ conversation_id: cid, title: row.title, created_at: row.created_at });
+ expect(restoredRow.project_id || null).toBe(project ? pid : null);
+ expect(fs.existsSync(path.join(root, 'chats', `${cid}.jsonl`))).toBe(false);
+ });
+
+ it('rejects a transcript that disappears after inventory instead of treating it as an unsent task', async () => {
+ const paths = await import('../../../src/main/paths');
+ const file = path.join(paths.userChatsDir(UID), 'existing-task.jsonl');
+ await fsp.mkdir(path.dirname(file), { recursive: true });
+ await fsp.writeFile(file, 'Existing history');
+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
+ vi.doMock('node:fs/promises', () => ({ ...actual, copyFile: vi.fn(async (source, destination, flags) => {
+ if (String(source) === file) throw Object.assign(new Error('simulated disappearing file'), { code: 'ENOENT' });
+ return actual.copyFile(source, destination, flags);
+ }) }));
+ vi.resetModules();
+ try {
+ const recycle = await import('../../../src/main/features/recycle_bin');
+ await expect(recycle.createAppRecycleBatchForConversation(UID, 'existing-task')).rejects.toThrow('recycle_archive_failed');
+ expect(await recycle.listRecycleBatches(UID)).toEqual([]);
+ expect(await fsp.readFile(file, 'utf8')).toBe('Existing history');
+ } finally { vi.doUnmock('node:fs/promises'); vi.resetModules(); }
+ });
+ it('keeps drafts when neither a transcript nor recoverable task metadata exists', async () => {
+ const paths = await import('../../../src/main/paths');
+ const recycle = await import('../../../src/main/features/recycle_bin');
+ const draft = path.join(paths.chatAttachmentDir(UID, 'incomplete-task'), 'draft.txt');
+ await fsp.mkdir(path.dirname(draft), { recursive: true });
+ await fsp.writeFile(draft, 'Keep the draft');
+ await expect(recycle.createAppRecycleBatchForConversation(UID, 'incomplete-task')).rejects.toThrow('recycle_archive_failed');
+ expect(await recycle.listRecycleBatches(UID)).toEqual([]);
+ expect(await fsp.readFile(draft, 'utf8')).toBe('Keep the draft');
+ });
it('permanently deletes only the selected archive while preserving live data and other accounts', async () => {
const paths = await import('../../../src/main/paths');
const recycle = await import('../../../src/main/features/recycle_bin');
diff --git a/test/main/features/task-cleanup.test.ts b/test/main/features/task-cleanup.test.ts
index 417e4546..33815175 100644
--- a/test/main/features/task-cleanup.test.ts
+++ b/test/main/features/task-cleanup.test.ts
@@ -4,13 +4,14 @@ import os from 'node:os';
import path from 'node:path';
const mocks = vi.hoisted(() => ({ rows: [] as any[], quiet: true,
- archive: vi.fn(), remove: vi.fn(), discard: vi.fn() }));
+ archive: vi.fn(), remove: vi.fn(), discard: vi.fn(), abort: vi.fn() }));
vi.mock('../../../src/main/features/chats', () => ({
listCleanupConversationRows: async () => mocks.rows,
getConversationMetadata: async (_uid: string, cid: string) => mocks.rows.find(r => r.conversation_id === cid) || null,
deleteConversation: (...args: any[]) => mocks.remove(...args),
}));
-vi.mock('../../../src/main/features/group_chat/bus', () => ({ isQuiescent: () => mocks.quiet }));
+vi.mock('../../../src/main/features/group_chat/bus', () => ({ isQuiescent: () => mocks.quiet, abort: (...args: any[]) => mocks.abort(...args) }));
+vi.mock('../../../src/main/features/projects', () => ({ getProject: async (_uid: string, projectId: string) => ({ project_id: projectId, name: 'Fixture project' }) }));
vi.mock('../../../src/main/features/recycle_bin', () => ({
createAppRecycleBatchForConversation: (...args: any[]) => mocks.archive(...args),
deleteRecycleBatch: (...args: any[]) => mocks.discard(...args),
@@ -41,9 +42,17 @@ beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-cleanup-'));
previous = process.env.ORKAS_WORKSPACE_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = root;
- vi.resetModules(); vi.clearAllMocks(); mocks.rows = []; mocks.quiet = true;
+ vi.resetModules(); vi.resetAllMocks(); mocks.rows = []; mocks.quiet = true;
mocks.archive.mockResolvedValue({ id: 'backup', items: [{ path: 'history' }] });
mocks.discard.mockResolvedValue(undefined);
+ mocks.abort.mockImplementation(async (_uid, cid) => {
+ const { conversationLayout } = await import('../../../src/main/util/project-layout');
+ const row = mocks.rows.find(r => r.conversation_id === cid);
+ const layout = conversationLayout(uid, cid, row.project_id || null);
+ row.updated_at = new Date().toISOString();
+ fs.writeFileSync(layout.stateFile, JSON.stringify({ status: 'aborted', in_flight: [], last_active_at: row.updated_at }));
+ mocks.quiet = true;
+ });
mocks.remove.mockImplementation(async (_uid, cid, _hint, guard) => {
const row = mocks.rows.find(r => r.conversation_id === cid);
if (!await guard(row)) return false;
@@ -63,6 +72,164 @@ afterEach(async () => {
});
describe('safe historical task cleanup', () => {
+ it.each([null, 'p1'])('uses the sidebar metadata timestamp for cleanup in project %s', async projectId => {
+ vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-10-17T06:00:00Z'));
+ for (const [cid, updated_at] of [['recent-metadata', '2026-10-16T14:15:58.377Z'], ['old-metadata', '2026-09-20T12:00:00+08:00']]) {
+ const { layout } = await seed(cid, { ...(projectId ? { project_id: projectId } : {}),
+ created_at: '2026-09-10T19:50:45+08:00', updated_at });
+ fs.writeFileSync(layout.messageFile, JSON.stringify({ ts: '2026-09-10T20:04:24+08:00', text: 'Historical response' }));
+ fs.writeFileSync(layout.stateFile, JSON.stringify({ status: 'idle', in_flight: [], last_active_at: '2026-09-21T00:00:00Z' }));
+ }
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 14 });
+ expect(p.rows).toEqual([expect.objectContaining({ cid: 'old-metadata', activeAt: '2026-09-20T04:00:00.000Z', selectable: true })]);
+ expect(await api.remove(uid, p.token, 'old-metadata')).toEqual({ status: 'deleted' });
+ expect(mocks.rows.map(row => row.conversation_id)).toEqual(['recent-metadata']);
+ });
+ it('refreshes and pages cleanup without reading transcript bodies', async () => {
+ const histories = new Set<string>();
+ const line = JSON.stringify({ ts: old, text: 'x'.repeat(64 * 1024) }) + '\n';
+ for (let i = 0; i < 26; i++) {
+ const { layout } = await seed(`history-${i}`, i === 25 ? { project_id: 'p1' } : {});
+ fs.writeFileSync(layout.messageFile, line.repeat(i === 0 ? 32 : 1));
+ histories.add(layout.messageFile);
+ }
+ const api = await import('../../../src/main/features/task_cleanup');
+ // Observe disk access, not elapsed time: this catches a scan even on a fast SSD.
+ const reads = [vi.spyOn(fs, 'createReadStream'), vi.spyOn(fs, 'open'), vi.spyOn(fs, 'openSync'), vi.spyOn(fs, 'readFileSync'),
+ vi.spyOn(fs.promises, 'readFile'), vi.spyOn(fs.promises, 'open')];
+ for (const days of [14, 30, 180]) {
+ const p = await api.preview(uid, { days });
+ expect(p.total).toBe(26);
+ expect(api.page(uid, p.token, 20).rows).toHaveLength(6);
+ expect(api.page(uid, p.token, 0, { projectId: 'p1' }).rows).toHaveLength(1);
+ }
+ for (const read of reads) expect(read.mock.calls.filter(args => histories.has(String(args[0]))).length).toBe(0);
+ expect(mocks.archive).not.toHaveBeenCalled();
+ });
+ it.each(['created_at', 'updated_at'])('keeps a task with an invalid %s out of cleanup', async field => {
+ await seed('invalid-clock', { [field]: 'invalid-time' });
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 14 });
+ expect(p.rows).toEqual([]);
+ await expect(api.remove(uid, p.token, 'invalid-clock')).rejects.toThrow('invalid_cleanup_selection');
+ expect(mocks.archive).not.toHaveBeenCalled();
+ expect(mocks.rows).toHaveLength(1);
+ });
+ it('keeps the preview cutoff fixed while time passes and admits newly aged tasks only after refresh', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-10-17T06:00:00Z'));
+ await seed('already-old');
+ await seed('at-cutoff', { updated_at: '2026-10-03T14:00:00+08:00' });
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 14 });
+ expect(p.rows.map(row => row.cid)).toEqual(['already-old']);
+ clock.mockReturnValue(Date.parse('2026-10-17T06:01:00Z'));
+ expect(api.page(uid, p.token, 0).rows.map(row => row.cid)).toEqual(['already-old']);
+ await expect(api.remove(uid, p.token, 'at-cutoff')).rejects.toThrow('invalid_cleanup_selection');
+ expect(await api.remove(uid, p.token, 'already-old')).toEqual({ status: 'deleted' });
+ const refreshed = await api.preview(uid, { days: 14 });
+ expect(refreshed.rows.map(row => row.cid)).toEqual(['at-cutoff']);
+ expect(() => api.page(uid, p.token, 0)).toThrow('cleanup_preview_expired');
+ });
+ it('retains metadata refreshed after selection without creating a backup or stopping the task', async () => {
+ const { row } = await seed('changed-before-confirm', {}, 'running');
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 14 });
+ row.updated_at = new Date().toISOString();
+ expect(await api.remove(uid, p.token, row.conversation_id)).toEqual({ status: 'skipped' });
+ expect(await api.remove(uid, p.token, row.conversation_id)).toEqual({ status: 'skipped' });
+ expect(mocks.abort).not.toHaveBeenCalled();
+ expect(mocks.archive).not.toHaveBeenCalled();
+ expect(mocks.remove).not.toHaveBeenCalled();
+ expect((await api.preview(uid, { days: 14 })).rows).toEqual([]);
+ expect(mocks.rows).toEqual([row]);
+ });
+ it.each(['message', 'replacement', 'metadata'])('preserves a task changed through %s during backup', async change => {
+ const { row, layout } = await seed('changed');
+ fs.writeFileSync(layout.messageFile, JSON.stringify({ ts: old, text: 'original' }));
+ fs.utimesSync(layout.messageFile, new Date(old), new Date(old));
+ const before = fs.statSync(layout.messageFile);
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 14 });
+ mocks.archive.mockImplementationOnce(async () => {
+ if (change === 'message') fs.appendFileSync(layout.messageFile, '\n' + JSON.stringify({ ts: old, text: 'Imported work during backup' }));
+ if (change === 'replacement') {
+ const replacement = layout.messageFile + '.replacement';
+ fs.writeFileSync(replacement, JSON.stringify({ ts: old, text: 'modified' }));
+ fs.utimesSync(replacement, before.atime, before.mtime);
+ fs.renameSync(replacement, layout.messageFile);
+ expect(fs.statSync(layout.messageFile)).toMatchObject({ size: before.size, mtimeMs: before.mtimeMs });
+ }
+ // Even an imported edit still older than the cutoff invalidates this backup.
+ if (change === 'metadata') row.updated_at = '2020-02-01T00:00:00Z';
+ return { id: 'backup', items: [{}] };
+ });
+ expect(await api.remove(uid, p.token, 'changed')).toEqual({ status: 'skipped' });
+ expect(mocks.rows).toHaveLength(1);
+ expect(mocks.discard).toHaveBeenCalledWith(uid, 'backup');
+ });
+ it.each(['queued', 'running'])('stops selected %s history before backing up and deleting, including stop-time updates', async status => {
+ await seed('active', { project_id: 'p1' }, status); mocks.quiet = false;
+ const api = await import('../../../src/main/features/task_cleanup');
+ const preview = await api.preview(uid, { days: 30 });
+ expect(preview.rows[0]).toMatchObject({ selectable: true, blocked: 'busy' });
+ expect(preview.selectableTotal).toBe(1);
+ expect(preview.entries[0]).toMatchObject({ selectableTotal: 1 });
+ expect(mocks.abort).not.toHaveBeenCalled();
+ let completeStop!: () => void;
+ const stop = mocks.abort.getMockImplementation()!;
+ mocks.abort.mockImplementationOnce(async (...args) => { await new Promise<void>(resolve => { completeStop = resolve; }); await stop(...args); });
+ const pending = api.remove(uid, preview.token, 'active');
+ await vi.waitFor(() => expect(completeStop).toBeTypeOf('function'));
+ expect(mocks.archive).not.toHaveBeenCalled(); expect(mocks.remove).not.toHaveBeenCalled();
+ completeStop();
+ expect(await pending).toEqual({ status: 'deleted' });
+ expect(mocks.abort).toHaveBeenCalledExactlyOnceWith(uid, 'active');
+ expect(mocks.rows).toEqual([]);
+ });
+ it.each(['rejects', 'still-running'])('keeps history when stopping %s and permits retry', async failure => {
+ await seed('active', {}, 'running'); mocks.quiet = false;
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 30 });
+ mocks.abort.mockImplementationOnce(async () => { if (failure === 'rejects') throw new Error('stop failed'); });
+ await expect(api.remove(uid, p.token, 'active')).rejects.toThrow('cleanup_failed');
+ expect(mocks.archive).not.toHaveBeenCalled(); expect(mocks.remove).not.toHaveBeenCalled();
+ expect(await api.remove(uid, p.token, 'active')).toEqual({ status: 'deleted' });
+ });
+ it('retries a failed backup after stop without treating its own stop as new task activity', async () => {
+ await seed('active', {}, 'running');
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 30 });
+ mocks.archive.mockRejectedValueOnce(new Error('archive unavailable'));
+ await expect(api.remove(uid, p.token, 'active')).rejects.toThrow('cleanup_failed');
+ expect(mocks.rows).toHaveLength(1);
+ expect(await api.remove(uid, p.token, 'active')).toEqual({ status: 'deleted' });
+ expect(mocks.abort).toHaveBeenCalledTimes(1);
+ });
+ it.each(['runtime', 'state', 'recent', 'project'])('preserves stopped history changed by %s during backup', async change => {
+ const { row, layout } = await seed('active', {}, 'running');
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 30 });
+ mocks.archive.mockImplementationOnce(async () => {
+ if (change === 'runtime') mocks.quiet = false;
+ if (change === 'state') fs.writeFileSync(layout.stateFile, JSON.stringify({ status: 'idle', in_flight: [], last_active_at: old }));
+ if (change === 'recent') row.updated_at = new Date(Date.now() + 1000).toISOString();
+ if (change === 'project') row.project_id = 'another';
+ return { id: 'backup', items: [{}] };
+ });
+ expect(await api.remove(uid, p.token, 'active')).toEqual({ status: 'skipped' });
+ expect(mocks.rows).toHaveLength(1);
+ expect(mocks.discard).toHaveBeenCalledWith(uid, 'backup');
+ });
+ it('never stops unreadable history even when the runtime is busy', async () => {
+ const { layout } = await seed('corrupt', {}, 'running'); mocks.quiet = false;
+ fs.writeFileSync(layout.stateFile, '{');
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 30 });
+ expect(p.rows[0]).toMatchObject({ selectable: false, blocked: 'unknown' });
+ expect(await api.remove(uid, p.token, 'corrupt')).toEqual({ status: 'skipped' });
+ expect(mocks.abort).not.toHaveBeenCalled(); expect(mocks.archive).not.toHaveBeenCalled();
+ });
it('keeps corrupt state and a recent completion even when its index is stale', async () => {
const corrupt = await seed('corrupt');
fs.writeFileSync(corrupt.layout.stateFile, '{');
@@ -71,9 +238,9 @@ describe('safe historical task cleanup', () => {
{ created_by: 'user', created_at: old, status: 'done', ended_at: new Date().toISOString() },
]));
const api = await import('../../../src/main/features/task_cleanup');
- expect((await api.preview(uid, { days: 90, protectedIds: [] })).total).toBe(0);
+ expect((await api.preview(uid, { days: 90, protectedIds: [] })).rows).toMatchObject([{ cid: 'corrupt', selectable: false, blocked: 'unknown' }]);
});
- it('keeps a failed sibling of the latest user request while allowing an older recovered failure', async () => {
+ it('includes failed and recovered work without requiring successful completion', async () => {
const first = await seed('mixed');
const second = await seed('recovered');
const prior = { created_by: 'user', source_msg_id: 'prior', created_at: '2019-01-01', ended_at: old, status: 'failed' };
@@ -81,7 +248,7 @@ describe('safe historical task cleanup', () => {
fs.writeFileSync(path.join(path.dirname(first.layout.stateFile), 'tasks.json'), JSON.stringify([done, { ...done, status: 'failed' }]));
fs.writeFileSync(path.join(path.dirname(second.layout.stateFile), 'tasks.json'), JSON.stringify([prior, done]));
const api = await import('../../../src/main/features/task_cleanup');
- expect((await api.preview(uid, { days: 90, protectedIds: [] })).rows.map(r => r.cid)).toEqual(['recovered']);
+ expect((await api.preview(uid, { days: 90, protectedIds: [] })).rows.map(r => r.cid)).toEqual(['mixed', 'recovered']);
});
it('expires previews and never uses an old receipt after restart or expiry', async () => {
await seed(); const api = await import('../../../src/main/features/task_cleanup');
@@ -91,7 +258,7 @@ describe('safe historical task cleanup', () => {
await expect(api.remove(uid, p.token, 'old-done')).rejects.toThrow('cleanup_preview_expired');
expect(mocks.archive).not.toHaveBeenCalled();
});
- it('selects old completed tasks inside and outside projects, retaining protected and uncertain work', async () => {
+ it('includes old history and marks active work without excluding pins, drafts, unread or automation', async () => {
await seed();
await seed('pinned', { pinned_at: old }); await seed('project', { project_id: 'p1' });
await seed('auto', { origin_auto_task_id: 'a1' }); await seed('edit', { kind: 'edit' });
@@ -101,7 +268,10 @@ describe('safe historical task cleanup', () => {
const unknown = await seed('unknown'); fs.unlinkSync(path.join(path.dirname(unknown.layout.stateFile), 'tasks.json'));
const api = await import('../../../src/main/features/task_cleanup');
const preview = await api.preview(uid, { days: 90, protectedIds: ['unread', 'draft'] });
- expect(preview.total).toBe(2); expect(preview.rows.map(r => r.cid)).toEqual(['old-done', 'project']);
+ expect(preview.total).toBe(14);
+ expect(preview.rows.filter(r => r.selectable).map(r => r.cid).sort()).toEqual(['auto', 'blocked', 'cancelled', 'draft', 'failed', 'old-done', 'pinned', 'project', 'stopped', 'unknown', 'unread', 'waiting_input', 'queued', 'running'].sort());
+ expect(preview.rows.find(r => r.cid === 'auto')).toMatchObject({ automation: true });
+ expect(preview.rows.find(r => r.cid === 'pinned')).toMatchObject({ pinned: true });
expect(mocks.archive).not.toHaveBeenCalled(); expect(mocks.remove).not.toHaveBeenCalled();
});
it('deletes a completed project task using its frozen project membership', async () => {
@@ -112,13 +282,15 @@ describe('safe historical task cleanup', () => {
expect(await api.remove(uid, p.token, 'project-done')).toEqual({ status: 'deleted' });
expect(mocks.remove).toHaveBeenCalledWith(uid, 'project-done', 'p1', expect.any(Function));
});
- it('protects project task drafts, unread, pinned, automated and unfinished work', async () => {
+ it('allows project history with annotations and running or queued work', async () => {
for (const status of ['failed', 'stopped', 'running', 'queued', 'waiting_input']) await seed(status, { project_id: 'p1' }, status);
await seed('pinned-project', { project_id: 'p1', pinned_at: old });
await seed('auto-project', { project_id: 'p1', origin_auto_task_id: 'a1' });
await seed('unread-project', { project_id: 'p1' }); await seed('draft-project', { project_id: 'p1' });
const api = await import('../../../src/main/features/task_cleanup');
- expect((await api.preview(uid, { days: 90, protectedIds: ['unread-project', 'draft-project'] })).total).toBe(0);
+ const p = await api.preview(uid, { days: 90, protectedIds: ['unread-project', 'draft-project'] });
+ expect(p.total).toBe(9);
+ expect(p.rows.filter(r => r.selectable).map(r => r.cid).sort()).toEqual(['failed', 'stopped', 'waiting_input', 'pinned-project', 'auto-project', 'unread-project', 'draft-project', 'running', 'queued'].sort());
});
it.each([null, 'p2'])('skips a project task relocated to %s after preview', async projectId => {
const { row } = await seed('moved-project', { project_id: 'p1' });
@@ -128,7 +300,7 @@ describe('safe historical task cleanup', () => {
expect(await api.remove(uid, p.token, 'moved-project')).toEqual({ status: 'skipped' });
expect(mocks.archive).not.toHaveBeenCalled();
});
- it.each([30, 90, 180])('uses the exact %i-day cutoff for every activity source, independent of timezone and file mtime', async days => {
+ it.each([7, 14, 30, 60, 90, 180])('uses the exact %i-day cutoff for every activity source, independent of timezone and file mtime', async days => {
const now = Date.parse('2026-10-16T14:10:00Z');
vi.spyOn(Date, 'now').mockReturnValue(now);
const expected: string[] = [];
@@ -170,12 +342,11 @@ describe('safe historical task cleanup', () => {
await expect(api.remove(uid, preview.token, 'new-arrival')).rejects.toThrow();
expect(mocks.archive).not.toHaveBeenCalled();
});
- it.each(['pinned', 'recent', 'project', 'running', 'waiting'])('skips a task changed to %s during its backup', async change => {
+ it.each(['recent', 'project', 'running', 'waiting'])('skips a task changed to %s during its backup', async change => {
const { row, layout } = await seed();
const api = await import('../../../src/main/features/task_cleanup');
const p = await api.preview(uid, { days: 90, protectedIds: [] });
mocks.archive.mockImplementationOnce(async () => {
- if (change === 'pinned') row.pinned_at = old;
if (change === 'recent') row.updated_at = new Date().toISOString();
if (change === 'project') row.project_id = 'p1';
if (change === 'running') mocks.quiet = false;
@@ -221,6 +392,30 @@ describe('safe historical task cleanup', () => {
await expect(api.remove(uid, p.token, 'old-done')).rejects.toThrow();
expect(mocks.discard).not.toHaveBeenCalled();
});
+ it.each(['unchanged', 'edited', 'added', 'symlink'])('handles nested attachments safely when %s', async change => {
+ await seed('nested');
+ const { chatAttachmentDirForConversation } = await import('../../../src/main/util/project-layout');
+ const dir = path.join(chatAttachmentDirForConversation(uid, 'nested'), 'folder', 'inner');
+ fs.mkdirSync(dir, { recursive: true });
+ const file = path.join(dir, 'draft.txt');
+ fs.writeFileSync(file, 'Original draft');
+ if (change === 'symlink') fs.symlinkSync(root, path.join(dir, 'outside'), process.platform === 'win32' ? 'junction' : 'dir');
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 30 });
+ mocks.archive.mockImplementationOnce(async () => {
+ if (change === 'edited') fs.writeFileSync(file, 'Edited draft during backup');
+ if (change === 'added') fs.writeFileSync(path.join(dir, 'new.txt'), 'New draft');
+ return { id: 'backup', items: [{}] };
+ });
+ if (change === 'symlink') {
+ await expect(api.remove(uid, p.token, 'nested')).rejects.toThrow('cleanup_failed');
+ expect(mocks.archive).not.toHaveBeenCalled();
+ } else {
+ expect(await api.remove(uid, p.token, 'nested')).toEqual({ status: change === 'unchanged' ? 'deleted' : 'skipped' });
+ expect(mocks.discard).toHaveBeenCalledTimes(change === 'unchanged' ? 0 : 1);
+ }
+ expect(mocks.rows).toHaveLength(change === 'unchanged' ? 0 : 1);
+ });
it('rejects cross-account, stale and invalid requests without mutation', async () => {
await seed(); const api = await import('../../../src/main/features/task_cleanup');
const p = await api.preview(uid, { days: 90, protectedIds: [] });
@@ -242,4 +437,28 @@ describe('safe historical task cleanup', () => {
finish({ id: 'backup', items: [{}] }); await first;
expect(mocks.archive).toHaveBeenCalledTimes(1);
});
+ it('pages project children separately and leaves personal tasks at the root', async () => {
+ for (let i = 0; i < 25; i++) await seed('child-' + String(i).padStart(2, '0'), { project_id: 'p1' });
+ await seed('personal');
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 30, protectedIds: [] });
+ expect(p.entries).toHaveLength(2);
+ expect(p.entries[0]).toMatchObject({ type: 'project', projectId: 'p1', total: 25, selectableTotal: 25 });
+ expect(p.entries[1]).toMatchObject({ cid: 'personal', projectId: null });
+ const children = api.page(uid, p.token, 20, { projectId: 'p1' });
+ expect(children.rows.map(r => r.cid)).toEqual(['child-20', 'child-21', 'child-22', 'child-23', 'child-24']);
+ expect(children.nextOffset).toBeNull();
+ expect(() => api.page(uid, p.token, 0, { projectId: 'another' })).toThrow();
+ });
+ it('allows an explicitly selected pinned failed task and existing attachment draft', async () => {
+ const { layout } = await seed('pinned-draft', { pinned_at: old }, 'failed');
+ const { chatAttachmentDirForConversation } = await import('../../../src/main/util/project-layout');
+ const dir = chatAttachmentDirForConversation(uid, 'pinned-draft');
+ fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, 'draft.txt'), 'Draft');
+ const api = await import('../../../src/main/features/task_cleanup');
+ const p = await api.preview(uid, { days: 14, protectedIds: ['pinned-draft'] });
+ expect(p.rows[0]).toMatchObject({ selectable: true, pinned: true, draft: true });
+ expect(await api.remove(uid, p.token, 'pinned-draft')).toEqual({ status: 'deleted' });
+ });
+
});
diff --git a/test/main/ipc/home-continuation.test.ts b/test/main/ipc/home-continuation.test.ts
index eb7817ec..8a42498b 100644
--- a/test/main/ipc/home-continuation.test.ts
+++ b/test/main/ipc/home-continuation.test.ts
@@ -94,16 +94,21 @@ describe('projects.tasks.listOpen', () => {
]);
});
- it('caps the rows but still reports how many unfinished to-dos exist', async () => {
+ it('returns every open to-do for expansion while preserving bounded legacy requests', async () => {
const tasks = await import('../../../src/main/features/project_tasks');
- for (let i = 0; i < 5; i += 1) {
- const result = await at(`2026-10-0${i + 1}T08:00:00.000Z`, () => tasks.createTask(TEST_UID, '', { content: `Item ${i}` }));
+ for (let i = 0; i < 26; i += 1) {
+ const result = await at(`2026-10-${String(i + 1).padStart(2, '0')}T08:00:00.000Z`, () => tasks.createTask(TEST_UID, '', { content: `Item ${i}` }));
expect(result.ok).toBe(true);
}
const res = await invoke('projects.tasks.listOpen', { limit: 3 });
expect(res.tasks).toHaveLength(3);
- expect(res.total).toBe(5);
+ expect(res.total).toBe(26);
expect(res.tasks[0].updated_at > res.tasks[1].updated_at).toBe(true);
+ expect((await invoke('projects.tasks.listOpen', {})).tasks).toHaveLength(3);
+ expect((await invoke('projects.tasks.listOpen', { limit: 100, all: 'true' })).tasks).toHaveLength(20);
+ const all = await invoke('projects.tasks.listOpen', { all: true });
+ expect(all.total).toBe(26);
+ expect(all.tasks.map((task: any) => task.content)).toEqual(Array.from({ length: 26 }, (_, i) => `Item ${25 - i}`));
});
// The home page repeats this listing on every visit and, while visible, on
diff --git a/test/renderer/conversation-cache-test-source.ts b/test/renderer/conversation-cache-test-source.ts
index 796def1d..d2649c05 100644
--- a/test/renderer/conversation-cache-test-source.ts
+++ b/test/renderer/conversation-cache-test-source.ts
@@ -9,3 +9,5 @@ const parsed = ts.createSourceFile('conversation.js', source, ts.ScriptTarget.La
const names = new Set(['_replaceConversationSlice', '_appendConversationSlice', '_cacheCreatedConversation']);
export const conversationCacheSource = parsed.statements.filter(node =>
ts.isFunctionDeclaration(node) && names.has(node.name?.text || '')).map(node => node.getText(parsed)).join('\n');
+export const conversationRemovalSource = parsed.statements.filter(node =>
+ ts.isFunctionDeclaration(node) && node.name?.text === '_removeConversationFromSidebar').map(node => node.getText(parsed)).join('\n');
diff --git a/test/renderer/conversation-sidebar.test.ts b/test/renderer/conversation-sidebar.test.ts
index 582893e2..0f605762 100644
--- a/test/renderer/conversation-sidebar.test.ts
+++ b/test/renderer/conversation-sidebar.test.ts
@@ -1170,6 +1170,36 @@ describe('conversation history response ordering', () => {
};
}
+ it.each([null, 'project-old'])('hydrates the title and project of history outside the sidebar slice (%s)', async projectId => {
+ const s = setup();
+ const title = { textContent: '', hidden: false };
+ const meta = { innerHTML: '' };
+ const getElement = s.context.document.getElementById;
+ s.context.document.getElementById = (id: string) => id === 'chat-header-title' ? title
+ : id === 'chat-header-meta' ? meta : getElement(id);
+ s.context.getCommanderProjectIdName = () => 'Archived project';
+ s.context.conversations = [{ conversation_id: 'other', title: 'Unrelated task' }];
+ const loading = s.context.loadConversationHistory('c1');
+ s.resolve(response([question, answer], { conversation: {
+ conversation_id: 'c1', title: 'Original historical task', project_id: projectId,
+ processing: false, created_at: '2020-01-01T00:00:00Z',
+ } }));
+ await loading;
+ expect(title.textContent).toBe('Original historical task');
+ expect(meta.innerHTML.includes('Archived project')).toBe(!!projectId);
+ expect(s.context.conversations.find((row: any) => row.conversation_id === 'other').title).toBe('Unrelated task');
+ expect(s.ids()).toEqual(['u1', 'a1']);
+ });
+ it('does not overwrite a newer cached title with an in-flight historical snapshot', async () => {
+ const s = setup();
+ const loading = s.context.loadConversationHistory('c1');
+ s.context.conversations = [{ conversation_id: 'c1', title: 'Renamed while loading', title_manually_set: true }];
+ s.resolve(response([question, answer], { conversation: {
+ conversation_id: 'c1', title: 'Old snapshot', processing: false,
+ } }));
+ await loading;
+ expect(s.context.conversations[0].title).toBe('Renamed while loading');
+ });
it.each(['success', 'failure', 'missing'] as const)('ignores an older request after a newer load succeeds: %s', async (outcome) => {
const s = setup();
const older = s.context.loadConversationHistory('c1');
@@ -1908,6 +1938,90 @@ describe('conversation sidebar task row actions', () => {
expect(html).not.toContain('data-conv-bucket-more');
});
+ it.each(['startup', 'project', 'unprojected'])('does not resurrect a deleted task from an older %s response, but permits restore', async (mode) => {
+ const context = loadConversationRenderer();
+ const row = { conversation_id: 'removed', project_id: mode === 'project' ? 'p1' : null };
+ context.conversations = [row, { conversation_id: 'keep' }];
+ context.renderConversationList = vi.fn();
+ let release!: (value: any) => void;
+ context.apiFetch = vi.fn(() => new Promise(resolve => { release = resolve; }));
+ const load = () => mode === 'startup' ? context.loadConversations()
+ : mode === 'project' ? context.loadConversationProject('p1', { reset: true })
+ : context.loadUnprojectedConversations({ reset: true });
+ const pending = load();
+ context._removeConversationFromSidebar('removed');
+ release({ json: async () => ({ ok: true, conversations: [row], total: 1, next_offset: null }) });
+ await pending;
+ expect(context.conversations.map((c: any) => c.conversation_id)).toEqual(['keep']);
+ context.apiFetch.mockResolvedValue({ json: async () => ({ ok: true, conversations: [row], total: 1, next_offset: null }) });
+ await load();
+ expect(context.conversations.some((c: any) => c.conversation_id === 'removed')).toBe(true);
+ });
+
+ it('does not repaint unchanged sidebars when cleaning history outside the loaded list', () => {
+ const context = loadConversationRenderer();
+ const current = { conversation_id: 'current', last_active_at: '2026-10-17T01:00:00Z' };
+ context.conversations = [current];
+ context.renderConversationList = vi.fn();
+ context.requestAnimationFrame = vi.fn();
+ for (let i = 0; i < 1000; i++) context._removeConversationFromSidebar(`old-${i}`, { deferRender: true });
+ expect(context.conversations).toEqual([current]);
+ expect(context.renderConversationList).not.toHaveBeenCalled();
+ expect(context.requestAnimationFrame).not.toHaveBeenCalled();
+ });
+
+ it('removes cached history immediately and coalesces a cleanup burst into one sidebar paint', () => {
+ const context = loadConversationRenderer();
+ context.conversations = [{ conversation_id: 'one' }, { conversation_id: 'two' }, { conversation_id: 'keep' }];
+ context.renderConversationList = vi.fn();
+ const frames: Function[] = [];
+ context.requestAnimationFrame = vi.fn((fn: Function) => { frames.push(fn); });
+ context._removeConversationFromSidebar('one', { deferRender: true });
+ context._removeConversationFromSidebar('two', { deferRender: true });
+ expect(context.conversations.map((c: any) => c.conversation_id)).toEqual(['keep']);
+ expect(context.renderConversationList).not.toHaveBeenCalled();
+ expect(frames).toHaveLength(1);
+ frames.shift()!();
+ expect(context.renderConversationList).toHaveBeenCalledTimes(1);
+ context._removeConversationFromSidebar('keep', { deferRender: true });
+ expect(frames).toHaveLength(1);
+ frames.shift()!();
+ expect(context.renderConversationList).toHaveBeenCalledTimes(2);
+ });
+
+ it('rejects an older response for deleted offscreen history without repainting the unchanged sidebar', async () => {
+ const context = loadConversationRenderer();
+ const keep = { conversation_id: 'keep' };
+ context.conversations = [keep];
+ context.renderConversationList = vi.fn();
+ let release!: (value: any) => void;
+ context.apiFetch = vi.fn(() => new Promise(resolve => { release = resolve; }));
+ const pending = context.loadConversations();
+ context._removeConversationFromSidebar('offscreen', { deferRender: true });
+ release({ json: async () => ({ ok: true, conversations: [keep, { conversation_id: 'offscreen' }] }) });
+ await pending;
+ expect(context.conversations).toEqual([keep]);
+ expect(context.renderConversationList).not.toHaveBeenCalled();
+ });
+
+ it('refreshes after cleanup even when an older sidebar request is still pending', async () => {
+ const context = loadConversationRenderer();
+ const removed = { conversation_id: 'removed' };
+ const keep = { conversation_id: 'keep' };
+ context.conversations = [removed, keep];
+ context.renderConversationList = vi.fn();
+ let release!: (value: any) => void;
+ context.apiFetch = vi.fn().mockImplementationOnce(() => new Promise(resolve => { release = resolve; }))
+ .mockResolvedValue({ json: async () => ({ ok: true, conversations: [keep] }) });
+ const older = context.loadConversations();
+ context._removeConversationFromSidebar('removed');
+ const fresh = context.loadConversations({ fresh: true });
+ release({ json: async () => ({ ok: true, conversations: [removed, keep] }) });
+ await Promise.all([older, fresh]);
+ expect(context.apiFetch).toHaveBeenCalledTimes(2);
+ expect(context.conversations.map((c: any) => c.conversation_id)).toEqual(['keep']);
+ });
+
it('resets a project list to its first 10 tasks when reopened', async () => {
const context = loadConversationRenderer();
const requestedOffsets: number[] = [];
diff --git a/test/renderer/home.test.ts b/test/renderer/home.test.ts
index 465e4a49..5f78e4fb 100644
--- a/test/renderer/home.test.ts
+++ b/test/renderer/home.test.ts
@@ -1,6 +1,6 @@
// Commander home (modules/home.js): which state the New task view shows, how
// open to-dos and unopened finished runs are grouped, folded and opened, and
-// the shortcuts and connect chooser. jsdom isn't installed, so — like the other
+// the shortcuts and Connectors navigation. jsdom isn't installed, so — like the other
// renderer tests — the classic script runs in a vm sandbox with a minimal DOM
// shim and the real zh copy, and assertions read the generated HTML.
@@ -153,9 +153,9 @@ describe('Commander home states', () => {
expect(h.state()).toBe('empty');
expect(h.html()).toBe('');
- // The context line carries the connect chooser inside the translated sentence.
+ // The context line carries the Connectors link inside the translated sentence.
expect(h.els['home-explore-context'].innerHTML).toBe(
- '用 + 分享资料,或<button type="button" class="home-connect-link" data-home-connect="1">连接飞书 / 钉钉 / 邮箱</button>,补充背景,让 Orkas 更了解你。从你愿意分享的内容开始。',
+ '添加资料或<button type="button" class="home-connect-link" data-home-connect="1">连接邮箱/店铺/办公软件等</button>,让 Orkas 更了解你。从你愿意分享的内容开始。',
);
});
@@ -167,6 +167,8 @@ describe('Commander home states', () => {
{ id: 't1', project_id: 'p1', project_name: '增长', status: 'review', content: '确认定价方案\n附件见对话', updated_at: new Date(Date.now() - 5 * MINUTE).toISOString() },
{ id: 't2', project_id: '', project_name: '', status: 'todo', content: '整理客户访谈', updated_at: new Date(Date.now() - 3 * 60 * MINUTE).toISOString() },
{ id: 't3', project_id: '', project_name: '', status: 'progress', content: '周报', updated_at: '' },
+ { id: 't4', project_id: '', status: 'todo', content: 'Follow-up 4' },
+ { id: 't5', project_id: '', status: 'todo', content: 'Follow-up 5' },
],
},
unread: [
@@ -218,23 +220,65 @@ describe('Commander home states', () => {
// More to-dos than rows: the link to the full To-dos page sits in the group header, not below the list.
expect(html).toContain('重要待办<span class="home-group-count">5</span></h2><button type="button" class="home-text-btn" data-home-action="more_todos" aria-describedby="home-group-todos-title">查看全部 →</button></div>');
expect(html).not.toContain('home-group-more" data-home-action="more_todos"');
- expect(html).not.toContain('data-home-toggle="todos"');
+ expect(html).toContain('data-home-toggle="todos"');
// Run rows: result-specific glyph and action, automation source, fallbacks for old records.
expect(html).toMatch(/data-home-cid="auto-new"[^>]*data-home-status="failed"[^>]*><span class="home-row-status is-failed"/);
expect(html).toMatch(/data-home-cid="auto-reply"[^>]*><span class="home-row-status is-completed"/);
expect(html).toMatch(/data-home-cid="project-task"[^>]*><span class="home-row-status is-waiting_input"/);
- expect(html).toMatch(/data-home-cid="legacy"[^>]*><span class="home-row-status is-unknown"/);
+ expect(html).toMatch(/data-home-cid="legacy"[^>]*><span class="home-row-status is-completed"/);
expect(html).toContain(`<span class="home-row-status is-failed" aria-hidden="true">${uiIconHtml('x-circle', 'home-row-status-icon')}</span>`);
expect(html).toContain('<span class="home-row-title">每周竞品简报</span><span class="home-row-meta"><span class="home-row-source">自动化</span>失败 · 2分钟前</span></span><span class="home-row-action">查看原因');
expect(html).toContain('<span class="home-row-source">增长 · 项目任务</span>等你输入 · 20分钟前</span></span><span class="home-row-action">去回复');
- expect(html).toContain('<span class="home-row-title">未命名任务</span><span class="home-row-meta"><span class="home-row-source">全局任务</span>有新结果 · 30分钟前');
+ expect(html).toContain('<span class="home-row-title">未命名任务</span><span class="home-row-meta"><span class="home-row-source">全局任务</span>已完成 · 30分钟前');
expect(html).not.toContain('deleted-elsewhere');
expect(html).toContain('全部自动化 →');
});
- it('shows three runs per group and folds up to twenty more', async () => {
- const unread = Array.from({ length: 25 }, (_, i) => run(`task-${i}`, 'completed', i + 1, 'chat_send'));
+ it.each(['automations', 'tasks'])('presents missing %s outcomes as completed without overwriting known outcomes or stored records', async (section) => {
+ const outcomes = [
+ [undefined, 'completed', 'check-circle', '已完成', '查看结果'],
+ ['failed', 'failed', 'x-circle', '失败', '查看原因'],
+ ['waiting_input', 'waiting_input', 'message-circle-more', '等你输入', '去回复'],
+ ['stopped', 'stopped', 'stop', '已停止', '查看结果'],
+ ['completed', 'completed', 'check-circle', '已完成', '查看结果'],
+ ['', 'completed', 'check-circle', '已完成', '查看结果'],
+ ['unknown', 'completed', 'check-circle', '已完成', '查看结果'],
+ ];
+ const unread = outcomes.map(([status], i) => ({
+ cid: `result-${i}`, finishedAt: Date.now() - i * MINUTE,
+ ...(status === undefined ? {} : { status }),
+ entryPoint: section === 'automations' ? 'automation' : 'chat_send',
+ }));
+ const h = loadHome({
+ unread,
+ // No message bodies or execution results exist in this fixture.
+ conversations: unread.map(({ cid }) => ({ conversation_id: cid, title: cid })),
+ });
+ h.context.homeOnEnter();
+ await h.settle();
+ const html = h.html();
+ outcomes.forEach(([original, displayed, icon, label, action], i) => {
+ const row = html.match(new RegExp(`<button type="button" class="home-row"[^>]*data-home-cid="result-${i}"[^>]*>.*?<\\/button>`))?.[0] || '';
+ expect(row).toContain(`class="home-row-status is-${displayed}" aria-hidden="true">${uiIconHtml(icon, 'home-row-status-icon')}`);
+ expect(row).toContain(`</span>${label} · `);
+ expect(row).toContain(`<span class="home-row-action">${action}`);
+ expect(row).toContain(`data-home-status="${original || 'unknown'}"`);
+ });
+ expect(html).not.toContain('有新结果');
+ expect(h.data()[section].map((row: any) => row.status)).toEqual(outcomes.map(([status]) => status || ''));
+ expect(h.invokes.map(([channel]) => channel)).toEqual(['projects.tasks.listOpen']);
+ });
+
+ it.each([
+ ['todos', 11, '重要待办'],
+ ['todos', 46, '重要待办'],
+ ['automations', 46, '自动化待处理'],
+ ['tasks', 25, '任务待你处理'],
+ ] as const)('expands every remaining %s row and keeps the displayed counts accurate (%i total)', async (section, total, title) => {
+ const unread = section === 'todos' ? [] : Array.from({ length: total }, (_, i) => run(`task-${i}`, 'completed', i + 1, section === 'automations' ? 'automation' : 'chat_send'));
+ const todoRows = Array.from({ length: total }, (_, i) => ({ id: `todo-${i}`, content: `To-do ${i}`, status: 'todo' }));
const h = loadHome({
+ ...(section === 'todos' ? { todos: { tasks: todoRows, total } } : {}),
unread,
conversations: unread.map((record) => ({ conversation_id: record.cid, title: record.cid, project_id: '' })),
});
@@ -243,26 +287,38 @@ describe('Commander home states', () => {
const html = h.html();
const visible = html.split('<div class="home-list-fold"')[0];
- const fold = html.match(/<div class="home-list-fold" id="home-fold-tasks" hidden>(.*?)<\/div>/)?.[1] || '';
- expect([...visible.matchAll(/data-home-cid="([^"]+)"/g)].map((m) => m[1])).toEqual(['task-0', 'task-1', 'task-2']);
+ const fold = html.match(new RegExp(`<div class="home-list-fold" id="home-fold-${section}" hidden>(.*?)<\\/div>`))?.[1] || '';
+ expect([...visible.matchAll(/data-home-position="(\d+)"/g)].map((m) => Number(m[1]))).toEqual([1, 2, 3]);
expect([...fold.matchAll(/data-home-position="(\d+)"/g)].map((m) => Number(m[1])))
- .toEqual(Array.from({ length: 20 }, (_, i) => i + 4));
- expect(html).toContain('aria-expanded="false">展开其余 20 条</button>');
- expect(html).toContain('任务待你处理<span class="home-group-count">25</span>');
+ .toEqual(Array.from({ length: total - 3 }, (_, i) => i + 4));
+ expect(html).toContain(`aria-expanded="false">展开其余 ${total - 3} 条</button>`);
+ expect(html).toContain(`${title}<span class="home-group-count">${total}</span>`);
const foldEl = element({ hidden: true });
- h.els['home-fold-tasks'] = foldEl;
- const toggle = element({ dataset: { homeToggle: 'tasks', homeFolded: '20' } });
+ h.els[`home-fold-${section}`] = foldEl;
+ const toggle = element({ dataset: { homeToggle: section, homeFolded: String(total - 3) } });
h.els['home-groups'].fire('click', click({ '[data-home-toggle]': toggle }));
expect(foldEl.hidden).toBe(false);
expect(toggle.getAttribute('aria-expanded')).toBe('true');
expect(toggle.textContent).toBe('收起');
// A refresh during the visit keeps the group unfolded.
- expect(vm.runInContext('_homeSectionHtml("tasks")', h.context)).toContain('id="home-fold-tasks">');
+ expect(vm.runInContext(`_homeSectionHtml("${section}")`, h.context)).toContain(`id="home-fold-${section}">`);
h.els['home-groups'].fire('click', click({ '[data-home-toggle]': toggle }));
expect(foldEl.hidden).toBe(true);
- expect(toggle.textContent).toBe('展开其余 20 条');
+ expect(toggle.textContent).toBe(`展开其余 ${total - 3} 条`);
+ });
+
+ it.each(['todos', 'automations', 'tasks'])('omits the %s expand control when all three rows fit', async (section) => {
+ const h = loadHome({
+ ...(section === 'todos'
+ ? { todos: { total: 3, tasks: Array.from({ length: 3 }, (_, i) => ({ id: `t${i}`, content: `To-do ${i}` })) } }
+ : { unread: Array.from({ length: 3 }, (_, i) => run(`c${i}`, 'completed', i, section === 'automations' ? 'automation' : 'chat_send')) }),
+ });
+ h.context.homeOnEnter();
+ await h.settle();
+ expect(h.html()).not.toContain('data-home-toggle');
+ expect([...h.html().matchAll(/data-home-position=/g)]).toHaveLength(3);
});
it('opens a run in its conversation and a to-do on the To-dos page', async () => {
@@ -375,22 +431,21 @@ describe('Commander home states', () => {
});
});
-describe('Commander home connect chooser', () => {
- it('marks connected services and opens the picked one in Connectors', async () => {
- const h = loadHome({ connectors: [
- { id: 'lark', status: { kind: 'connected' } },
- { id: 'gmail', status: { kind: 'error' } },
- ] });
+describe('Commander home Connectors link', () => {
+ it('opens Connectors directly without a chooser or starting setup', async () => {
+ const h = loadHome();
h.context.homeOnEnter();
await h.settle();
+ const beforeClick = h.invokes.length;
+ h.els['home-explore-context'].fire('click', click({}));
+ expect(h.views).toEqual([]);
+ expect(h.clicks).toEqual([]);
h.els['home-explore-context'].fire('click', click({ '[data-home-connect]': element() }));
- await h.settle();
- expect(h.menus).toHaveLength(1);
- expect(h.menus[0].map((item: any) => item.label)).toEqual(['飞书 · 已连接', '钉钉', 'Gmail', 'Microsoft 365 邮箱']);
-
- h.menus[0][2].onClick();
expect(h.views).toEqual([['connectors', null, { entryPoint: 'home' }]]);
- expect(h.context.window.openConnectorSetupById).toHaveBeenCalledWith('gmail', 'form');
+ await h.settle();
+ expect(h.invokes).toHaveLength(beforeClick);
+ expect(h.menus).toEqual([]);
+ expect(h.context.window.openConnectorSetupById).not.toHaveBeenCalled();
});
});
diff --git a/test/renderer/oss.test.ts b/test/renderer/oss.test.ts
index a3fabd50..8627e685 100644
--- a/test/renderer/oss.test.ts
+++ b/test/renderer/oss.test.ts
@@ -102,38 +102,14 @@ function loadOss(opts: LoadOpts = {}) {
}
describe('oss.js', () => {
- it('surfaces open source as one localized entry on the quick-start header', () => {
+ it('keeps open-source tools off the home quick-start surface', () => {
const html = fs.readFileSync(path.join(__dirname, '../../src/renderer/index.html'), 'utf8');
- const css = fs.readFileSync(path.join(__dirname, '../../src/renderer/style.css'), 'utf8');
const conversation = fs.readFileSync(path.join(__dirname, '../../src/renderer/modules/conversation.js'), 'utf8');
- const locales = Object.fromEntries(['en', 'zh', 'ja', 'pt'].map((lang) => [
- lang,
- JSON.parse(fs.readFileSync(path.join(__dirname, `../../src/renderer/locales/${lang}.json`), 'utf8')),
- ]));
- const zh = locales.zh;
-
- // Neither the old rail nor a grid card: the entry lives on the header row
- // beside the quick-start title, so the grid stays a list of runnable tasks.
expect(html).not.toContain('id="oss-entry"');
expect(html).not.toContain('id="oss-entry-grid"');
- expect(html.match(/id="quick-panel-oss-more"/g)).toHaveLength(1);
- expect(html).toMatch(/quick-panel-rule[\s\S]{0,200}quick-panel-oss-more/);
+ expect(html).not.toContain('id="quick-panel-oss-more"');
expect(conversation).not.toContain('oss-quick-task-card');
expect(conversation).not.toContain("_quickStartText('new_chat.quick.task.oss'");
- expect(css).toContain('.quick-panel-more');
- expect(css).not.toContain('.quick-thumb-oss');
- expect(css).not.toContain('.oss-entry {');
- expect(zh['new_chat.quick.oss_more']).toBe('接入开源工具能力');
- expect(zh['new_chat.quick.oss']).toBeUndefined();
- expect(zh['new_chat.quick.task.oss']).toBeUndefined();
- expect(zh['new_chat.quick.deliver.oss']).toBeUndefined();
- for (const [lang, messages] of Object.entries(locales)) {
- expect((messages as any)['new_chat.quick.oss_more'], `${lang} label`).toBeTruthy();
- }
- expect(Object.fromEntries(Object.entries(locales).map(([lang, messages]: [string, any]) => [
- lang,
- messages['sidebar.new_chat'],
- ]))).toEqual({ en: 'New Task', zh: '新任务', ja: '新規タスク', pt: 'Nova tarefa' });
});
it('prefillCommander writes the task, focuses, sets the Commander recipient, and does NOT send', () => {
@@ -188,33 +164,6 @@ describe('oss.js', () => {
.toContain('[describe your task here]');
});
- it('opens the marketplace OSS page from the header entry and keeps New Task as the return view', async () => {
- const { context, calls, invokeCount } = loadOss();
- let cardClick: Function | null = null;
- const card = {
- dataset: {} as Record<string, string>,
- addEventListener(type: string, fn: Function) { if (type === 'click') cardClick = fn; },
- };
- const baseGetElementById = context.document.getElementById;
- context.document.getElementById = (id: string) => {
- if (id === 'quick-panel-oss-more') return card;
- return baseGetElementById(id);
- };
-
- context.initOssQuickTask();
- context.initOssQuickTask();
- expect(card.dataset.bound).toBe('1');
- expect(invokeCount()).toBe(0);
- cardClick!();
- await Promise.resolve();
- await Promise.resolve();
-
- expect(calls.openMarketplace).toEqual([{
- tab: 'oss',
- opts: { returnView: 'new-chat', preserveReturnTab: true },
- }]);
- });
-
it('loadOssCatalog uses bundled cache first, then refreshes without duplicate calls', async () => {
const payload = {
list: [{ id: 'x', name: 'X', task_zh: 't', task_en: 't', category: 'anim', driver: 'cli', stars: 10 }],
diff --git a/test/renderer/task-cleanup.test.ts b/test/renderer/task-cleanup.test.ts
index 170e5afa..5336d3eb 100644
--- a/test/renderer/task-cleanup.test.ts
+++ b/test/renderer/task-cleanup.test.ts
@@ -3,15 +3,17 @@ import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
import { LOCALES } from '../../src/main/i18n';
+import { conversationRemovalSource } from './conversation-cache-test-source';
function harness() {
const listeners: Record<string, any> = {};
+ const back = { hidden: true, addEventListener: (_type: string, fn: any) => { listeners.back = fn; } };
const body = { innerHTML: '', addEventListener: (type: string, fn: any) => { listeners[type] = fn; }, querySelector: () => null };
const picker = { setOptions: vi.fn(), setAriaLabel: vi.fn(), close() {}, onChange(fn: any) { this.change = fn; }, change: null as any };
- const rows = [{ cid: 'one', title: '<unsafe title>', activeAt: '2020-01-01T00:00:00Z' },
- { cid: 'two', title: 'Second', activeAt: '2020-01-02T00:00:00Z' }];
+ const rows = [{ cid: 'one', title: '<unsafe title>', activeAt: '2020-01-01T00:00:00Z', projectId: null, selectable: true },
+ { cid: 'two', title: 'Second', activeAt: '2020-01-02T00:00:00Z', projectId: null, selectable: true }];
const invoke = vi.fn(async (channel: string, _payload?: any) => !channel.endsWith('remove')
- ? { ok: true, token: 'receipt', total: 2, rows, nextOffset: null }
+ ? { ok: true, token: 'receipt', total: 2, selectableTotal: 2, rows, entries: rows, treeTotal: 2, treeNextOffset: null, listTotal: 2, nextOffset: null }
: { ok: true, status: 'deleted' });
const store = new Map<string, string>();
const refresh = vi.fn(); const forgot = vi.fn();
@@ -19,26 +21,100 @@ function harness() {
const scope: any = { currentUserId: 'u1', currentCid: '', conversations: [], currentView: 'settings',
window: { orkas: { invoke }, TaskUnread: { list: () => [], isUnread: () => false },
addEventListener() {}, initRecycleBin: refresh },
- document: { getElementById: (id: string) => id === 'settings-task-cleanup-body' ? body : {},
+ document: { getElementById: (id: string) => id === 'settings-task-cleanup-body' ? body : id === 'chat-cleanup-back' ? back : {},
querySelector: () => null },
localStorage: { get length() { return store.size; }, key: (i: number) => [...store.keys()][i], getItem: (key: string) => store.get(key) ?? null },
t: (key: string, vars: any = {}) => Object.entries(vars).reduce((text, [k, v]) => text.replaceAll(`{${k}}`, String(v)), messages[key] || key),
escapeHtml: (v: string) => String(v).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('"', '&quot;'),
- _aiSelectMount: () => picker, _forgetConvLocal: forgot, loadConversations: refresh,
+ _aiSelectMount: () => picker, _forgetConvLocal: forgot, _chatAttachClear: vi.fn(), loadConversations: refresh, setView: vi.fn(),
_composerHoldsUnsentInput: () => false, _chatAttachList: () => [],
+ _clearConversationInlineRenameState: vi.fn(), renderConversationList: vi.fn(),
createLogger: () => ({ warn: vi.fn() }), setTimeout, clearTimeout, Date,
};
- vm.runInNewContext(readFileSync(resolve(__dirname, '../../src/renderer/modules/task-cleanup.js'), 'utf8'), scope);
- const click = async (action: string, cid = '') => listeners.click({ target: { closest: () => ({ dataset: { cleanupAction: action, cid } }) } });
- const check = async (cid: string | null, checked: boolean) => listeners.change({ target: {
- checked, getAttribute: () => cid, hasAttribute: () => !cid,
+ vm.runInNewContext(`let _conversationRemovalRevision = 0;
+ let _conversationRemovalRenderPending = false;
+ const _conversationProjectPages = new Map();
+ const _unprojectedConversationPage = { total: 0, nextOffset: null };
+ ${conversationRemovalSource}\n` + readFileSync(resolve(__dirname, '../../src/renderer/modules/task-cleanup.js'), 'utf8'), scope);
+ const click = async (action: string, projectId = '') => listeners.click({ preventDefault: vi.fn(), target: { closest: () => ({ dataset: { cleanupAction: action, cleanupOwner: projectId } }) } });
+ const check = async (cid: string | null, checked: boolean, projectId = '') => listeners.change({ target: {
+ checked, getAttribute: (name: string) => name === 'data-cleanup-cid' ? cid : name === 'data-cleanup-project' ? projectId : null, hasAttribute: (name: string) => name === 'data-cleanup-all' && !cid && !projectId,
} });
- return { scope, body, invoke, store, picker, refresh, forgot, click, check,
+ return { scope, body, back, invoke, store, picker, refresh, forgot, click, check,
show: () => scope.window.initTaskCleanup() };
}
describe('inline history cleanup', () => {
+ it.each([undefined, 'busy', 'unknown'])('opens a task with blocking state %s without selecting or deleting it', async blocked => {
+ const h = harness();
+ const original = h.invoke.getMockImplementation()!;
+ h.invoke.mockImplementation(async (channel, payload) => {
+ const response = await original(channel, payload);
+ if (response.entries) response.entries = response.entries.map(row => ({ ...row, selectable: !blocked, blocked }));
+ return response;
+ });
+ await h.show(); await h.click('view');
+ expect(h.body.innerHTML).toContain('data-cleanup-action="open" data-cleanup-owner="one"');
+ await h.click('open', 'one');
+ expect(h.scope.setView).toHaveBeenCalledExactlyOnceWith('conversation', 'one');
+ expect(h.body.innerHTML).toContain('Clean up (0)');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(0);
+ });
+ it('returns to the existing cleanup selection and only offers Back for its originating conversation', async () => {
+ const h = harness();
+ h.scope.setView.mockImplementation((view, cid, opts = {}) => {
+ const preserve = h.scope.window.TaskCleanupNavigation?.beforeNavigate(view, cid, opts);
+ h.scope.currentView = view; h.scope.currentCid = view === 'conversation' ? cid : null;
+ if (view === 'settings' && !preserve) h.show();
+ });
+ await h.show(); await h.click('view'); await h.check('one', true);
+ const previewCount = h.invoke.mock.calls.filter(([c]) => c.endsWith('preview')).length;
+ await h.click('open', 'one');
+ expect(h.back.hidden).toBe(false);
+ h.scope.window.TaskCleanupNavigation.back();
+ expect(h.scope.currentView).toBe('settings');
+ expect(h.body.innerHTML).toContain('Clean up (1)');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('preview'))).toHaveLength(previewCount);
+ expect(h.back.hidden).toBe(true);
+ await h.click('open', 'one');
+ h.scope.setView('conversation', 'two');
+ expect(h.back.hidden).toBe(true);
+ h.scope.window.TaskCleanupNavigation.back();
+ expect(h.scope.currentCid).toBe('two');
+ });
+ it('does not return another account to the previous cleanup receipt', async () => {
+ const h = harness(); await h.show(); await h.click('view'); await h.click('open', 'one');
+ h.scope.currentView = 'conversation'; h.scope.currentCid = 'one'; h.scope.currentUserId = 'other';
+ h.scope.setView.mockClear();
+ h.scope.window.TaskCleanupNavigation.back();
+ expect(h.scope.setView).not.toHaveBeenCalled();
+ expect(h.back.hidden).toBe(true);
+ });
+ it('rejects unknown or cross-account destinations and keeps confirmation in place', async () => {
+ const h = harness(); await h.show(); await h.click('view');
+ for (const cid of ['missing', '../one', 'https://example.com', 'javascript:alert(1)']) await h.click('open', cid);
+ await h.check('one', true); await h.click('prepare'); await h.click('open', 'one');
+ expect(h.scope.setView).not.toHaveBeenCalled();
+ await h.click('cancel'); h.scope.currentUserId = 'other'; await h.click('open', 'one');
+ expect(h.scope.setView).not.toHaveBeenCalled();
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(0);
+ });
+ it('lets users select active history and discloses automatic stopping before cleanup', async () => {
+ const h = harness(); const original = h.invoke.getMockImplementation()!;
+ h.invoke.mockImplementation(async (channel, payload) => {
+ const response = await original(channel, payload);
+ if (response.entries) response.entries = response.entries.map(row => ({ ...row, blocked: 'busy' }));
+ return response;
+ });
+ await h.show(); await h.click('view');
+ expect(h.body.innerHTML).not.toContain('Stops on cleanup');
+ await h.check('one', true); await h.click('prepare');
+ expect(h.body.innerHTML).toContain('Running tasks are stopped automatically before cleanup.');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(0);
+ await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one']);
+ });
it('retries only failed tasks after a partial success', async () => {
- const h = harness(); await h.show();
+ const h = harness(); await h.show(); await h.check(null, true);
const original = h.invoke.getMockImplementation()!;
let fail = true;
h.invoke.mockImplementation(async (channel, payload) => {
@@ -46,34 +122,63 @@ describe('inline history cleanup', () => {
return original(channel, payload);
});
await h.click('prepare'); await h.click('confirm');
- expect(h.body.innerHTML).toContain('Moved to recycle bin: 1. Skipped: 0. Failed: 1.');
+ expect(h.body.innerHTML).toContain('Recycled 1 · Skipped 0 · Failed 1');
fail = false; await h.click('retry');
expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one', 'two', 'two']);
expect(h.forgot.mock.calls.map(([cid]) => cid)).toEqual(['one', 'two']);
});
+ it.each([false, true])('removes completed tasks from selection after partial success (project=%s)', async project => {
+ const h = harness();
+ const original = h.invoke.getMockImplementation()!;
+ h.invoke.mockImplementation(async (channel, payload) => {
+ if (channel.endsWith('remove') && payload.cid === 'two') throw new Error('backup unavailable');
+ const response = await original(channel, payload);
+ if (project && response.rows) {
+ response.rows = response.rows.map(row => ({ ...row, projectId: 'p1' }));
+ response.entries = [{ type: 'project', projectId: 'p1', title: 'Project', total: 2, selectableTotal: 2 }] as any;
+ }
+ return response;
+ });
+ await h.show(); await h.click('view');
+ if (project) await h.click('project', 'p1');
+ await h.check(null, true); await h.click('prepare'); await h.click('confirm');
+ expect(h.body.innerHTML).toContain('Recycled 1 · Skipped 0 · Failed 1');
+ expect(h.body.innerHTML).toContain('Clean up (1)');
+ expect(h.body.innerHTML).toContain('Select all (1)');
+ expect(h.body.innerHTML).not.toContain('data-cleanup-cid="one"');
+ expect(h.body.innerHTML).toContain('data-cleanup-cid="two"');
+ if (project) expect(h.body.innerHTML).toContain('>1 / 1<');
+ // Re-reading a frozen page and selecting all must not resurrect a deletion.
+ await h.click('previous', project ? 'p1' : '');
+ await h.check(null, false); await h.check(null, true);
+ expect(h.body.innerHTML).not.toContain('data-cleanup-cid="one"');
+ expect(h.body.innerHTML).toContain('Clean up (1)');
+ await h.click('prepare'); await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one', 'two', 'two']);
+ });
it('retains selection across pages and executes the frozen receipt once per selected task', async () => {
const h = harness();
- const rows = Array.from({ length: 25 }, (_, n) => ({ cid: `task_${n}`, title: `Task ${n}`, activeAt: '2020-01-01' }));
+ const rows = Array.from({ length: 25 }, (_, n) => ({ cid: `task_${n}`, title: `Task ${n}`, activeAt: '2020-01-01', projectId: null, selectable: true }));
h.invoke.mockImplementation(async (channel, payload) => channel.endsWith('remove')
? { ok: true, status: 'deleted' } as any
- : { ok: true, token: 'frozen', total: 25, rows: rows.slice(payload.offset || 0, (payload.offset || 0) + 20), nextOffset: payload.offset === 20 ? null : 20 });
- await h.show(); await h.click('view'); await h.check('task_0', false);
+ : { ok: true, token: 'frozen', total: 25, selectableTotal: 25, treeTotal: 25, treeNextOffset: 20, listTotal: 25, entries: rows.slice(payload.offset || 0, (payload.offset || 0) + 20), rows: rows.slice(payload.offset || 0, (payload.offset || 0) + 20), nextOffset: payload.offset === 20 ? null : 20 });
+ await h.show(); await h.check(null, true); await h.click('view'); await h.check('task_0', false);
await h.click('next'); expect(h.body.innerHTML).toContain('Task 24');
await h.check('task_24', false); await h.click('previous');
- expect(h.body.innerHTML).toContain('Selected tasks: 23');
+ expect(h.body.innerHTML).toContain('Clean up (23)');
await h.click('prepare'); await h.click('confirm');
const removals = h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p);
expect(removals.map(p => p.cid)).toEqual(rows.slice(1, 24).map(row => row.cid));
expect(removals.every(p => p.token === 'frozen')).toBe(true);
});
it('deselects all without fetching every page and cleans only a subsequent individual selection', async () => {
- const h = harness(); await h.show(); await h.check(null, false);
+ const h = harness(); await h.show(); await h.check(null, true); await h.check(null, false);
expect(h.invoke).toHaveBeenCalledTimes(1);
await h.check('two', true); await h.click('prepare'); await h.click('confirm');
expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['two']);
});
it('stops between tasks and prevents duplicate confirmation while an item is being deleted', async () => {
- const h = harness(); await h.show();
+ const h = harness(); await h.show(); await h.check(null, true);
const original = h.invoke.getMockImplementation()!;
let finish!: (value: any) => void;
h.invoke.mockImplementation((channel, payload) => channel.endsWith('remove')
@@ -82,38 +187,56 @@ describe('inline history cleanup', () => {
for (let i = 0; i < 5; i++) await Promise.resolve();
expect(h.body.innerHTML).toContain('Cleaning 0 / 2');
expect(h.body.innerHTML.match(/role="status"/g)).toHaveLength(1);
- expect(h.body.innerHTML).not.toContain('Moved to recycle bin:');
+ expect(h.body.innerHTML).not.toContain('Recycled ');
await h.click('confirm'); await h.click('stop');
expect(h.body.innerHTML.match(/role="status"/g)).toHaveLength(1);
finish({ ok: true, status: 'deleted' }); await pending;
- expect(h.body.innerHTML).toContain('Moved to recycle bin: 1. Skipped: 0. Failed: 0.');
+ expect(h.body.innerHTML).toContain('Recycled 1 · Skipped 0 · Failed 0');
expect(h.body.innerHTML).not.toContain('Cleaning ');
expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(1);
expect(h.forgot).toHaveBeenCalledWith('one');
});
it('shows a preview, confirms inline, cancels without deleting and escapes titles', async () => {
- const h = harness(); await h.show();
+ const h = harness(); await h.show(); await h.check(null, true);
expect(h.invoke.mock.calls[0][0]).toBe('conversations.cleanup.preview');
expect(h.body.innerHTML).toContain('2');
await h.click('view'); expect(h.body.innerHTML).toContain('&lt;unsafe title>');
await h.click('prepare'); expect(h.body.innerHTML).toContain('data-cleanup-action="confirm"');
+ expect(h.body.innerHTML.match(/class="settings-row"/g)).toHaveLength(1);
+ expect(h.body.innerHTML).not.toContain('data-cleanup-action="prepare"');
await h.click('cancel'); expect(h.invoke).toHaveBeenCalledTimes(1);
expect(h.body.innerHTML).not.toContain('data-cleanup-action="confirm"');
});
it('cleans the selected snapshot and refreshes the recycle bin', async () => {
- const h = harness(); await h.show(); await h.click('prepare'); await h.click('confirm');
+ const h = harness(); await h.show(); await h.check(null, true); await h.click('prepare'); await h.click('confirm');
expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one', 'two']);
expect(h.forgot).toHaveBeenCalledWith('one'); expect(h.refresh).toHaveBeenCalled();
+ expect(h.scope._chatAttachClear.mock.calls).toEqual([['one'], ['two']]);
+ });
+ it('removes each deleted task from sidebar data before the next deletion finishes', async () => {
+ const h = harness();
+ h.scope.conversations = [{ conversation_id: 'one' }, { conversation_id: 'two' }];
+ const original = h.invoke.getMockImplementation()!;
+ let release!: (value: any) => void;
+ h.invoke.mockImplementation((channel, payload) => channel.endsWith('remove') && payload.cid === 'two'
+ ? new Promise(resolve => { release = resolve; }) : original(channel, payload));
+ await h.show(); await h.check(null, true); await h.click('prepare');
+ const pending = h.click('confirm');
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ const during = h.scope.conversations.map((row: any) => row.conversation_id);
+ release({ ok: true, status: 'skipped' }); await pending;
+ expect(during).toEqual(['two']);
+ expect(h.scope.conversations.map((row: any) => row.conversation_id)).toEqual(['two']);
});
- it('sends draft protection and rechecks newly unread tasks before deletion', async () => {
- const h = harness(); h.store.set('draft_other', JSON.stringify({ text: 'Keep me' })); await h.show();
- expect((h.invoke.mock.calls[0] as any)[1].protectedIds).toContain('other');
+ it('allows unread tasks and labels stored drafts instead of excluding them', async () => {
+ const h = harness(); h.store.set('draft_other', JSON.stringify({ text: 'Keep me' })); await h.show(); await h.check(null, true);
+ expect((h.invoke.mock.calls[0] as any)[1].draftIds).toContain('other');
await h.click('prepare'); h.scope.window.TaskUnread.isUnread = (cid: string) => cid === 'two';
await h.click('confirm');
- expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one']);
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(['one', 'two']);
});
it('keeps failures visible and never reports a malformed response as success', async () => {
- const h = harness(); await h.show();
+ const h = harness(); await h.show(); await h.check(null, true);
const original = h.invoke.getMockImplementation()!;
h.invoke.mockImplementation(async (channel: string, payload: any) => channel.endsWith('remove') ? { ok: true } as any : original(channel, payload));
await h.click('prepare'); await h.click('confirm');
@@ -121,16 +244,93 @@ describe('inline history cleanup', () => {
expect(h.body.innerHTML).toContain('data-cleanup-action="retry"');
});
it('does not execute a previous account selection after an account switch', async () => {
- const h = harness(); await h.show(); await h.click('prepare'); h.scope.currentUserId = 'u2';
+ const h = harness(); await h.show(); await h.check(null, true); await h.click('prepare'); h.scope.currentUserId = 'u2';
await h.click('confirm');
expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(0);
});
it('distinguishes a failed scan from an empty result and provides retry', async () => {
const h = harness(); h.invoke.mockRejectedValueOnce(new Error('private path'));
- await h.show(); expect(h.body.innerHTML).toContain('data-cleanup-action="refresh"');
+ await h.show(); await h.check(null, true); expect(h.body.innerHTML).toContain('data-cleanup-action="refresh"');
expect(h.body.innerHTML).not.toContain('private path');
expect(h.body.innerHTML).not.toContain('data-cleanup-action="prepare"');
});
+
+ it('starts at 30 days with no selection and offers every requested age', async () => {
+ const h = harness(); await h.show();
+ expect(h.invoke.mock.calls[0][1].days).toBe(30);
+ expect(h.body.innerHTML).toContain('Clean up (0)');
+ expect(h.body.innerHTML.match(/class="settings-row"/g)).toHaveLength(1);
+ expect(h.body.innerHTML).not.toContain('Selected tasks:');
+ expect(h.picker.setOptions.mock.calls.at(-1)?.[0].map((o: any) => o.value)).toEqual(['7', '14', '30', '60', '90', '180']);
+ await h.click('prepare'); await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(0);
+ });
+ it('clears the old selection when changing age and deletes only from the new preview', async () => {
+ const h = harness(); const original = h.invoke.getMockImplementation()!;
+ h.invoke.mockImplementation(async (channel, payload) => {
+ if ((channel.endsWith('preview') && payload.days === 14)
+ || (channel.endsWith('page') && payload.token === 'fourteen-day-receipt')) {
+ const rows = [{ cid: 'new-scope', title: 'New filter result', activeAt: '2020-01-01', projectId: null, selectable: true }];
+ return { ok: true, token: 'fourteen-day-receipt', total: 1, selectableTotal: 1, rows, entries: rows,
+ treeTotal: 1, treeNextOffset: null, listTotal: 1, nextOffset: null };
+ }
+ return original(channel, payload);
+ });
+ await h.show(); await h.click('view'); await h.check('one', true);
+ expect(h.body.innerHTML).toContain('Clean up (1)');
+ h.picker.change('14');
+ await vi.waitFor(() => expect(h.body.innerHTML).toContain('New filter result'));
+ expect(h.body.innerHTML).toContain('Clean up (0)');
+ expect(h.body.innerHTML).not.toContain('data-cleanup-cid="one"');
+ await h.click('prepare'); await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove'))).toHaveLength(0);
+ await h.check('new-scope', true); await h.click('prepare'); await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, payload]) => payload))
+ .toEqual([{ expectedUserId: 'u1', token: 'fourteen-day-receipt', cid: 'new-scope' }]);
+ });
+ it('selects a whole collapsed project across pages while leaving root tasks alone', async () => {
+ const h = harness();
+ const rows = Array.from({ length: 25 }, (_, n) => ({ cid: 'child_' + n, title: 'Child ' + n, projectId: 'p1', selectable: true, activeAt: '2020-01-01' }));
+ const personal = { cid: 'personal', title: 'Personal', projectId: null, selectable: true, activeAt: '2020-01-01' };
+ const group = { type: 'project', projectId: 'p1', title: 'Local project', shared: false, total: 25, selectableTotal: 25 };
+ h.invoke.mockImplementation(async (channel, payload) => {
+ if (channel.endsWith('remove')) return { ok: true, status: 'deleted' } as any;
+ const all = payload.projectId ? rows : [...rows, personal];
+ const offset = payload.offset || 0;
+ return { ok: true, token: 'receipt', total: 26, selectableTotal: 26, entries: [group, personal], treeTotal: 2, treeNextOffset: null,
+ rows: all.slice(offset, offset + 20), listTotal: all.length, nextOffset: offset + 20 < all.length ? offset + 20 : null } as any;
+ });
+ await h.show(); await h.click('view');
+ expect(h.body.innerHTML).toContain('Personal');
+ expect(h.body.innerHTML).toContain('data-ui-icon="folder"');
+ expect(h.body.innerHTML).not.toContain('data-cleanup-project=""');
+ await h.check(null, true, 'p1');
+ expect(h.body.innerHTML).toContain('Clean up (25)');
+ await h.click('prepare'); await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(rows.map(r => r.cid));
+ });
+ it('keeps partial project selection across child pages and collapse, excluding unavailable tasks', async () => {
+ const h = harness();
+ const rows = Array.from({ length: 25 }, (_, n) => ({ cid: 'child_' + n, title: 'Child ' + n,
+ projectId: 'p1', selectable: n !== 0, activeAt: '2020-01-01', ...(n === 0 ? { blocked: 'unknown' } : {}) }));
+ const group = { type: 'project', projectId: 'p1', title: 'Project', shared: false, total: 25, selectableTotal: 24 };
+ h.invoke.mockImplementation(async (channel, payload) => {
+ if (channel.endsWith('remove')) return { ok: true, status: 'deleted' } as any;
+ const offset = payload.offset || 0;
+ return { ok: true, token: 'receipt', total: 25, selectableTotal: 24, entries: [group], treeTotal: 1,
+ treeNextOffset: null, rows: rows.slice(offset, offset + 20), listTotal: 25, nextOffset: offset + 20 < 25 ? offset + 20 : null } as any;
+ });
+ await h.show(); await h.click('view'); await h.click('project', 'p1');
+ expect(h.body.innerHTML).toContain('Unavailable');
+ await h.check(null, true, 'p1'); await h.check('child_1', false);
+ expect(h.body.innerHTML).toContain('data-cleanup-project="p1" aria-label="Project" data-cleanup-mixed');
+ await h.click('next', 'p1'); await h.check('child_24', false);
+ expect(h.body.innerHTML).toContain('Clean up (22)');
+ await h.click('project', 'p1'); expect(h.body.innerHTML).not.toContain('Child 24');
+ await h.click('project', 'p1'); expect(h.body.innerHTML).toContain('Child 24');
+ await h.click('prepare'); await h.click('confirm');
+ expect(h.invoke.mock.calls.filter(([c]) => c.endsWith('remove')).map(([, p]: any) => p.cid)).toEqual(rows.slice(2, 24).map(r => r.cid));
+ });
it('translates every cleanup key in every supported locale', () => {
const en = JSON.parse(readFileSync(resolve(__dirname, '../../src/renderer/locales/en.json'), 'utf8'));
const keys = Object.keys(en).filter(key => key.startsWith('settings.cleanup.'));