Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(scheduled): return from a run's conversation to its task
Hanawa16b671aaa491
diff --git a/apps/desktop/src/components/ConversationTopbar.tsx b/apps/desktop/src/components/ConversationTopbar.tsxindex 3720928c7..3649d12cc 100644--- a/apps/desktop/src/components/ConversationTopbar.tsx+++ b/apps/desktop/src/components/ConversationTopbar.tsx@@ -7,6 +7,11 @@ import {import { useTranslation } from "react-i18next";import { useAppStore } from "../stores/app-store";import {+ scheduledReturnFor,+ scheduledReturnUsesHistory,+} from "../features/scheduled/scheduled-return";+import {+ IconChevronLeft,IconSidebar,IconNewSession,IconSearch,@@ -44,6 +49,10 @@ export function ConversationTopbar({const sessions = useAppStore((s) => s.sessions);const workspace = useAppStore((s) => s.workspace);const keybindings = useAppStore((s) => s.settings?.keybindings);+ const navStack = useAppStore((s) => s.navStack);+ const navIndex = useAppStore((s) => s.navIndex);+ const navBack = useAppStore((s) => s.navBack);+ const setPage = useAppStore((s) => s.setPage);const platform = (typeof window === "undefined" ? "darwin" : window.piDesktop?.platform ?? "darwin") as ShortcutPlatform;@@ -80,6 +89,23 @@ export function ConversationTopbar({const activeSession = sessions.find((session) => session.id === activeSessionId);+ /*+ * A scheduled run's conversation is read from the Scheduled route, and the+ * session list keeps automation transcripts out, so this row is the way+ * back. The remembered origin is what restores the task and run exactly.+ */+ const scheduledSession = activeSession?.scheduledRun === true ? activeSession : null;+ const scheduledReturn = scheduledSession ? scheduledReturnFor(scheduledSession.id) : null;+ const backAction = t("nav.backToScheduledAction");+ const backTooltip = scheduledReturn+ ? t("nav.backToScheduledTask", { title: scheduledReturn.taskTitle })+ : backAction;+ const goBackToScheduled = () => {+ /* History first: it re-enters the route with the reader's own stack. */+ if (scheduledReturnUsesHistory(navStack, navIndex)) navBack();+ else setPage("scheduled");+ };+const fullTaskTitle = isDefaultSessionTitle(activeSession?.title)? t("chat.untitledTask"): activeSession?.title || t("chat.untitledTask");@@ -111,6 +137,19 @@ export function ConversationTopbar({<IconSidebar size={15} /></TooltipButton></div>+ {scheduledSession ? (+ <button+ type="button"+ className="ct-back"+ data-nav="back-to-scheduled"+ aria-label={backAction}+ title={backTooltip}+ onClick={goBackToScheduled}+ >+ <IconChevronLeft size={13} aria-hidden />+ <span className="ct-back-label">{t("nav.backToScheduled")}</span>+ </button>+ ) : null}<divclassName="ct-title-wrap"title={project ? `${project} · ${fullTaskTitle}` : fullTaskTitle}diff --git a/apps/desktop/src/features/scheduled/ScheduledEditor.tsx b/apps/desktop/src/features/scheduled/ScheduledEditor.tsxindex 6b1066488..4c02f288e 100644--- a/apps/desktop/src/features/scheduled/ScheduledEditor.tsx+++ b/apps/desktop/src/features/scheduled/ScheduledEditor.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import type { GlobalPermissionMode, ProjectRecord, ScheduledTask } from "@pi-desktop/shared";+import type { GlobalPermissionMode, ProjectRecord, ScheduledTask, ScheduledSessionMode } from "@pi-desktop/shared";import { Button, Field, Input, Textarea } from "../../components/ui";import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";import { ScheduledWeekdaySelect } from "./ScheduledWeekdaySelect";@@ -17,6 +17,7 @@ export type ScheduledDraft = Pick<ScheduledTask, "title" | "prompt" | "cadence"providerId?: string | null;modelId?: string | null;thinkingLevel?: ScheduledTask["thinkingLevel"] | null;+ sessionMode?: ScheduledSessionMode;};export function ScheduledEditor({@@ -52,6 +53,10 @@ export function ScheduledEditor({task?.permissionMode ?? "ask",);const [permissionTouched, setPermissionTouched] = useState(false);+ // A conversation mode always has a value, so it is saved with every draft.+ const [sessionMode, setSessionMode] = useState<ScheduledSessionMode>(+ task?.sessionMode ?? "perRun",+ );const defaultModel = !task && settings?.defaultProviderId && settings.defaultModelId? { providerId: settings.defaultProviderId, modelId: settings.defaultModelId }: {};@@ -93,7 +98,7 @@ export function ScheduledEditor({if (busy || !valid) return;const executionSettings: Pick<ScheduledDraft,- "workspacePath" | "permissionMode" | "providerId" | "modelId" | "thinkingLevel"+ "workspacePath" | "permissionMode" | "providerId" | "modelId" | "thinkingLevel" | "sessionMode"> = {};if (!task || task.workspacePath || workspaceTouched) {if (workspacePath) executionSettings.workspacePath = workspacePath;@@ -108,6 +113,8 @@ export function ScheduledEditor({if (modelTouched || task?.thinkingLevel) {executionSettings.thinkingLevel = modelSelection.thinkingLevel ?? null;}+ // The mode always has a value, so it is saved with every draft.+ executionSettings.sessionMode = sessionMode;void save({title: title.trim(),prompt: prompt.trim(),@@ -152,6 +159,7 @@ export function ScheduledEditor({projects={projects}permissionMode={permissionMode}modelSelection={modelSelection}+ sessionMode={sessionMode}busy={busy}onWorkspaceChange={(path) => {setWorkspacePath(path);@@ -165,6 +173,7 @@ export function ScheduledEditor({setModelSelection(selection);setModelTouched(true);}}+ onSessionModeChange={setSessionMode}/></div></Field>@@ -173,6 +182,12 @@ export function ScheduledEditor({{t("scheduled.autoPermissionHint")}</p>)}++ {sessionMode === "reuse" && (+ <p className="dest-row-meta" role="status">+ {t("scheduled.sessionModeHint")}+ </p>+ )}<div className="scheduled-fields"><Field label={t("scheduled.cadence")}><SettingsMenuSelectdiff --git a/apps/desktop/src/features/scheduled/ScheduledExecutionSettings.tsx b/apps/desktop/src/features/scheduled/ScheduledExecutionSettings.tsxindex 842c02280..bddb8648a 100644--- a/apps/desktop/src/features/scheduled/ScheduledExecutionSettings.tsx+++ b/apps/desktop/src/features/scheduled/ScheduledExecutionSettings.tsx@@ -3,9 +3,10 @@ import { useTranslation } from "react-i18next";import {type GlobalPermissionMode,type ProjectRecord,+ type ScheduledSessionMode,type SessionThinkingLevel,} from "@pi-desktop/shared";-import { IconFolder } from "../../components/icons";+import { IconChat, IconFolder } from "../../components/icons";import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";import { useAppStore } from "../../stores/app-store";import { ScheduledModelPicker } from "./ScheduledModelPicker";@@ -33,6 +34,8 @@ export function ScheduledExecutionSettings({onWorkspaceChange,onPermissionChange,onModelChange,+ sessionMode,+ onSessionModeChange,}: {workspacePath: string;projects: readonly ProjectRecord[];@@ -42,6 +45,8 @@ export function ScheduledExecutionSettings({onWorkspaceChange: (path: string) => void;onPermissionChange: (mode: GlobalPermissionMode) => void;onModelChange: (selection: ScheduledModelSelection) => void;+ sessionMode: ScheduledSessionMode;+ onSessionModeChange: (mode: ScheduledSessionMode) => void;}) {const { t } = useTranslation();const [permissionOpen, setPermissionOpen] = useState(false);@@ -86,6 +91,19 @@ export function ScheduledExecutionSettings({permissionOpen={permissionOpen} setPermissionOpen={setPermissionOpen}controlsBlocked={busy} onCloseOtherMenus={() => {}}onSelect={onPermissionChange} />+ <SettingsMenuSelect+ className="scheduled-execution-session"+ triggerClassName="icon-btn mode-chip scheduled-execution-trigger"+ leading={<IconChat size={14} />}+ label={t("scheduled.sessionMode")}+ value={sessionMode}+ disabled={busy}+ options={[+ { id: "perRun", label: t("scheduled.sessionModePerRun") },+ { id: "reuse", label: t("scheduled.sessionModeReuse") },+ ]}+ onChange={(value) => onSessionModeChange(value === "reuse" ? "reuse" : "perRun")}+ /></div><div className="composer-right"><ScheduledModelPicker value={modelSelection} disabled={busy} onChange={onModelChange} />diff --git a/apps/desktop/src/features/scheduled/ScheduledRunHistory.tsx b/apps/desktop/src/features/scheduled/ScheduledRunHistory.tsxindex f670c90cb..238fd9978 100644--- a/apps/desktop/src/features/scheduled/ScheduledRunHistory.tsx+++ b/apps/desktop/src/features/scheduled/ScheduledRunHistory.tsx@@ -41,7 +41,7 @@ export function ScheduledRunHistory({busy: boolean;locale: string;onSelectRun: (runId: string) => void;- onOpenSession: (sessionId: string) => void;+ onOpenSession: (sessionId: string, runId: string) => void;}) {const { t } = useTranslation();return (@@ -94,7 +94,7 @@ export function ScheduledRunHistory({ariaLabel={t("scheduled.openResult")}className="scheduled-icon-btn"disabled={busy}- onClick={() => onOpenSession(sessionId)}+ onClick={() => onOpenSession(sessionId, run.id)}><IconExternal size={14} aria-hidden /></TooltipButton>diff --git a/apps/desktop/src/features/scheduled/ScheduledRunTranscript.tsx b/apps/desktop/src/features/scheduled/ScheduledRunTranscript.tsxindex d2f82a6c3..e2b17dd3b 100644--- a/apps/desktop/src/features/scheduled/ScheduledRunTranscript.tsx+++ b/apps/desktop/src/features/scheduled/ScheduledRunTranscript.tsx@@ -37,11 +37,15 @@ function roleLabelKey(role: UiMessage["role"]): string {function TranscriptMessage({ message }: { message: UiMessage }) {const { t } = useTranslation();const text = message.content.trim();- // A tool call with no text of its own adds nothing a reader can use here.+ // A step with no text of its own adds nothing a reader can use here.if (!text) return null;return (<li className={`scheduled-message scheduled-message-${message.role}`}>- <span className="scheduled-message-role">{t(roleLabelKey(message.role))}</span>+ <span className="scheduled-message-role">+ {message.role === "tool" && message.toolName+ ? message.toolName+ : t(roleLabelKey(message.role))}+ </span><p className="scheduled-message-text" data-status={message.status ?? "complete"}>{text}</p>@@ -50,9 +54,10 @@ function TranscriptMessage({ message }: { message: UiMessage }) {}/**- * Read-only view of one run's transcript, rendered inside the Scheduled page so- * reviewing an automation result never costs a conversation switch. The- * conversation itself stays one explicit action away.+ * Read-only view of one run's transcript — the steps it took and the answer it+ * produced — rendered inside the Scheduled page so reviewing an automation+ * result never costs a conversation switch. The conversation itself stays one+ * explicit action away.*/export function ScheduledRunTranscript({ run }: { run: ScheduledTaskRun }) {const { t } = useTranslation();@@ -124,7 +129,11 @@ export function ScheduledRunTranscript({ run }: { run: ScheduledTaskRun }) {if (reading.messages.length === 0) {return (<p className="scheduled-hint" role={reading.status === "loading" ? "status" : undefined}>- {t(reading.status === "loading" ? "scheduled.runContentLoading" : "scheduled.runContentUnavailable")}+ {t(+ reading.status === "loading"+ ? "scheduled.runContentLoading"+ : "scheduled.runContentUnavailable",+ )}</p>);}diff --git a/apps/desktop/src/features/scheduled/ScheduledTaskDetail.tsx b/apps/desktop/src/features/scheduled/ScheduledTaskDetail.tsxindex 1eb84886e..f8af60905 100644--- a/apps/desktop/src/features/scheduled/ScheduledTaskDetail.tsx+++ b/apps/desktop/src/features/scheduled/ScheduledTaskDetail.tsx@@ -54,7 +54,7 @@ export function ScheduledTaskDetail({now: number;locale: string;onSelectRun: (runId: string) => void;- onOpenSession: (sessionId: string) => void;+ onOpenSession: (sessionId: string, runId: string) => void;onRunNow: () => void;onEdit: () => void;onToggleEnabled: () => void;@@ -136,6 +136,13 @@ export function ScheduledTaskDetail({{t(PERMISSION_MODE_I18N_KEYS[task.permissionMode ?? "inherit"])}</Fact><Fact label={t("scheduled.detailModel")}>{model}</Fact>+ <Fact label={t("scheduled.sessionMode")}>+ {t(+ task.sessionMode === "reuse"+ ? "scheduled.sessionModeReuse"+ : "scheduled.sessionModePerRun",+ )}+ </Fact></dl><section className="scheduled-card" aria-labelledby="scheduled-instruction">@@ -190,7 +197,7 @@ export function ScheduledTaskDetail({size="sm"variant="ghost"disabled={busy}- onClick={() => onOpenSession(selectedSessionId)}+ onClick={() => onOpenSession(selectedSessionId, selectedRun.id)}><IconExternal size={13} aria-hidden />{t("scheduled.openResult")}diff --git a/apps/desktop/src/features/scheduled/scheduled-return.ts b/apps/desktop/src/features/scheduled/scheduled-return.tsnew file mode 100644index 000000000..7f1d2c38e--- /dev/null+++ b/apps/desktop/src/features/scheduled/scheduled-return.ts@@ -0,0 +1,50 @@+/**+ * Where a scheduled run's conversation was opened from.+ *+ * Hiding automation transcripts from the SessionList (issue #1291) made the+ * Scheduled route their only entry point, so the chat surface has to offer the+ * way back — and returning should land on the same task and the same run the+ * reader left. The origin is remembered for the session it belongs to, so a+ * later visit to an unrelated conversation never offers it.+ */+export type ScheduledReturnOrigin = {+ taskId: string;+ taskTitle: string;+ /** The run whose transcript the reader opened, when a row started it. */+ runId: string | null;+ sessionId: string;+};++let origin: ScheduledReturnOrigin | null = null;++/** Remember the run row a conversation was opened from. */+export function rememberScheduledReturn(next: ScheduledReturnOrigin): void {+ origin = next;+}++/** The remembered origin, without consuming it: the Scheduled route restores+ * its selection from this on every mount, and revisiting must keep working. */+export function peekScheduledReturn(): ScheduledReturnOrigin | null {+ return origin;+}++/** The origin only when it belongs to the conversation being shown. */+export function scheduledReturnFor(+ sessionId: string | null | undefined,+): ScheduledReturnOrigin | null {+ if (!sessionId || origin?.sessionId !== sessionId) return null;+ return origin;+}++/**+ * Whether going back can reuse the navigation history: only when the entry+ * right behind this conversation is the Scheduled route. Anything else (the+ * reader navigated on) falls back to opening the route directly.+ */+export function scheduledReturnUsesHistory(+ stack: readonly { page: string }[],+ index: number,+): boolean {+ if (index <= 0 || index >= stack.length) return false;+ return stack[index - 1]?.page === "scheduled";+}diff --git a/apps/desktop/src/features/scheduled/scheduled-runs.ts b/apps/desktop/src/features/scheduled/scheduled-runs.tsindex f630d17b0..ba712fe2a 100644--- a/apps/desktop/src/features/scheduled/scheduled-runs.ts+++ b/apps/desktop/src/features/scheduled/scheduled-runs.ts@@ -1,4 +1,4 @@-import type { ScheduledTaskRun } from "@pi-desktop/shared";+import type { ScheduledTask, ScheduledTaskRun } from "@pi-desktop/shared";export type ScheduledRunStatus = ScheduledTaskRun["status"];@@ -86,3 +86,17 @@ export function latestRunForTask(if (!taskId) return null;return runsForTask(runs, taskId)[0] ?? null;}++/** The task the workspace keeps selected: the caller's pick while that task+ * still exists, otherwise the first one. A selection restored from a+ * conversation must survive the first read — an empty list is not a verdict+ * on whether the task exists. */+export function resolveSelectedTaskId(+ tasks: readonly ScheduledTask[],+ selectedTaskId: string | null | undefined,+ loaded: boolean,+): string | null {+ if (!loaded) return selectedTaskId ?? null;+ if (selectedTaskId && tasks.some((task) => task.id === selectedTaskId)) return selectedTaskId;+ return tasks[0]?.id ?? null;+}diff --git a/apps/desktop/src/features/scheduled/use-scheduled-workspace.ts b/apps/desktop/src/features/scheduled/use-scheduled-workspace.tsindex c84525cde..8fd40f4f3 100644--- a/apps/desktop/src/features/scheduled/use-scheduled-workspace.ts+++ b/apps/desktop/src/features/scheduled/use-scheduled-workspace.ts@@ -1,8 +1,9 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type { ProjectRecord, ScheduledTask, ScheduledTaskRun } from "@pi-desktop/shared";import { api } from "../../lib/api";-import { latestRunByTask, runsForTask, taskIsRunning } from "./scheduled-runs";+import { latestRunByTask, resolveSelectedTaskId, runsForTask, taskIsRunning } from "./scheduled-runs";import type { ScheduledDraft } from "./ScheduledEditor";+import { peekScheduledReturn } from "./scheduled-return";/** Same cadence the page always used: the host owns admission, the page only* reflects it. */@@ -44,12 +45,14 @@ export type ScheduledWorkspace = {export function useScheduledWorkspace(onError: (message: string) => void,): ScheduledWorkspace {+ // Coming back from a run's conversation restores the same task and run.+ const restored = peekScheduledReturn();const [tasks, setTasks] = useState<ScheduledTask[]>([]);const [recentRuns, setRecentRuns] = useState<ScheduledTaskRun[]>([]);const [taskRuns, setTaskRuns] = useState<ScheduledTaskRun[]>([]);const [projects, setProjects] = useState<ProjectRecord[]>([]);- const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);- const [selectedRunId, setSelectedRunId] = useState<string | null>(null);+ const [selectedTaskId, setSelectedTaskId] = useState<string | null>(restored?.taskId ?? null);+ const [selectedRunId, setSelectedRunId] = useState<string | null>(restored?.runId ?? null);const [busy, setBusy] = useState(false);const [loaded, setLoaded] = useState(false);const [error, setError] = useState("");@@ -121,16 +124,21 @@ export function useScheduledWorkspace(}, [refresh, readTaskRuns]);// Keep one task selected: the first one, or the previous selection while it- // still exists. A deleted task never leaves the pane pointing at nothing.+ // still exists. A deleted task never leaves the pane pointing at nothing, and+ // a selection restored from a conversation outlives the first, empty read.useEffect(() => {- setSelectedTaskId((current) => {- if (current && tasks.some((task) => task.id === current)) return current;- return tasks[0]?.id ?? null;- });- }, [tasks]);+ setSelectedTaskId((current) => resolveSelectedTaskId(tasks, current, loaded));+ }, [tasks, loaded]);+ // 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);useEffect(() => {- setSelectedRunId(null);+ if (previousTaskRef.current !== selectedTaskId) {+ previousTaskRef.current = selectedTaskId;+ setSelectedRunId(null);+ }if (selectedTaskId) void readTaskRuns(selectedTaskId);}, [selectedTaskId, readTaskRuns]);diff --git a/apps/desktop/src/pages/ScheduledPage.tsx b/apps/desktop/src/pages/ScheduledPage.tsxindex eb77bce79..a6cd62298 100644--- a/apps/desktop/src/pages/ScheduledPage.tsx+++ b/apps/desktop/src/pages/ScheduledPage.tsx@@ -8,6 +8,7 @@ import { ScheduledEditor, type ScheduledDraft } from "../features/scheduled/Scheimport { ScheduledTaskDetail } from "../features/scheduled/ScheduledTaskDetail";import { ScheduledTaskRail } from "../features/scheduled/ScheduledTaskRail";import { useScheduledWorkspace } from "../features/scheduled/use-scheduled-workspace";+import { rememberScheduledReturn } from "../features/scheduled/scheduled-return";import "../features/scheduled/scheduled-workspace.css";/**@@ -29,7 +30,17 @@ export function ScheduledPage() {const { tasks, projects, selectedTask, selectedTaskId, runs, latestRuns, selectedRunId, busy, loaded, error } =workspace;- const openSession = async (sessionId: string) => {+ // Remember where the reader came from: the conversation offers the way back,+ // and this page restores the same task and the same run.+ const openSession = async (sessionId: string, runId: string) => {+ if (selectedTask) {+ rememberScheduledReturn({+ taskId: selectedTask.id,+ taskTitle: selectedTask.title,+ runId,+ sessionId,+ });+ }await selectSession(sessionId);setPage("chat");};@@ -111,7 +122,7 @@ export function ScheduledPage() {now={now}locale={locale}onSelectRun={workspace.selectRun}- onOpenSession={(sessionId) => void openSession(sessionId)}+ onOpenSession={(sessionId, runId) => void openSession(sessionId, runId)}onRunNow={() => void workspace.runTaskNow(selectedTask.id)}onEdit={() => setEditor(selectedTask)}onToggleEnabled={() =>diff --git a/apps/desktop/src/styles/chrome.css b/apps/desktop/src/styles/chrome.cssindex a7ab01b14..08c40cdb2 100644--- a/apps/desktop/src/styles/chrome.css+++ b/apps/desktop/src/styles/chrome.css@@ -593,6 +593,45 @@line-height: var(--leading-compact);}+/*+ * Where a scheduled run's conversation was opened from: the session list keeps+ * automation transcripts out of the project groups, so this is the way back to+ * the task and the run the reader was reading. It sits in the title's own lane,+ * so a long task title truncates exactly as it did before.+ */+.conversation-topbar .ct-back {+ display: inline-flex;+ flex: 0 1 auto;+ min-width: 0;+ height: 24px;+ align-items: center;+ gap: 2px;+ border: none;+ border-radius: var(--radius-md);+ padding: 0 8px 0 4px;+ background: transparent;+ color: var(--ds-text-secondary);+ cursor: pointer;+ -webkit-app-region: no-drag;+ app-region: no-drag;+ transition: background var(--motion-duration-fast) var(--motion-ease-out),+ color var(--motion-duration-fast) var(--motion-ease-out);+}++.conversation-topbar .ct-back:hover {+ background: var(--ds-bg-hover);+ color: var(--ds-text-primary);+}++.conversation-topbar .ct-back-label {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: var(--text-sm);+ line-height: var(--leading-compact);+}+/* One geometry and one seat for every chrome icon control: the topbar's docktoggle, the viewport-fixed work-panel toggle, the preview/route-band laneactions, and the work-panel header's create and maximize controls. The seat isdiff --git a/apps/desktop/test/scheduled-return.test.mjs b/apps/desktop/test/scheduled-return.test.mjsnew file mode 100644index 000000000..2d4022709--- /dev/null+++ b/apps/desktop/test/scheduled-return.test.mjs@@ -0,0 +1,169 @@+import assert from "node:assert/strict";+import test from "node:test";+import { fileURLToPath } from "node:url";+import { readFile } from "node:fs/promises";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { createServer } from "vite";++const read = (path) => readFile(new URL(path, import.meta.url), "utf8");++const ORIGIN = {+ taskId: "task-a",+ taskTitle: "Nightly dependency check",+ runId: "run-completed",+ sessionId: "session-completed",+};++async function withVite(work) {+ const server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ esbuild: { jsx: "automatic" },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ try {+ return await work(server);+ } finally {+ await server.close();+ }+}++/**+ * Renders the topbar the way the shell does, through the real catalog and the+ * store's own initial state.+ */+async function renderTopbar(server, session, locale = "en") {+ const { ConversationTopbar } = await server.ssrLoadModule(+ "/src/components/ConversationTopbar.tsx",+ );+ const { useAppStore } = await server.ssrLoadModule("/src/stores/app-store.ts");+ Object.assign(useAppStore.getInitialState(), {+ activeSessionId: session.id,+ sessions: [session],+ workspace: { path: "/project", name: "Project" },+ });+ const i18n = createInstance();+ await i18n.init({ lng: locale, resources: { [locale]: { translation: catalogs[locale] } } });+ return renderToStaticMarkup(+ createElement(+ I18nextProvider,+ { i18n },+ createElement(ConversationTopbar, {+ sidebarCollapsed: false,+ workPanelOpen: false,+ onToggleSidebar() {},+ onNewTask() {},+ onOpenSearch() {},+ }),+ ),+ );+}++test("a scheduled run's conversation remembers the row it was opened from", async () => {+ await withVite(async (server) => {+ const returns = await server.ssrLoadModule("/src/features/scheduled/scheduled-return.ts");++ assert.equal(returns.peekScheduledReturn(), null, "nothing is remembered up front");+ assert.equal(returns.scheduledReturnFor("session-completed"), null);++ returns.rememberScheduledReturn(ORIGIN);+ assert.deepEqual(returns.peekScheduledReturn(), ORIGIN);+ assert.deepEqual(returns.peekScheduledReturn(), ORIGIN, "peeking never consumes the origin");++ assert.deepEqual(returns.scheduledReturnFor("session-completed"), ORIGIN);+ assert.equal(+ returns.scheduledReturnFor("session-unrelated"),+ null,+ "unrelated conversations never offer this task",+ );+ assert.equal(returns.scheduledReturnFor(null), null);+ assert.equal(returns.scheduledReturnFor(undefined), null);++ const back = [{ page: "chat" }, { page: "scheduled" }, { page: "chat" }];+ assert.equal(returns.scheduledReturnUsesHistory(back, 2), true, "the row behind is the route");+ assert.equal(returns.scheduledReturnUsesHistory(back, 1), false, "the route itself is not back");+ assert.equal(+ returns.scheduledReturnUsesHistory([{ page: "chat" }, { page: "chat" }], 1),+ false,+ "a conversation reached from elsewhere opens the route directly",+ );+ assert.equal(returns.scheduledReturnUsesHistory([], 0), false);+ assert.equal(returns.scheduledReturnUsesHistory(back, 3), false, "past the stack's end");+ });+});++test("the topbar offers the way back only for a scheduled run's conversation", async () => {+ await withVite(async (server) => {+ const returns = await server.ssrLoadModule("/src/features/scheduled/scheduled-return.ts");+ const automation = {+ id: "session-completed",+ title: "Nightly dependency check",+ scheduledRun: true,+ };++ returns.rememberScheduledReturn(ORIGIN);+ const withOrigin = await renderTopbar(server, automation);+ assert.match(withOrigin, /class="ct-back"/);+ assert.match(withOrigin, /data-nav="back-to-scheduled"/);+ assert.match(withOrigin, /<span class="ct-back-label">Scheduled<\/span>/);+ assert.match(withOrigin, /aria-label="Back to Scheduled"/);+ assert.match(+ withOrigin,+ /title="Back to Scheduled · Nightly dependency check"/,+ "hovering names the task the reader returns to",+ );++ returns.rememberScheduledReturn({ ...ORIGIN, sessionId: "session-other" });+ const unrelated = await renderTopbar(server, automation);+ const unrelatedRow = unrelated.match(/<button[^>]*ct-back[^>]*>/)?.[0] ?? "";+ assert.match(+ unrelatedRow,+ /title="Back to Scheduled"/,+ "without its own origin the row only names the destination",+ );+ assert.doesNotMatch(+ unrelatedRow,+ /Nightly dependency check/,+ "another conversation's task is never offered here",+ );++ const localized = await renderTopbar(server, automation, "zh-CN");+ assert.match(localized, /<span class="ct-back-label">定时任务<\/span>/);+ assert.match(localized, /aria-label="返回定时任务"/);++ const ordinary = await renderTopbar(server, { id: "session-plain", title: "Plain task" });+ assert.doesNotMatch(ordinary, /ct-back|back-to-scheduled/);+ });+});++test("the Scheduled route is the one that writes the return origin", async () => {+ const [pageSource, workspaceSource, topbarSource] = await Promise.all([+ read("../src/pages/ScheduledPage.tsx"),+ read("../src/features/scheduled/use-scheduled-workspace.ts"),+ read("../src/components/ConversationTopbar.tsx"),+ ]);++ assert.match(pageSource, /rememberScheduledReturn\(\{/);+ assert.match(pageSource, /taskTitle: selectedTask\.title/);+ assert.match(pageSource, /runId,/);+ 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,+ /resolveSelectedTaskId\(tasks, current, loaded\)/,+ "the restored task survives the first, still empty task list",+ );++ assert.match(topbarSource, /const scheduledSession = activeSession\?\.scheduledRun === true/);+ assert.match(topbarSource, /scheduledReturnUsesHistory\(navStack, navIndex\)/);+ assert.match(topbarSource, /navBack\(\);[\s\S]{0,80}else setPage\("scheduled"\)/);+});diff --git a/apps/desktop/test/scheduled-workspace.test.mjs b/apps/desktop/test/scheduled-workspace.test.mjsindex bdf1f22ec..dd022ad8b 100644--- a/apps/desktop/test/scheduled-workspace.test.mjs+++ b/apps/desktop/test/scheduled-workspace.test.mjs@@ -124,6 +124,27 @@ test("run helpers scope, order, and measure one task's history", async () => {});});+test("the workspace keeps exactly one task selected across a reload", async () => {+ await withVite(async (server) => {+ const runs = await server.ssrLoadModule("/src/features/scheduled/scheduled-runs.ts");++ assert.equal(+ runs.resolveSelectedTaskId([], "task-b", false),+ "task-b",+ "a task restored from a conversation outlives the first, empty read",+ );+ assert.equal(runs.resolveSelectedTaskId([TASK_A, TASK_B], "task-b", true), "task-b");+ assert.equal(+ runs.resolveSelectedTaskId([TASK_A, TASK_B], "task-deleted", true),+ "task-a",+ "a task that is gone falls back to the first one",+ );+ assert.equal(runs.resolveSelectedTaskId([TASK_A, TASK_B], null, true), "task-a");+ assert.equal(runs.resolveSelectedTaskId([], null, true), null);+ assert.equal(runs.resolveSelectedTaskId([], "task-b", true), null, "an empty list selects nothing");+ });+});+test("run formatting stays compact, localized, and bounded", async () => {await withVite(async (server) => {const format = await server.ssrLoadModule("/src/features/scheduled/scheduled-format.ts");@@ -205,6 +226,18 @@ test("the task page reads facts, history, and the selected run in place", asyncassert.match(html, /~/u, "the project path is shortened");assert.match(html, /Auto/, "the task's own permission mode is shown");assert.match(html, /Fixture provider \/ fixture/, "the model fact names the provider, not its id");+ assert.match(+ html,+ /New conversation per run/,+ "the task's conversation mode is part of the facts",+ );+ const reused = await render(+ server,+ "/src/features/scheduled/ScheduledTaskDetail.tsx",+ "ScheduledTaskDetail",+ { ...props, task: { ...TASK_A, sessionMode: "reuse" } },+ );+ assert.match(reused, /Reuse one conversation/, "a reuse task says so");const unnamedProvider = await render(server,"/src/features/scheduled/ScheduledTaskDetail.tsx",diff --git a/crates/host-core/src/rpc/scheduled_rpc.rs b/crates/host-core/src/rpc/scheduled_rpc.rsindex f40e9b38c..55ea9bd1d 100644--- a/crates/host-core/src/rpc/scheduled_rpc.rs+++ b/crates/host-core/src/rpc/scheduled_rpc.rs@@ -196,23 +196,43 @@ fn handle_with_workspace_policy(let uses_task_execution_settings = task.permission_mode.is_some()|| task.thinking_level.is_some()|| (task.provider_id.is_some() && task.model_id.is_some());- let session = if automatic || uses_task_execution_settings {- sessions::create_session_with_options(&st.db, options)+ // A `reuse` task continues its own previous conversation, but only+ // while that conversation still exists and still belongs to the same+ // project; a deleted one, or a re-pointed task, opens a fresh one.+ let target_project = options.project_path.clone();+ let reused = if task.session_mode == "reuse" {+ scheduled::reusable_session(&st.db, id, target_project.as_deref())+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?} else {- sessions::create_session(- &st.db,- options.title,- options.mode,- options.provider_id,- options.model_id,- options.project_path,- )- }- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;- let run_id = match scheduled::begin_run(&st.db, id, Some(&session.id)) {+ None+ };+ let starting_fresh = reused.is_none();+ let session_id = match reused {+ Some(session_id) => session_id,+ None => {+ let session = if automatic || uses_task_execution_settings {+ sessions::create_session_with_options(&st.db, options)+ } else {+ sessions::create_session(+ &st.db,+ options.title,+ options.mode,+ options.provider_id,+ options.model_id,+ options.project_path,+ )+ }+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ session.id+ }+ };+ let run_id = match scheduled::begin_run(&st.db, id, Some(&session_id)) {Ok(run_id) => run_id,Err(error) => {- let _ = sessions::delete_session(&st.db, &session.id);+ // Only a conversation this dispatch opened is cleaned up.+ if starting_fresh {+ let _ = sessions::delete_session(&st.db, &session_id);+ }return Err(rpc_err(1000, error.to_string(), "INTERNAL"));}};@@ -220,7 +240,7 @@ fn handle_with_workspace_policy(.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?.unwrap_or(task);Ok(json!({- "sessionId": session.id,+ "sessionId": session_id,"prompt": task.prompt,"task": task,"runId": run_id@@ -372,6 +392,73 @@ mod tests {);}+ /// A `reuse` task keeps one conversation; the default keeps one per run.+ #[tokio::test]+ async fn reuse_tasks_continue_one_conversation_and_per_run_tasks_do_not() {+ let dir = tempfile::tempdir().unwrap();+ let mut st = AppState::open(dir.path()).unwrap();+ st.handshook = true;+ let create = |mode: Option<&str>| {+ let mut params =+ json!({"title":"Nightly","prompt":"Summarize","cadence":"manual","schedule":null});+ if let Some(mode) = mode {+ params["sessionMode"] = json!(mode);+ }+ handle(&st, "scheduled.create", params).unwrap()["task"].clone()+ };+ let dispatch = |id: &str| handle(&st, "scheduled.run", json!({"id":id})).unwrap();+ let settle = |launch: &Value| {+ handle(+ &st,+ "scheduled.finishRun",+ json!({"runId":launch["runId"].as_str().unwrap(),"status":"completed"}),+ )+ .unwrap();+ };++ let per_run = create(None);+ assert_eq!(+ per_run["sessionMode"],+ json!("perRun"),+ "a task without the setting keeps the historical shape"+ );+ let per_run_id = per_run["id"].as_str().unwrap();+ let first = dispatch(per_run_id);+ settle(&first);+ let second = dispatch(per_run_id);+ settle(&second);+ assert_ne!(+ first["sessionId"], second["sessionId"],+ "a per-run task opens a conversation per run"+ );++ let reuse = create(Some("reuse"));+ assert_eq!(reuse["sessionMode"], json!("reuse"));+ let reuse_id = reuse["id"].as_str().unwrap();+ let first = dispatch(reuse_id);+ settle(&first);+ let second = dispatch(reuse_id);+ settle(&second);+ assert_eq!(+ first["sessionId"], second["sessionId"],+ "a reuse task continues the conversation its previous run used"+ );++ // Deleting that conversation starts a fresh one instead of failing.+ sessions::delete_session(&st.db, first["sessionId"].as_str().unwrap()).unwrap();+ let third = dispatch(reuse_id);+ settle(&third);+ assert_ne!(third["sessionId"], first["sessionId"]);++ let invalid = handle(+ &st,+ "scheduled.create",+ json!({"title":"Bad","prompt":"Summarize","cadence":"manual",+ "schedule":null,"sessionMode":"sometimes"}),+ );+ assert!(invalid.is_err(), "an unknown conversation mode is refused");+ }+#[tokio::test]async fn review_deleted_project_is_not_recreated_by_automatic_task() {use std::sync::Arc;diff --git a/crates/host-core/src/scheduled.rs b/crates/host-core/src/scheduled.rsindex 6e92978e0..1159568aa 100644--- a/crates/host-core/src/scheduled.rs+++ b/crates/host-core/src/scheduled.rs@@ -40,6 +40,9 @@ pub struct ScheduledTask {pub model_id: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub thinking_level: Option<String>,+ /// Whether each run continues one conversation or opens its own.+ #[serde(default = "default_session_mode")]+ pub session_mode: String,/// Presence distinguishes a saved project (including null) from legacy tasks.#[serde(skip)]pub(crate) workspace_bound: bool,@@ -48,6 +51,10 @@ pub struct ScheduledTask {pub(crate) calendar_configured: bool,}+fn default_session_mode() -> String {+ "perRun".to_string()+}+#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct TaskRun {@@ -225,6 +232,14 @@ fn task_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<ScheduledTask> {.and_then(Value::as_str).filter(|level| sessions::is_valid_thinking_level(level)).map(str::to_string),+ // Absent or unrecognized config keeps the historical shape: one+ // conversation per run.+ session_mode: config+ .get("sessionMode")+ .and_then(Value::as_str)+ .filter(|mode| automation::TASK_SESSION_MODES.contains(mode))+ .unwrap_or("perRun")+ .to_string(),})}@@ -435,6 +450,30 @@ pub fn begin_run(db: &Database, task_id: &str, session_id: Option<&str>) -> ResuOk(run_id)}+/// The conversation a `reuse` task should continue: the session its newest run+/// used, while that session still exists and still belongs to the same project.+/// A deleted conversation — or a task re-pointed at another folder — starts a+/// new one instead of replaying into the wrong workspace.+pub fn reusable_session(+ db: &Database,+ task_id: &str,+ project_path: Option<&str>,+) -> Result<Option<String>> {+ let found: Option<String> = db+ .conn()+ .prepare_cached(+ "SELECT r.session_id FROM task_runs r+ JOIN sessions s ON s.id = r.session_id+ LEFT JOIN projects p ON p.id = s.project_id+ WHERE r.task_id = ?1 AND r.session_id IS NOT NULL AND s.deleted_at IS NULL+ AND ((?2 IS NULL AND s.project_id IS NULL) OR p.path = ?2)+ ORDER BY r.started_at DESC LIMIT 1",+ )?+ .query_row(params![task_id, project_path], |row| row.get(0))+ .optional()?;+ Ok(found)+}+pub fn finish_run(db: &Database,run_id: &str,diff --git a/crates/host-core/src/scheduled/automation.rs b/crates/host-core/src/scheduled/automation.rsindex f419f8cb3..ba0285937 100644--- a/crates/host-core/src/scheduled/automation.rs+++ b/crates/host-core/src/scheduled/automation.rs@@ -7,6 +7,10 @@ use crate::db::{now_ms, Database};const TASK_PERMISSION_MODES: [&str; 3] = ["ask", "accept-edits", "auto"];+/// Whether a run opens its own conversation or continues the task's previous+/// one. `perRun` is the historical behavior.+pub const TASK_SESSION_MODES: [&str; 2] = ["perRun", "reuse"];+pub fn validate_execution_input(input: &Value) -> Result<()> {if let Some(value) = input.get("thinkingLevel") {if !value.is_null()@@ -40,6 +44,15 @@ pub fn validate_execution_input(input: &Value) -> Result<()> {bail!("providerId and modelId must be nonempty strings together, or both null");}}+ if let Some(value) = input.get("sessionMode") {+ if !value.is_null()+ && !value+ .as_str()+ .is_some_and(|mode| TASK_SESSION_MODES.contains(&mode))+ {+ bail!("sessionMode must be perRun, reuse, or null");+ }+ }Ok(())}@@ -70,6 +83,13 @@ pub(crate) fn configure_execution(config: &mut Value, input: &Value) {object.insert("modelId".into(), input["modelId"].clone());}}+ if let Some(value) = input.get("sessionMode") {+ if value.is_null() {+ object.remove("sessionMode");+ } else if let Some(mode) = value.as_str() {+ object.insert("sessionMode".into(), json!(mode));+ }+ }}pub fn configure(config: &mut Value, input: &Value, cadence: &str, now: i64) -> Result<()> {diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 4ae94d59a..85bba6989 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1134,7 +1134,8 @@ SessionList and session search hide the transcript while it has a run, anddeleting the task returns it to the ordinary lists instead of leaving itunreachable (issue #1291).The existing JSON extension stores `schedule: {hour, minute, weekday}`,-`nextRunAt` (epoch milliseconds) and `workspacePath` for desktop automations.+`nextRunAt` (epoch milliseconds), `workspacePath`, and `sessionMode` (`perRun` or+`reuse`, absent means `perRun`) for desktop automations.Optional `weekdays` stores 1–7 unique integers in 0–6, overriding legacy`weekday` for weekly schedules. Missing `weekdays` preserves the single-daybehavior. Invalid or empty selections are rejected before mutation. No tablediff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.mdindex 3030b352f..413348faa 100644--- a/docs/spec/04-ux/01-ui-ia.md+++ b/docs/spec/04-ux/01-ui-ia.md@@ -245,7 +245,7 @@ destination, chat as the home surface, tools and permissions inline.### 3.3 ScheduledA task column beside the selected task's page, with an explicit create/edit form, a cadence dropdown, time,-next occurrence, saved project, per-task permission/model selection, pause/resume and delete confirmation. Hourly+next occurrence, saved project, per-task permission/model selection, a per-task conversation mode (a new conversation per run, or one conversation every run continues), pause/resume and delete confirmation. Hourlyschedules repeat at one-hour intervals without a time selector. Daily schedulesuse a themed time-period dropdown: Morning 09:00, Afternoon 14:00, Evening19:00, Night 22:00. The form does not expose hour/minute editing. AI tools may@@ -262,7 +262,10 @@ its own run history newest first (status, start time, duration, stable errorcode), and the transcript of the selected run read in the page through a boundedread. A run's transcript belongs to this route: the SessionList and globalsession search never list it, and Open conversation is the explicit action that-carries it into the chat route. The footer clock and global search open+carries it into the chat route, and the chat top bar then offers that+conversation's own way back: the row names the task it belongs to, and returning+restores the same task and the same run, reusing the navigation history when+this route is directly behind it. The footer clock and global search openthis route. Run now dispatches in the background, selects the run it admitted,and leaves the reader on this page. Automatic runs never steal foregroundfocus. See [desktop automations](../../adr/scheduled-desktop-automations.md).diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 0dff72b7f..87c05be16 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -4134,7 +4134,14 @@ TASKS (2) │ Nightly dependency check [Enabled] [Run now]- The instruction is disclosed on demand and starts collapsed.- Run now dispatches in the background, selects the run it admitted, and keepsthe reader on the route.-- Open conversation is the only action that leaves for the chat route.+- The conversation mode decides who owns a run's transcript: `perRun` opens a+ conversation for each run, and `reuse` continues the task's previous one while+ it still exists and still belongs to the same project.+- Open conversation is the only action that leaves for the chat route. A+ scheduled run's conversation then shows a back row in the chat top bar,+ labelled with the route and, when the row's own origin is known, the task it+ belongs to; returning restores that task and that run, and steps back through+ the navigation history when this route is directly behind the conversation.- Above 900px the task column sticks below the titlebar band; below it thecolumn stacks above the page.- Motion: colour and chevron transitions only, disabled underdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 683144d89..0d3c9b3a7 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -416,7 +416,8 @@arrows, Home/End, Enter, Escape/Tab and outside dismissal; select hourly without timefields and verify its first occurrence is one hour away; pause/resume; Run nowand read the admitted run's transcript inside the task page; open the result- conversation from that page; configure a daily task for the next real minute;+ conversation from that page and verify its top bar offers the way back to the+ scheduled task; return and confirm the same task and run are still selected;observe automatic completion; delete the settled task. In a normal Agentconversation, use model tool calls to discover, create, list, update to 15:30and delete a task. Verify the custom time appears in the form and survives@@ -430,7 +431,8 @@not dispatch, both execution paths reach the real Agent sidecar, the task's ownhistory lists each run with its status and duration and Open conversationreaches the persisted transcript while the SessionList and session search never- list it, and automatic execution does not require a+ list it, that conversation's top bar returns to the same task and run, and+ automatic execution does not require arenderer prompt. Host tests additionally prove duplicate admission rejection,stale/missed occurrence handling, invalid input rejection and recovery.- **Specs:** 04-ux/01-ui-ia §3.3; 04-ux/08-component-spec §6, §20A;diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex fb7f7bf76..6b568b7bb 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -915,7 +915,7 @@ CREATE INDEX idx_task_runs ON task_runs(task_id, started_at DESC);生成会话的运行通过 `session_id` 免费获取其转录本。该转录本通过针对 `task_runs` 的 `EXISTS` 判断被识别为自动化产出,每个会话摘要与搜索命中都以 `scheduledRun` 返回这一归属。归属在读取时派生、不写入会话行:因此在该会话仍属于某次运行时,会话列表与会话搜索会隐藏它;删除任务后它会回到普通列表,而不会变得无法访问(issue #1291)。`config_json` 保存 `schedule: {hour, minute, weekday}`、毫秒时间戳 `nextRunAt`、-`workspacePath`,以及可选的任务级 `permissionMode` 与成对的 `providerId`/`modelId`。+`workspacePath`、会话模式 `sessionMode`(`perRun` 或 `reuse`,缺失按 `perRun`),以及可选的任务级 `permissionMode` 与成对的 `providerId`/`modelId`。这些新增字段无需物理表迁移。缺少模型字段时仍在运行时读取应用默认值;缺少权限字段时,自动运行继续使用 Ask,立即运行继续继承全局权限。每天、每周按宿主本地时区计算。每小时采用 `nextRunAt = now + 3_600_000`,忽略日历时间字段。可选 `weekdays` 保存 1–7 个不重复的 0–6 整数,覆盖每周的旧 `weekday`;diff --git a/docs/zh-CN/spec/04-ux/01-ui-ia.md b/docs/zh-CN/spec/04-ux/01-ui-ia.mdindex d0444c9bc..09a8609fc 100644--- a/docs/zh-CN/spec/04-ux/01-ui-ia.md+++ b/docs/zh-CN/spec/04-ux/01-ui-ia.md@@ -202,13 +202,13 @@焦点。### 3. 3 定时任务-任务列与所选任务的页面并排展示,支持创建、编辑、暂停、启用和确认删除。表单可为每个任务单独选择项目、权限和模型。周期保留下拉选择,并与时分统一为自定义主题菜单。每小时按一小时间隔执行,不显示时间选择;保存、启用、启动或上次自动准入后重新计时。+任务列与所选任务的页面并排展示,支持创建、编辑、暂停、启用和确认删除。表单可为每个任务单独选择项目、权限、模型与会话模式(每次新开会话或复用同一会话)。周期保留下拉选择,并与时分统一为自定义主题菜单。每小时按一小时间隔执行,不显示时间选择;保存、启用、启动或上次自动准入后重新计时。每天通过下拉框选择上午 09:00、下午 14:00、晚上 19:00、夜间 22:00;界面不提供时分编辑,AI 可设置具体时间,非预设值显示为自定义时间,其他字段的编辑不得覆盖它。每周通过独立下拉面板多选周一至周日,右侧显示选中标记,不提供快捷组合。至少选择一天才能保存。支持方向键、Home/End、Enter/Space选择及 Escape/外部点击关闭,选项具有选中状态语义。每天、每周按电脑本地时区计算并显示下次执行时间。-任务列显示每个任务的周期与时间、最近一次运行的结果与耗时,以及暂停或运行中状态;任务页面显示该任务的上次运行、下次执行、项目、权限与模型,指令默认折叠,运行记录只列本任务的运行(状态、开始时间、耗时与稳定错误码,最新在前),并在页内按有界读取展示所选运行的转写。运行的转写属于本页面:会话列表与全局搜索不再列出它,只有“打开会话”这个显式动作才会把它带入对话页。侧边栏时钟与全局搜索均可进入。立即运行在后台执行并选中刚准入的那次运行,读者仍停留在本页。+任务列显示每个任务的周期与时间、最近一次运行的结果与耗时,以及暂停或运行中状态;任务页面显示该任务的上次运行、下次执行、项目、权限与模型,指令默认折叠,运行记录只列本任务的运行(状态、开始时间、耗时与稳定错误码,最新在前),并在页内按有界读取展示所选运行的转写。运行的转写属于本页面:会话列表与全局搜索不再列出它,只有“打开会话”这个显式动作才会把它带入对话页,对话顶部栏随后为这段会话提供返回入口(入口标注它所属的任务;返回后仍选中同一个任务与同一次运行,若本页紧邻其后则直接复用导航历史)。侧边栏时钟与全局搜索均可进入。立即运行在后台执行并选中刚准入的那次运行,读者仍停留在本页。应用必须保持运行。每 30 秒检查一次,超过 90 秒的错过时段与重叠运行被跳过;重启只安排未来时段。旧任务需明确保存周期后才自动执行。新任务保存所选项目、Ask 权限和当前默认 provider/model;这些值只属于当前任务。任务文本标为“指令”,项目、权限和模型选择器嵌在指令框底部,并复用主 Composer 的容器、芯片和锚定菜单样式。两处直接共用权限选择组件和支持搜索、服务商分组、能力标记的模型列表。任务的模型按钮只显示模型名或别名,不拼接服务商名称;选择结果只更新任务草稿,不更改当前对话或应用默认设置。指令输入区域使用独立圆角边框及与底栏不同的底色,不显示原生缩放手柄,长文本在输入区内滚动。缺少模型字段的旧任务继续跟随应用默认值,已保存但不可用的模型保留显示且不会被静默替换。选择 Auto 时明确提示受限操作可能无需询问。没有显式选择时,首次设置仍保存当前项目,diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 3a59e55fd..3007d8066 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -2901,7 +2901,8 @@ Sidebar footer Popover (360px max)并把运行内容卡片切到该运行。- 指令按需展开,默认折叠。- 立即运行在后台执行,选中刚准入的那次运行,读者仍停留在本页面。-- 「打开会话」是唯一离开本页面进入对话页的动作。+- 会话模式决定运行转写的归属:`perRun` 为每次运行新开一段会话;`reuse` 在该任务上一次会话仍存在、且仍属于同一项目时继续使用它。+- 「打开会话」是唯一离开本页面进入对话页的动作。定时任务的会话随后在对话顶部栏显示返回行,行上标注目标页面(已知来源时还标注所属任务);返回后恢复同一个任务与同一次运行,若本页紧邻该会话之后则沿导航历史后退。- 宽度大于 900px 时任务列吸附在标题栏下方;更窄时任务列堆叠在页面上方。- 动画仅使用颜色与箭头过渡,并在 `prefers-reduced-motion` 下关闭,包括运行中圆点的脉冲。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 8b65dea7c..81256e94d 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@@ -8714,14 +8714,13 @@ the latest destination. These assertions measure work counts, not device FPS.- **前提:** 独立桌面配置、构建后的任务候选版本、本地 SSE 模拟模型;不使用真实服务凭据或付费 API。-- **步骤:** 点击页脚时钟;创建每天上午 09:00 的任务;选择另一个已保存项目、Auto 权限和非默认模型;编辑名称;暂停/启用;立即运行并在任务页面内读取刚准入运行的转写;从该页面打开结果会话;验证周期/四个时段主题下拉菜单、星期多选及选中标记、保存回显、空选择与固定时间;- 打开结果会话;验证周期/四个时段主题下拉菜单、星期多选及选中标记、保存回显、空选择与固定时间;+- **步骤:** 点击页脚时钟;创建每天上午 09:00 的任务;选择另一个已保存项目、Auto 权限和非默认模型;编辑名称;暂停/启用;立即运行并在任务页面内读取刚准入运行的转写;从该页面打开结果会话,确认顶部栏提供返回定时任务的入口,返回后仍选中同一个任务与同一次运行;验证周期/四个时段主题下拉菜单、星期多选及选中标记、保存回显、空选择与固定时间;验证方向键、Home/End、Enter、Escape/Tab 和外部点击关闭;验证每小时无时间输入且首次等待一小时;设置每天任务在下一个真实分钟执行;观察自动完成;删除已结束的任务。普通 Agent 对话经模型工具调用发现、创建、查询、修改任务到 15:30,再删除;验证页面显示具体时间,改名保存不覆盖。模型为本地确定性夹具。- **预期:** 项目、权限和精确 provider/model 只保存在该任务,重新打开仍显示相同值并实际传到 sidecar,其他任务不受影响;项目、权限和模型控件保持嵌在“指令”框的 Composer 风格底栏中,窄窗口也不产生横向溢出;缺少新增字段的旧记录保持原默认行为。配置持久化并显示下次时间;暂停后不触发;手动与自动入口均调用真实- Agent sidecar;本任务的运行记录列出每次运行的状态与耗时,「打开会话」到达持久化会话,而会话列表与会话搜索不会列出它;自动执行不依赖渲染器发送提示词。+ Agent sidecar;本任务的运行记录列出每次运行的状态与耗时,「打开会话」到达持久化会话,而会话列表与会话搜索不会列出它,该会话顶部栏可返回同一个任务与同一次运行;自动执行不依赖渲染器发送提示词。宿主测试补充验证重复准入、错过时段、无效输入和重启恢复。- **规格:** 04-ux/01-ui-ia §3.3;04-ux/08-component-spec §6、§20A;03-runtime/04-data-storage §4.11;ADR scheduled-desktop-automations;ADR 0305。diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 1447077e3..1046527ba 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -145,6 +145,9 @@ export const de = {"newChat": "Neuer Chat","conversation": "Konversation","toggleSidebar": "Seitenleiste umschalten",+ "backToScheduled": "Geplant",+ "backToScheduledAction": "Zurück zu den geplanten Aufgaben",+ "backToScheduledTask": "Zurück zu den geplanten Aufgaben · {{title}}","toggleWorkPanel": "Seitenpanel umschalten","sessions": "Sitzungen","collapseSidebar": "Seitenleiste einklappen",@@ -1759,6 +1762,10 @@ sklm: {"detailProject": "Projekt","detailPermission": "Berechtigung","detailModel": "Modell",+ "sessionMode": "Unterhaltung",+ "sessionModePerRun": "Neue Unterhaltung pro Ausführung",+ "sessionModeReuse": "Eine Unterhaltung wiederverwenden",+ "sessionModeHint": "Jede Ausführung schreibt in dieselbe Unterhaltung, sodass die Aufgabe einen fortlaufenden Verlauf behält.","neverRun": "Noch nicht ausgeführt","selectTask": "Wähle eine Aufgabe, um ihre Ausführungen zu sehen.","emptyRuns": "Noch keine Ausführungen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 95fc6af31..67dd5610c 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -152,6 +152,9 @@ export const en = {newChat: "New chat",conversation: "Conversation",toggleSidebar: "Toggle sidebar",+ backToScheduled: "Scheduled",+ backToScheduledAction: "Back to Scheduled",+ backToScheduledTask: "Back to Scheduled · {{title}}",toggleWorkPanel: "Toggle side panel",sessions: "Sessions",collapseSidebar: "Collapse sidebar",@@ -1782,6 +1785,10 @@ sklm: {detailProject: "Project",detailPermission: "Permission",detailModel: "Model",+ sessionMode: "Conversation",+ sessionModePerRun: "New conversation per run",+ sessionModeReuse: "Reuse one conversation",+ sessionModeHint: "Every run writes into the same conversation, so the task keeps one continuous record.",neverRun: "Not run yet",selectTask: "Select a task to see its runs.",emptyRuns: "No runs yet",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 0163966c7..57e17e322 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -145,6 +145,9 @@ export const es = {"newChat": "Nuevo chat","conversation": "Conversación","toggleSidebar": "Alternar barra lateral",+ "backToScheduled": "Programado",+ "backToScheduledAction": "Volver a lo programado",+ "backToScheduledTask": "Volver a lo programado · {{title}}","toggleWorkPanel": "Alternar panel lateral","sessions": "Sesiones","collapseSidebar": "Contraer barra lateral",@@ -1759,6 +1762,10 @@ sklm: {"detailProject": "Proyecto","detailPermission": "Permiso","detailModel": "Modelo",+ "sessionMode": "Conversación",+ "sessionModePerRun": "Nueva conversación por ejecución",+ "sessionModeReuse": "Reutilizar una conversación",+ "sessionModeHint": "Cada ejecución escribe en la misma conversación, así la tarea mantiene un solo hilo continuo.","neverRun": "Aún no se ha ejecutado","selectTask": "Selecciona una tarea para ver sus ejecuciones.","emptyRuns": "Aún no hay ejecuciones",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 6495a19d4..417cc1c87 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -145,6 +145,9 @@ export const fr = {"newChat": "Nouvelle discussion","conversation": "Conversation","toggleSidebar": "Basculer la barre latérale",+ "backToScheduled": "Planifié",+ "backToScheduledAction": "Revenir aux tâches planifiées",+ "backToScheduledTask": "Revenir aux tâches planifiées · {{title}}","toggleWorkPanel": "Basculer le panneau latéral","sessions": "Sessions","collapseSidebar": "Réduire la barre latérale",@@ -1759,6 +1762,10 @@ sklm: {"detailProject": "Projet","detailPermission": "Autorisation","detailModel": "Modèle",+ "sessionMode": "Conversation",+ "sessionModePerRun": "Nouvelle conversation à chaque exécution",+ "sessionModeReuse": "Réutiliser une conversation",+ "sessionModeHint": "Chaque exécution écrit dans la même conversation : la tâche garde un fil continu.","neverRun": "Pas encore exécuté","selectTask": "Sélectionnez une tâche pour voir ses exécutions.","emptyRuns": "Aucune exécution",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 3e9de3db3..67fb7236c 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -154,6 +154,9 @@ export const ko = {newChat: "새 채팅",conversation: "대화",toggleSidebar: "사이드바 전환",+ backToScheduled: "예약됨",+ backToScheduledAction: "예약됨으로 돌아가기",+ backToScheduledTask: "예약됨으로 돌아가기 · {{title}}",toggleWorkPanel: "사이드 패널 전환",sessions: "세션",collapseSidebar: "사이드바 접기",@@ -1774,6 +1777,10 @@ sklm: {detailProject: "프로젝트",detailPermission: "권한",detailModel: "모델",+ sessionMode: "대화",+ sessionModePerRun: "실행마다 새 대화",+ sessionModeReuse: "같은 대화 재사용",+ sessionModeHint: "모든 실행이 같은 대화에 기록되어 작업은 하나의 이어지는 기록을 유지합니다.",neverRun: "아직 실행되지 않음",selectTask: "실행 기록을 보려면 작업을 선택하세요.",emptyRuns: "실행 기록 없음",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex d4e8c0e76..38092f128 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -144,6 +144,9 @@ export const ptBR = {newChat: "Nova conversa",conversation: "Conversa",toggleSidebar: "Alternar barra lateral",+ backToScheduled: "Agendadas",+ backToScheduledAction: "Voltar para tarefas agendadas",+ backToScheduledTask: "Voltar para tarefas agendadas · {{title}}",toggleWorkPanel: "Alternar painel lateral",sessions: "Sessões",collapseSidebar: "Recolher barra lateral",@@ -1714,6 +1717,10 @@ export const ptBR = {detailProject: "Projeto",detailPermission: "Permissão",detailModel: "Modelo",+ sessionMode: "Conversa",+ sessionModePerRun: "Nova conversa por execução",+ sessionModeReuse: "Reutilizar uma conversa",+ sessionModeHint: "Cada execução grava na mesma conversa, então a tarefa mantém um único histórico contínuo.",neverRun: "Ainda não executado",selectTask: "Selecione uma tarefa para ver as execuções dela.",emptyRuns: "Nenhuma execução ainda",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 8fdb63a99..4222761a0 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -154,6 +154,9 @@ export const tr = {newChat: "Yeni sohbet",conversation: "Sohbet",toggleSidebar: "Kenar çubuğunu aç/kapat",+ backToScheduled: "Zamanlanmış",+ backToScheduledAction: "Zamanlanmış görevlere dön",+ backToScheduledTask: "Zamanlanmış görevlere dön · {{title}}",toggleWorkPanel: "Yan paneli aç/kapat",sessions: "Oturumlar",collapseSidebar: "Kenar çubuğunu daralt",@@ -1764,6 +1767,10 @@ sklm: {detailProject: "Proje",detailPermission: "İzin",detailModel: "Model",+ sessionMode: "Konuşma",+ sessionModePerRun: "Her çalıştırmada yeni konuşma",+ sessionModeReuse: "Aynı konuşmayı yeniden kullan",+ sessionModeHint: "Her çalıştırma aynı konuşmaya yazar, böylece görev tek bir sürekli kayıt tutar.",neverRun: "Henüz çalıştırılmadı",selectTask: "Çalıştırmalarını görmek için bir görev seçin.",emptyRuns: "Henüz çalıştırılmadı",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex fc93fab24..aee084c71 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -147,6 +147,9 @@ export const zhCN = {newChat: "新对话",conversation: "对话",toggleSidebar: "切换侧边栏",+ backToScheduled: "定时任务",+ backToScheduledAction: "返回定时任务",+ backToScheduledTask: "返回定时任务 · {{title}}",toggleWorkPanel: "切换侧边面板",sessions: "会话",collapseSidebar: "收起侧边栏",@@ -1745,6 +1748,10 @@ sklm: {detailProject: "项目",detailPermission: "权限",detailModel: "模型",+ sessionMode: "会话",+ sessionModePerRun: "每次新开会话",+ sessionModeReuse: "复用同一会话",+ sessionModeHint: "每次运行都会写入同一段会话,因此该任务只保留一条持续增长的记录。",neverRun: "尚未运行",selectTask: "选择一个任务以查看它的运行记录。",emptyRuns: "暂无运行记录",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex d8e11b609..f72b6521d 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -147,6 +147,9 @@ export const zhTW = {newChat: "新對話",conversation: "對話",toggleSidebar: "切換側邊欄",+ backToScheduled: "已安排",+ backToScheduledAction: "返回已安排",+ backToScheduledTask: "返回已安排 · {{title}}",toggleWorkPanel: "切換側邊面板",sessions: "會話",collapseSidebar: "收起側邊欄",@@ -1745,6 +1748,10 @@ sklm: {detailProject: "專案",detailPermission: "權限",detailModel: "模型",+ sessionMode: "對話",+ sessionModePerRun: "每次執行另開對話",+ sessionModeReuse: "重複使用同一對話",+ sessionModeHint: "每次執行都會寫入同一段對話,因此此任務只保留一條持續累積的紀錄。",neverRun: "尚未執行",selectTask: "選擇一個任務以查看它的執行記錄。",emptyRuns: "尚無執行記錄",diff --git a/packages/shared/src/types/platform.ts b/packages/shared/src/types/platform.tsindex 81e392782..650676010 100644--- a/packages/shared/src/types/platform.ts+++ b/packages/shared/src/types/platform.ts@@ -107,6 +107,9 @@ export type ScheduledTaskRun = {errorCode: string | null; startedAt: string; endedAt: string | null;};+/** How a scheduled run relates to the task's conversations. */+export type ScheduledSessionMode = "perRun" | "reuse";+export type ScheduledTask = {id: string;title: string;@@ -123,6 +126,11 @@ export type ScheduledTask = {/** Explicit task-owned execution settings. Missing fields preserve legacy behavior. */permissionMode?: GlobalPermissionMode;thinkingLevel?: SessionThinkingLevel;+ /**+ * Whether each run opens its own conversation (`perRun`, the default) or+ * continues the conversation its previous run used (`reuse`).+ */+ sessionMode?: ScheduledSessionMode;providerId?: string;modelId?: string;};