Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(scheduled): render task lists independently and retain route snapshots
Linuxdazhaodda598c6f7e4
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsxindex 6200f4b7d..690b6420c 100644--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx@@ -16,6 +16,7 @@ import { installRendererApi } from "../../capture/renderer-api";import { StartupAnimation } from "../../components/StartupAnimation";import { StartupSplash } from "../../components/StartupSplash";import { api } from "../../lib/api";+import { scheduledWorkspaceCache } from "../scheduled/scheduled-workspace-cache";import { composerSuggestion } from "../chat/composer/plugins/suggestion-bridge";import { usePluginBrowseState } from "../plugins/browse-state";import { subscribeRemoteInteractions } from "../../lib/remote-interactions";@@ -757,6 +758,7 @@ export function useAppShellRuntime() {});});const offHostStatus = api.onHostStatus((status) => {+ if (status.component !== "sidecar" && (!status.ok || status.restarted)) scheduledWorkspaceCache.clear();if (status.archMismatch) setArchMismatch(status.archMismatch);if (status.ok) {setBackendDown(null);diff --git a/apps/desktop/src/features/scheduled/ScheduledRunHistory.tsx b/apps/desktop/src/features/scheduled/ScheduledRunHistory.tsxindex 238fd9978..667fffc5e 100644--- a/apps/desktop/src/features/scheduled/ScheduledRunHistory.tsx+++ b/apps/desktop/src/features/scheduled/ScheduledRunHistory.tsx@@ -30,6 +30,8 @@ function RunStatusGlyph({ status }: { status: ScheduledTaskRun["status"] }) {* page; opening its conversation stays a separate, explicit action. */export function ScheduledRunHistory({runs,+ loaded = true,+ error = "",selectedRunId,busy,locale,@@ -37,6 +39,8 @@ export function ScheduledRunHistory({onOpenSession,}: {runs: ScheduledTaskRun[];+ loaded?: boolean;+ error?: string;selectedRunId: string | null;busy: boolean;locale: string;@@ -50,10 +54,12 @@ export function ScheduledRunHistory({<h3 className="scheduled-card-title" id="scheduled-run-history">{t("scheduled.runs")}</h3>- <span className="scheduled-card-count">{runs.length}</span>+ {loaded && <span className="scheduled-card-count">{runs.length}</span>}</div>{runs.length === 0 ? (- <p className="scheduled-hint">{t("scheduled.emptyRuns")}</p>+ <p className="scheduled-hint" role={error ? "alert" : !loaded ? "status" : undefined}>+ {error || t(loaded ? "scheduled.emptyRuns" : "common.loading")}+ </p>) : (<><p className="scheduled-hint">{t("scheduled.historyHint")}</p>diff --git a/apps/desktop/src/features/scheduled/ScheduledTaskDetail.tsx b/apps/desktop/src/features/scheduled/ScheduledTaskDetail.tsxindex 702674749..bb13af7ce 100644--- a/apps/desktop/src/features/scheduled/ScheduledTaskDetail.tsx+++ b/apps/desktop/src/features/scheduled/ScheduledTaskDetail.tsx@@ -33,8 +33,11 @@ function Fact({ label, children }: { label: string; children: ReactNode }) {export function ScheduledTaskDetail({task,runs,+ runsLoaded = true,+ runsError = "",selectedRunId,running,+ runningKnown = true,busy,now,locale,@@ -48,8 +51,11 @@ export function ScheduledTaskDetail({}: {task: ScheduledTask;runs: ScheduledTaskRun[];+ runsLoaded?: boolean;+ runsError?: string;selectedRunId: string | null;running: boolean;+ runningKnown?: boolean;busy: boolean;now: number;locale: string;@@ -101,7 +107,7 @@ export function ScheduledTaskDetail({</div></div><div className="scheduled-detail-actions">- <Button size="sm" variant="primary" disabled={busy || running} onClick={onRunNow}>+ <Button size="sm" variant="primary" disabled={busy || running || !runningKnown} onClick={onRunNow}>{t(running ? "scheduled.statusRunning" : "scheduled.runNow")}</Button><Button size="sm" disabled={busy} onClick={onEdit}>@@ -110,7 +116,7 @@ export function ScheduledTaskDetail({<Button size="sm" disabled={busy} onClick={onToggleEnabled}>{t(task.enabled ? "scheduled.pause" : "scheduled.resume")}</Button>- <Button size="sm" variant="ghost" disabled={busy || running} onClick={onDelete}>+ <Button size="sm" variant="ghost" disabled={busy || running || !runningKnown} onClick={onDelete}>{t("scheduled.delete")}</Button></div>@@ -126,7 +132,7 @@ export function ScheduledTaskDetail({{latestDuration === null ? "" : ` · ${formatDuration(latestDuration)}`}</span>) : (- t("scheduled.neverRun")+ runsError || t(runsLoaded ? "scheduled.neverRun" : "common.loading"))}</Fact><Fact label={t("scheduled.nextRun")}>{nextRun}</Fact>@@ -171,6 +177,8 @@ export function ScheduledTaskDetail({<ScheduledRunHistoryruns={runs}+ loaded={runsLoaded}+ error={runsError}selectedRunId={selectedRun?.id ?? null}busy={busy}locale={locale}diff --git a/apps/desktop/src/features/scheduled/ScheduledTaskRail.tsx b/apps/desktop/src/features/scheduled/ScheduledTaskRail.tsxindex 1add29368..58b776d0c 100644--- a/apps/desktop/src/features/scheduled/ScheduledTaskRail.tsx+++ b/apps/desktop/src/features/scheduled/ScheduledTaskRail.tsx@@ -31,6 +31,8 @@ function RunGlyph({ run }: { run: ScheduledTaskRun }) {export function ScheduledTaskRail({tasks,latestRuns,+ latestRunsLoaded = true,+ latestRunsError = "",selectedTaskId,now,locale,@@ -38,6 +40,8 @@ export function ScheduledTaskRail({}: {tasks: ScheduledTask[];latestRuns: Map<string, ScheduledTaskRun>;+ latestRunsLoaded?: boolean;+ latestRunsError?: string;selectedTaskId: string | null;now: number;locale: string;@@ -95,7 +99,9 @@ export function ScheduledTaskRail({</span></span>) : (- <span className="scheduled-task-last is-empty">{t("scheduled.neverRun")}</span>+ <span className="scheduled-task-last is-empty" role={!latestRunsLoaded && !latestRunsError ? "status" : undefined}>+ {latestRunsError || t(latestRunsLoaded ? "scheduled.neverRun" : "common.loading")}+ </span>)}</button></li>diff --git a/apps/desktop/src/features/scheduled/scheduled-workspace-cache.ts b/apps/desktop/src/features/scheduled/scheduled-workspace-cache.tsnew file mode 100644index 000000000..7211e9d3f--- /dev/null+++ b/apps/desktop/src/features/scheduled/scheduled-workspace-cache.ts@@ -0,0 +1,18 @@+import type { ScheduledTask, ScheduledTaskRun } from "@pi-desktop/shared";++type ScheduledSnapshot = {+ tasks?: ScheduledTask[];+ latestPerTaskRuns?: ScheduledTaskRun[];+ history?: { taskId: string; runs: ScheduledTaskRun[] };+ selection?: { taskId: string; runId: string | null };+};++// Renderer-lifetime display data only; Host admission remains authoritative.+export const scheduledWorkspaceCache = {+ generation: 0,+ snapshot: {} as ScheduledSnapshot,+ clear() {+ this.generation++;+ this.snapshot = {};+ },+};diff --git a/apps/desktop/src/features/scheduled/use-scheduled-workspace.ts b/apps/desktop/src/features/scheduled/use-scheduled-workspace.tsindex cf4447f71..2a52e6d1a 100644--- a/apps/desktop/src/features/scheduled/use-scheduled-workspace.ts+++ b/apps/desktop/src/features/scheduled/use-scheduled-workspace.ts@@ -4,6 +4,7 @@ import { api } from "../../lib/api";import { latestRunByTask, resolveSelectedTaskId, runsForTask, taskIsRunning } from "./scheduled-runs";import type { ScheduledDraft } from "./ScheduledEditor";import { peekScheduledReturn } from "./scheduled-return";+import { scheduledWorkspaceCache as cache } from "./scheduled-workspace-cache";/** Same cadence the page always used: the host owns admission, the page only* reflects it. */@@ -26,6 +27,13 @@ export type ScheduledWorkspace = {busy: boolean;loaded: boolean;error: string;+ latestRunsLoaded: boolean;+ latestRunsError: string;+ runsLoaded: boolean;+ runsError: string;+ projectsLoaded: boolean;+ projectsError: string;+ loadProjects: () => Promise<void>;taskIsRunning: (taskId: string) => boolean;selectTask: (taskId: string) => void;selectRun: (runId: string) => void;@@ -47,19 +55,30 @@ export function useScheduledWorkspace(): ScheduledWorkspace {// Coming back from a run's conversation restores the same task and run.const restored = peekScheduledReturn();- const [tasks, setTasks] = useState<ScheduledTask[]>([]);- const [latestPerTaskRuns, setLatestPerTaskRuns] = useState<ScheduledTaskRun[]>([]);- const [taskRuns, setTaskRuns] = useState<ScheduledTaskRun[]>([]);+ const snapshot = cache.snapshot;+ const cachedTaskId = snapshot.selection?.taskId;+ const initialTaskId = restored?.taskId ?? (snapshot.tasks?.some((task) => task.id === cachedTaskId) ? cachedTaskId : snapshot.tasks?.[0]?.id) ?? null;+ const [tasks, setTasks] = useState<ScheduledTask[]>(snapshot.tasks ?? []);+ const [latestPerTaskRuns, setLatestPerTaskRuns] = useState<ScheduledTaskRun[]>(snapshot.latestPerTaskRuns ?? []);+ const [taskRuns, setTaskRuns] = useState<ScheduledTaskRun[]>(snapshot.history?.runs ?? []);+ const [latestRunsLoaded, setLatestRunsLoaded] = useState(snapshot.latestPerTaskRuns !== undefined);+ const [latestRunsError, setLatestRunsError] = useState("");+ const [historyTaskId, setHistoryTaskId] = useState(snapshot.history?.taskId ?? null);+ const [historyLoaded, setHistoryLoaded] = useState(snapshot.history !== undefined);+ const [historyError, setHistoryError] = useState("");const [projects, setProjects] = useState<ProjectRecord[]>([]);- const [selectedTaskId, setSelectedTaskId] = useState<string | null>(restored?.taskId ?? null);- const [selectedRunId, setSelectedRunId] = useState<string | null>(restored?.runId ?? null);+ const [projectsLoaded, setProjectsLoaded] = useState(false);+ const [projectsError, setProjectsError] = useState("");+ const [selectedTaskId, setSelectedTaskId] = useState<string | null>(initialTaskId);+ const [selectedRunId, setSelectedRunId] = useState<string | null>(restored?.runId ?? (snapshot.selection?.taskId === initialTaskId ? snapshot.selection.runId : null));const [busy, setBusy] = useState(false);- const [loaded, setLoaded] = useState(false);+ const [loaded, setLoaded] = useState(snapshot.tasks !== undefined);const [error, setError] = useState("");const mounted = useRef(false);const revision = useRef(0);const runRevision = useRef(0);+ const projectRevision = useRef(0);const selectedTaskIdRef = useRef<string | null>(null);const busyRef = useRef(false);const onErrorRef = useRef(onError);@@ -73,43 +92,69 @@ export function useScheduledWorkspace(const refresh = useCallback(async () => {const request = ++revision.current;- try {- const [taskResult, runResult, projectResult] = await Promise.all([- api.listScheduled(),- api.listScheduledRuns({ latestPerTask: true }),- api.listProjects().catch(() => ({ projects: [] as ProjectRecord[] })),- ]);- if (!mounted.current || request !== revision.current) return;- setTasks(taskResult.tasks);- setLatestPerTaskRuns(runResult.runs);- setProjects(projectResult.projects);- setError("");- setLoaded(true);- } catch (failure) {- if (mounted.current && request === revision.current) {- setError(failure instanceof Error ? failure.message : String(failure));- }- }+ const generation = cache.generation;+ const current = () => mounted.current && request === revision.current && generation === cache.generation;+ await Promise.all([+ api.listScheduled().then((result) => {+ if (!current()) return;+ cache.snapshot.tasks = result.tasks;+ setTasks(result.tasks);+ setError("");+ setLoaded(true);+ }).catch((failure) => {+ if (current()) setError(failure instanceof Error ? failure.message : String(failure));+ }),+ api.listScheduledRuns({ latestPerTask: true }).then((result) => {+ if (!current()) return;+ cache.snapshot.latestPerTaskRuns = result.runs;+ setLatestPerTaskRuns(result.runs);+ setLatestRunsLoaded(true);+ setLatestRunsError("");+ }).catch((failure) => {+ if (current()) setLatestRunsError(failure instanceof Error ? failure.message : String(failure));+ }),+ ]);}, []);const readTaskRuns = useCallback(async (taskId: string) => {const request = ++runRevision.current;+ const generation = cache.generation;try {const result = await api.listScheduledRuns({ taskId, limit: TASK_RUN_LIMIT });- if (!mounted.current || request !== runRevision.current) return;+ if (!mounted.current || request !== runRevision.current || generation !== cache.generation) return;+ cache.snapshot.history = { taskId, runs: result.runs };setTaskRuns(result.runs);- } catch {- // The rail still reports the outcome it read; an empty history with a- // retryable page error is better than clearing what the user is reading.- if (mounted.current && request === runRevision.current) setTaskRuns([]);+ setHistoryTaskId(taskId);+ setHistoryLoaded(true);+ setHistoryError("");+ } catch (failure) {+ if (mounted.current && request === runRevision.current && generation === cache.generation) {+ setHistoryTaskId(taskId);+ setHistoryError(failure instanceof Error ? failure.message : String(failure));+ }+ }+ }, []);++ const loadProjects = useCallback(async () => {+ const request = ++projectRevision.current;+ const generation = cache.generation;+ setProjectsLoaded(false);+ setProjectsError("");+ try {+ const result = await api.listProjects();+ if (!mounted.current || request !== projectRevision.current || generation !== cache.generation) return;+ setProjects(result.projects);+ setProjectsLoaded(true);+ } catch (failure) {+ if (mounted.current && request === projectRevision.current && generation === cache.generation) {+ setProjectsError(failure instanceof Error ? failure.message : String(failure));+ }}}, []);useEffect(() => {mounted.current = true;void refresh();- const id = selectedTaskIdRef.current;- if (id) void readTaskRuns(id);const timer = setInterval(() => {void refresh();const current = selectedTaskIdRef.current;@@ -119,6 +164,7 @@ export function useScheduledWorkspace(mounted.current = false;revision.current++;runRevision.current++;+ projectRevision.current++;clearInterval(timer);};}, [refresh, readTaskRuns]);@@ -133,12 +179,15 @@ export function useScheduledWorkspace(// A task switch releases the run selection, but the pair restored from a// conversation must survive the first mount or the reader loses the row that// brought them back.- const previousTaskRef = useRef<string | null>(restored?.taskId ?? null);+ const previousTaskRef = useRef<string | null>(initialTaskId);useEffect(() => {if (previousTaskRef.current !== selectedTaskId) {previousTaskRef.current = selectedTaskId;setSelectedRunId(null);+ setHistoryLoaded(false);+ setHistoryError("");}+ runRevision.current++;if (selectedTaskId) void readTaskRuns(selectedTaskId);}, [selectedTaskId, readTaskRuns]);@@ -210,8 +259,15 @@ export function useScheduledWorkspace([action],);- const selectTask = useCallback((taskId: string) => setSelectedTaskId(taskId), []);- const selectRun = useCallback((runId: string) => setSelectedRunId(runId), []);+ const selectTask = useCallback((taskId: string) => {+ cache.snapshot.selection = { taskId, runId: null };+ setSelectedTaskId(taskId);+ }, []);+ const selectRun = useCallback((runId: string) => {+ const taskId = selectedTaskIdRef.current;+ if (taskId) cache.snapshot.selection = { taskId, runId };+ setSelectedRunId(runId);+ }, []);const runningFor = useCallback((taskId: string) => taskIsRunning(latestPerTaskRuns, taskId),[latestPerTaskRuns],@@ -228,10 +284,20 @@ export function useScheduledWorkspace(busy,loaded,error,+ latestRunsLoaded,+ latestRunsError,+ runsLoaded: historyTaskId === selectedTaskId && historyLoaded,+ runsError: historyTaskId === selectedTaskId ? historyError : "",+ projectsLoaded,+ projectsError,+ loadProjects,taskIsRunning: runningFor,selectTask,selectRun,- refresh,+ refresh: async () => {+ const id = selectedTaskIdRef.current;+ await Promise.all([refresh(), ...(id ? [readTaskRuns(id)] : [])]);+ },saveTask,runTaskNow,toggleTask,diff --git a/apps/desktop/src/pages/ScheduledPage.tsx b/apps/desktop/src/pages/ScheduledPage.tsxindex 40ba09cfb..1186493df 100644--- a/apps/desktop/src/pages/ScheduledPage.tsx+++ b/apps/desktop/src/pages/ScheduledPage.tsx@@ -29,6 +29,11 @@ export function ScheduledPage() {const locale = i18n.resolvedLanguage ?? i18n.language;const { tasks, projects, selectedTask, selectedTaskId, runs, latestRuns, selectedRunId, busy, loaded, error } =workspace;+ const pageError = error || workspace.latestRunsError || workspace.runsError || (editor ? workspace.projectsError : "");+ const openEditor = (task: ScheduledTask | "new") => {+ setEditor(task);+ void workspace.loadProjects();+ };// Remember where the reader came from: the conversation offers the way back,// and this page restores the same task and the same run.@@ -65,20 +70,29 @@ export function ScheduledPage() {<h1 className="page-title">{t("scheduled.title")}</h1><p className="dest-row-meta">{t("scheduled.description")}</p></div>- <Button variant="primary" disabled={busy} onClick={() => setEditor("new")}>+ <Button variant="primary" disabled={busy} onClick={() => openEditor("new")}>{t("scheduled.create")}</Button></div>- {error && (+ {pageError && (<Panel className="scheduled-error">- <p role="alert">{error}</p>- <Button onClick={() => void workspace.refresh()}>{t("scheduled.retry")}</Button>+ <p role="alert">{pageError}</p>+ <Button onClick={() => {+ void workspace.refresh();+ if (editor) void workspace.loadProjects();+ }}>{t("scheduled.retry")}</Button></Panel>)}{!loaded && !error && <p role="status">{t("common.loading")}</p>}- {editor && (+ {editor && !workspace.projectsLoaded && (+ <div className="scheduled-editor-slot">+ {!workspace.projectsError && <p role="status">{t("common.loading")}</p>}+ <Button onClick={() => setEditor(null)}>{t("scheduled.cancel")}</Button>+ </div>+ )}+ {editor && workspace.projectsLoaded && (<div className="scheduled-editor-slot"><ScheduledEditorkey={editor === "new" ? "new" : editor.id}@@ -109,6 +123,8 @@ export function ScheduledPage() {<ScheduledTaskRailtasks={tasks}latestRuns={latestRuns}+ latestRunsLoaded={workspace.latestRunsLoaded}+ latestRunsError={workspace.latestRunsError}selectedTaskId={selectedTaskId}now={now}locale={locale}@@ -118,15 +134,18 @@ export function ScheduledPage() {<ScheduledTaskDetailtask={selectedTask}runs={runs}+ runsLoaded={workspace.runsLoaded}+ runsError={workspace.runsError}selectedRunId={selectedRunId}running={workspace.taskIsRunning(selectedTask.id)}+ runningKnown={workspace.latestRunsLoaded && !workspace.latestRunsError}busy={busy}now={now}locale={locale}onSelectRun={workspace.selectRun}onOpenSession={(sessionId, runId) => void openSession(sessionId, runId)}onRunNow={() => void workspace.runTaskNow(selectedTask.id)}- onEdit={() => setEditor(selectedTask)}+ onEdit={() => openEditor(selectedTask)}onToggleEnabled={() =>void workspace.toggleTask(selectedTask.id, !selectedTask.enabled)}diff --git a/apps/desktop/test/scheduled-return.test.mjs b/apps/desktop/test/scheduled-return.test.mjsindex 2d4022709..423eb9aa0 100644--- a/apps/desktop/test/scheduled-return.test.mjs+++ b/apps/desktop/test/scheduled-return.test.mjs@@ -155,8 +155,8 @@ test("the Scheduled route is the one that writes the return origin", async () =>assert.match(pageSource, /sessionId,/);assert.match(workspaceSource, /const restored = peekScheduledReturn\(\)/);- assert.match(workspaceSource, /useState<string \| null>\(restored\?\.taskId \?\? null\)/);- assert.match(workspaceSource, /useState<string \| null>\(restored\?\.runId \?\? null\)/);+ assert.match(workspaceSource, /const initialTaskId = restored\?\.taskId \?\?/);+ assert.match(workspaceSource, /useState<string \| null>\(restored\?\.runId \?\?/);assert.match(workspaceSource,/resolveSelectedTaskId\(tasks, current, loaded\)/,diff --git a/apps/desktop/test/scheduled-workspace-loading.test.mjs b/apps/desktop/test/scheduled-workspace-loading.test.mjsnew file mode 100644index 000000000..0f223ccf1--- /dev/null+++ b/apps/desktop/test/scheduled-workspace-loading.test.mjs@@ -0,0 +1,176 @@+import assert from "node:assert/strict";+import test from "node:test";+import { readFileSync } from "node:fs";+import { register } from "node:module";+import ts from "typescript";++register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const returns = await import("../src/features/scheduled/scheduled-return.ts");+const runs = await import("../src/features/scheduled/scheduled-runs.ts");+const { scheduledWorkspaceCache: cache } = await import("../src/features/scheduled/scheduled-workspace-cache.ts");+const code = ts.transpileModule(readFileSync(new URL("../src/features/scheduled/use-scheduled-workspace.ts", import.meta.url), "utf8"), {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },+}).outputText;+const deferred = () => {+ let resolve, reject;+ const promise = new Promise((a, b) => { resolve = a; reject = b; });+ return { promise, resolve, reject };+};++// Exercise the production hook with controlled API promises and poll ticks.+function harness(api) {+ const slots = [], effects = [], timers = new Set();+ let cursor = 0, dirty = true, output;+ const equal = (a, b) => a?.length === b?.length && a?.every((value, index) => value === b[index]);+ const memo = (work, deps) => {+ const index = cursor++, old = slots[index];+ if (!old || !equal(old.deps, deps)) slots[index] = { deps, value: work() };+ return slots[index].value;+ };+ const react = {+ useState(initial) {+ const index = cursor++;+ slots[index] ??= { value: typeof initial === "function" ? initial() : initial };+ return [slots[index].value, next => {+ const value = typeof next === "function" ? next(slots[index].value) : next;+ if (value !== slots[index].value) { slots[index].value = value; dirty = true; }+ }];+ },+ useRef(initial) { const index = cursor++; slots[index] ??= { value: { current: initial } }; return slots[index].value; },+ useMemo: memo,+ useCallback: (work, deps) => memo(() => work, deps),+ useEffect(work, deps) {+ const index = cursor++, old = slots[index];+ if (!old || !equal(old.deps, deps)) {+ slots[index] = { deps, cleanup: old?.cleanup };+ effects.push(() => { slots[index].cleanup?.(); slots[index].cleanup = work(); });+ }+ },+ };+ const exports = {};+ new Function("exports", "require", "setInterval", "clearInterval", code)(exports, id => {+ if (id === "react") return react;+ if (id === "../../lib/api") return { api };+ if (id === "./scheduled-return") return returns;+ if (id === "./scheduled-workspace-cache") return { scheduledWorkspaceCache: cache };+ if (id === "./scheduled-runs") return runs;+ throw new Error(`Unexpected import: ${id}`);+ }, callback => { timers.add(callback); return callback; }, callback => timers.delete(callback));+ return {+ get output() { return output; },+ async settle() {+ for (let round = 0; round < 30; round++) {+ if (dirty) { dirty = false; cursor = 0; output = exports.useScheduledWorkspace(() => {}); }+ while (effects.length) effects.shift()();+ await Promise.resolve();+ }+ },+ tick() { for (const callback of timers) callback(); },+ close() { for (const slot of slots) slot.cleanup?.(); },+ };+}+const task = id => ({ id, title: id });+const run = (id, taskId) => ({ id, taskId, status: "completed", startedAt: "2026-01-01T00:00:00Z" });+const api = (overrides = {}) => ({+ listScheduled: async () => ({ tasks: [task("a"), task("b")] }),+ listScheduledRuns: async () => ({ runs: [] }),+ listProjects: async () => ({ projects: [] }),+ ...overrides,+});+test.beforeEach(() => cache.clear());++test("task definitions display before held outcomes; project options load only for editing", async t => {+ const outcomes = deferred(), projects = deferred();+ let projectsRequested = false;+ const h = harness(api({+ listScheduledRuns: input => input.latestPerTask ? outcomes.promise : Promise.resolve({ runs: [] }),+ listProjects: () => { projectsRequested = true; return projects.promise; },+ }));+ t.after(() => h.close());+ await h.settle();+ assert.equal(h.output.loaded, true);+ assert.equal(h.output.tasks.length, 2);+ assert.equal(h.output.latestRunsLoaded, false);+ assert.equal(projectsRequested, false);+ h.output.loadProjects(); await h.settle();+ assert.equal(projectsRequested, true);+ assert.equal(h.output.projectsLoaded, false);+ assert.equal(h.output.tasks.length, 2);+ projects.resolve({ projects: [{ id: 1, path: "/synthetic/project" }] });+ outcomes.resolve({ runs: [] }); await h.settle();+ assert.equal(h.output.projectsLoaded, true);+ assert.equal(h.output.latestRunsLoaded, true);+});++test("route return displays cached definitions and outcomes while refreshing", async t => {+ const first = harness(api({ listScheduledRuns: async () => ({ runs: [run("first", "a")] }) }));+ await first.settle(); first.close();+ const refresh = deferred();+ const second = harness(api({ listScheduled: () => refresh.promise, listScheduledRuns: () => new Promise(() => {}) }));+ t.after(() => second.close()); await second.settle();+ assert.equal(second.output.loaded, true);+ assert.equal(second.output.tasks[0].id, "a");+ assert.equal(second.output.latestRuns.get("a").id, "first");+ refresh.resolve({ tasks: [task("b")] }); await second.settle();+ assert.deepEqual(second.output.tasks.map(value => value.id), ["b"]);+});++test("return restores the selected task, run and bounded history", async t => {+ const record = run("selected-b", "b");+ const first = harness(api({ listScheduledRuns: async input => ({ runs: input.taskId === "b" ? [record] : [] }) }));+ await first.settle(); first.output.selectTask("b"); await first.settle();+ first.output.selectRun(record.id); await first.settle(); first.close();+ const next = harness(api({ listScheduled: () => new Promise(() => {}), listScheduledRuns: () => new Promise(() => {}) }));+ t.after(() => next.close()); await next.settle();+ assert.equal(next.output.selectedTaskId, "b");+ assert.equal(next.output.selectedRunId, record.id);+ assert.equal(next.output.runsLoaded, true);+ assert.deepEqual(next.output.runs, [record]);+});++test("failed summaries and task histories stay distinguishable from successful empty results", async t => {+ const h = harness(api({ listScheduledRuns: async () => { throw new Error("Synthetic read failure"); } }));+ t.after(() => h.close()); await h.settle();+ assert.equal(h.output.loaded, true);+ assert.equal(h.output.latestRunsLoaded, false);+ assert.match(h.output.latestRunsError, /Synthetic read failure/);+ assert.match(h.output.runsError, /Synthetic read failure/);+ assert.equal(h.output.runsLoaded, false);+});++test("late histories cannot replace the selected task and failures retain known history", async t => {+ const old = deferred(), newest = run("b-result", "b"); let fail = false;+ const h = harness(api({ listScheduledRuns: input => input.latestPerTask ? Promise.resolve({ runs: [] })+ : input.taskId === "a" ? old.promise : fail ? Promise.reject(new Error("Unavailable")) : Promise.resolve({ runs: [newest] }) }));+ t.after(() => h.close()); await h.settle();+ h.output.selectTask("b"); await h.settle();+ old.resolve({ runs: [run("late-a", "a")] }); await h.settle();+ assert.deepEqual(h.output.runs, [newest]);+ fail = true; h.tick(); await h.settle();+ assert.deepEqual(h.output.runs, [newest]);+ assert.match(h.output.runsError, /Unavailable/);+});++test("invalidated lifecycle rejects late reads and does not repopulate the next page", async t => {+ const held = deferred();+ const first = harness(api({ listScheduled: () => held.promise }));+ await first.settle(); cache.clear();+ held.resolve({ tasks: [task("old-host")] }); await first.settle(); first.close();+ assert.equal(cache.snapshot.tasks, undefined);+ const next = harness(api({ listScheduled: () => new Promise(() => {}) }));+ t.after(() => next.close()); await next.settle();+ assert.equal(next.output.loaded, false);+ assert.deepEqual(next.output.tasks, []);+});++test("conversation return takes precedence over the cached task during initial loading", async t => {+ returns.rememberScheduledReturn({ taskId: "b", taskTitle: "Synthetic B", runId: "restored-b", sessionId: "synthetic-session" });+ const held = deferred();+ const h = harness(api({ listScheduled: () => held.promise }));+ t.after(() => h.close()); await h.settle();+ assert.equal(h.output.selectedTaskId, "b");+ assert.equal(h.output.selectedRunId, "restored-b");+ held.resolve({ tasks: [task("a"), task("b")] }); await h.settle();+ assert.equal(h.output.selectedTaskId, "b");+ assert.equal(h.output.selectedRunId, "restored-b");+});diff --git a/apps/desktop/test/scheduled-workspace.test.mjs b/apps/desktop/test/scheduled-workspace.test.mjsindex 17616bcc7..6d06171ce 100644--- a/apps/desktop/test/scheduled-workspace.test.mjs+++ b/apps/desktop/test/scheduled-workspace.test.mjs@@ -288,6 +288,24 @@ test("a run with no stored transcript says so instead of showing an empty pane",});});+test("pending or failed run reads never render as a task that has not run", async () => {+ await withVite(async server => {+ const props = { tasks: [TASK_A], latestRuns: new Map(), selectedTaskId: TASK_A.id, now: NOW, locale: "en", onSelect() {} };+ const loading = await render(server, "/src/features/scheduled/ScheduledTaskRail.tsx", "ScheduledTaskRail", { ...props, latestRunsLoaded: false });+ assert.match(loading, /Loading/);+ assert.doesNotMatch(loading, /Not run yet/);+ const failed = await render(server, "/src/features/scheduled/ScheduledTaskRail.tsx", "ScheduledTaskRail", { ...props, latestRunsError: "Synthetic read failure" });+ assert.match(failed, /Synthetic read failure/);+ assert.doesNotMatch(failed, /Not run yet/);+ const historyProps = { runs: [], selectedRunId: null, busy: false, locale: "en", onSelectRun() {}, onOpenSession() {} };+ for (const state of [{ loaded: false }, { loaded: false, error: "Synthetic read failure" }]) {+ const history = await render(server, "/src/features/scheduled/ScheduledRunHistory.tsx", "ScheduledRunHistory", { ...historyProps, ...state });+ assert.match(history, state.error ? /Synthetic read failure/ : /Loading/);+ assert.doesNotMatch(history, new RegExp(catalogs.en.scheduled.emptyRuns.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));+ }+ });+});+test("automation ownership keeps run transcripts out of the lists", async () => {await withVite(async (server) => {const { isAutomationSession } = await server.ssrLoadModule("/src/lib/session-origin.ts");diff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.mdindex 30e37501d..daccdd93e 100644--- a/docs/spec/04-ux/01-ui-ia.md+++ b/docs/spec/04-ux/01-ui-ia.md@@ -306,6 +306,15 @@ destination, chat as the home surface, tools and permissions inline.focus.### 3.3 Scheduled+Task definitions render as soon as their own read completes; latest outcomes+and the selected task's bounded history load independently. Pending or failed+run reads never imply that a task has not run. Returning to the route displays+the renderer's last successful in-memory snapshot while refreshing. Host loss+or restart invalidates that snapshot and rejects late responses from the old+lifecycle. Project options load only when opening Create/Edit; the form waits+for that read to succeed and exposes retry on failure. Run now and Delete wait+for known run status; Host admission remains authoritative.+Settings → Behavior → Execution → Scheduled tasks controls this feature, on by default(`scheduledTasksEnabled` absent or true). Off hides the footer and search pageentries and prevents new runs without deleting tasks or run history. Thediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex e4c1ddc92..ba0ab1764 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1,5 +1,25 @@# 04. E2E Test Plan+## E2E-SCHEDULED-independent-loading-and-route-return++- **Preconditions:** Synthetic tasks; controllable task, latest-run, history and+ project API responses. No provider execution is required.+- **Steps:** Hold latest-run and project reads while resolving task definitions;+ select a task and run, leave and re-enter with refresh held; open Create/Edit;+ fail and retry a history read; switch tasks while a previous history is held;+ invalidate the Host lifecycle before an old read resolves.+- **Expected:** Definitions appear independently. Route return immediately shows+ the last successful in-memory task/outcome/history snapshot and selection.+ Project options are requested only for editing; the form waits for successful+ options and failures expose retry. Pending/failed run reads never say the task+ has not run. Failed refresh retains known history, and late responses cannot+ replace another task's data or repopulate an invalidated snapshot. Run now and+ Delete require known run status and retain authoritative Host admission.+- **Coverage:** `apps/desktop/test/scheduled-workspace-loading.test.mjs` exercises+ the production hook with controlled API promises and poll ticks;+ `scheduled-workspace.test.mjs` checks rendered loading/error states.+ These are renderer regression checks, not a native Electron E2E run.+## E2E-PROVIDER-DASHSCOPE-terminal-parameter-error- **Preconditions:** Isolated Agent runtime and a synthetic OpenAI-compatiblediff --git a/docs/zh-CN/spec/04-ux/01-ui-ia.md b/docs/zh-CN/spec/04-ux/01-ui-ia.mdindex 6a4abc8d9..5c55aae79 100644--- a/docs/zh-CN/spec/04-ux/01-ui-ia.md+++ b/docs/zh-CN/spec/04-ux/01-ui-ia.md@@ -219,6 +219,15 @@焦点。### 3. 3 定时任务++Task definitions render as soon as their own read completes; latest outcomes+and the selected task's bounded history load independently. Pending or failed+run reads never imply that a task has not run. Returning to the route displays+the renderer's last successful in-memory snapshot while refreshing. Host loss+or restart invalidates that snapshot and rejects late responses from the old+lifecycle. Project options load only when opening Create/Edit; the form waits+for that read to succeed and exposes retry on failure. Run now and Delete wait+for known run status; Host admission remains authoritative.任务列与所选任务的页面并排展示,支持创建、编辑、暂停、启用和确认删除。表单可为每个任务单独选择项目、权限、模型与会话模式(每次新开会话或复用同一会话)。周期保留下拉选择,并与时分统一为自定义主题菜单。每小时按一小时间隔执行,不显示时间选择;保存、启用、启动或上次自动准入后重新计时。间隔直接给出跨度:数量加分钟或小时单位(5 分钟至 24 小时),从准入时刻起算。每天通过下拉框选择上午 09:00、下午 14:00、晚上 19:00、夜间 22:00;diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 75caab25e..1b3b7cbb9 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -1,5 +1,25 @@# 04. E2E 测试 Plan+## E2E-SCHEDULED-independent-loading-and-route-return++- **Preconditions:** Synthetic tasks; controllable task, latest-run, history and+ project API responses. No provider execution is required.+- **Steps:** Hold latest-run and project reads while resolving task definitions;+ select a task and run, leave and re-enter with refresh held; open Create/Edit;+ fail and retry a history read; switch tasks while a previous history is held;+ invalidate the Host lifecycle before an old read resolves.+- **Expected:** Definitions appear independently. Route return immediately shows+ the last successful in-memory task/outcome/history snapshot and selection.+ Project options are requested only for editing; the form waits for successful+ options and failures expose retry. Pending/failed run reads never say the task+ has not run. Failed refresh retains known history, and late responses cannot+ replace another task's data or repopulate an invalidated snapshot. Run now and+ Delete require known run status and retain authoritative Host admission.+- **Coverage:** `apps/desktop/test/scheduled-workspace-loading.test.mjs` exercises+ the production hook with controlled API promises and poll ticks;+ `scheduled-workspace.test.mjs` checks rendered loading/error states.+ These are renderer regression checks, not a native Electron E2E run.+> **翻译说明:** 本页是与 [英文源规格](/spec/06-delivery/04-e2e-test-plan) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。