Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(scheduled): reuse Composer execution settings

Jack62ac0871a60d
diff --git a/.github/pr-assets/scheduled-execution-settings/01-before.png b/.github/pr-assets/scheduled-execution-settings/01-before.png
new file mode 100644
index 000000000..99129974f
Binary files /dev/null and b/.github/pr-assets/scheduled-execution-settings/01-before.png differ
diff --git a/.github/pr-assets/scheduled-execution-settings/02-after.png b/.github/pr-assets/scheduled-execution-settings/02-after.png
new file mode 100644
index 000000000..82ca3f040
Binary files /dev/null and b/.github/pr-assets/scheduled-execution-settings/02-after.png differ
diff --git a/.github/pr-assets/scheduled-execution-settings/03-model-menu.png b/.github/pr-assets/scheduled-execution-settings/03-model-menu.png
new file mode 100644
index 000000000..b7b9ff653
Binary files /dev/null and b/.github/pr-assets/scheduled-execution-settings/03-model-menu.png differ
diff --git a/.github/pr-assets/scheduled-execution-settings/04-narrow.png b/.github/pr-assets/scheduled-execution-settings/04-narrow.png
new file mode 100644
index 000000000..209e04dc7
Binary files /dev/null and b/.github/pr-assets/scheduled-execution-settings/04-narrow.png differ
diff --git a/.github/pr-assets/scheduled-execution-settings/05-dark.png b/.github/pr-assets/scheduled-execution-settings/05-dark.png
new file mode 100644
index 000000000..317e1feb9
Binary files /dev/null and b/.github/pr-assets/scheduled-execution-settings/05-dark.png differ
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index c09ed9898..153264d16 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -384,6 +384,7 @@ export function Composer({
? composerModelDisplayName(provider, modelId, selectedModel?.displayName)
: selectedModel?.displayName || modelId || t("chat.model");
const modelMenu = useComposerModelMenu({
+ configureActiveSession,
mode,
activeSessionId,
provider,
diff --git a/apps/desktop/src/components/settings/SettingsMenuSelect.tsx b/apps/desktop/src/components/settings/SettingsMenuSelect.tsx
index 4c44451c2..6da9270b9 100644
--- a/apps/desktop/src/components/settings/SettingsMenuSelect.tsx
+++ b/apps/desktop/src/components/settings/SettingsMenuSelect.tsx
@@ -14,7 +14,12 @@
* catalog here is the host command-shell list — so the menu opens on the
* current option and keyboard users move with arrows alone.
*/
-import { useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
+import {
+ useRef,
+ useState,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type ReactNode,
+} from "react";
import { cx } from "../ui";
import { IconCheck, IconChevronDown } from "../icons";
import { AnchoredMenu } from "./AnchoredMenu";
@@ -35,6 +40,8 @@ export function SettingsMenuSelect({
busy = false,
fullWidth = false,
className,
+ triggerClassName,
+ leading,
}: {
value: string;
options: MenuSelectOption[];
@@ -47,6 +54,10 @@ export function SettingsMenuSelect({
/** Stretch across a form field. Compact settings rows leave this off. */
fullWidth?: boolean;
className?: string;
+ /** Optional surface-specific styling while retaining the shared menu behavior. */
+ triggerClassName?: string;
+ /** Optional icon or marker shown before the selected value. */
+ leading?: ReactNode;
}) {
const [open, setOpen] = useState(false);
const [activeId, setActiveId] = useState(value);
@@ -99,7 +110,7 @@ export function SettingsMenuSelect({
<button
ref={ref}
type="button"
- className="settings-menu-select-trigger"
+ className={cx("settings-menu-select-trigger", triggerClassName)}
aria-haspopup="listbox"
aria-expanded={open}
aria-label={label}
@@ -109,6 +120,11 @@ export function SettingsMenuSelect({
setOpen((current) => !current);
}}
>
+ {leading ? (
+ <span className="settings-menu-select-trigger-leading" aria-hidden="true">
+ {leading}
+ </span>
+ ) : null}
<span className="settings-menu-select-trigger-label">
{current?.label ?? value}
</span>
diff --git a/apps/desktop/src/features/chat/composer/ComposerModelList.tsx b/apps/desktop/src/features/chat/composer/ComposerModelList.tsx
new file mode 100644
index 000000000..73cafc366
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/ComposerModelList.tsx
@@ -0,0 +1,107 @@
+import type { RefObject } from "react";
+import type { TFunction } from "i18next";
+import { formatTokenCount, modelIdsMatch, type ModelInfo, type ProviderPublic } from "@pi-desktop/shared";
+import { IconCheck, IconSearch } from "../../../components/icons";
+import { composerModelBadges } from "../../../lib/composer-models";
+
+export type ComposerModelGroup = {
+ provider: ProviderPublic;
+ providerDisplayName: string;
+ models: ModelInfo[];
+};
+
+/** Shared model list. Selection is owned by the caller, never by this view. */
+export function ComposerModelList({
+ t, query, setQuery, modelSearchRef, modelListRef, modelGroups,
+ modelHighlight, setModelHighlight, selectedProviderId, selectedModelId, selectModel,
+}: {
+ t: TFunction;
+ query: string;
+ setQuery: (query: string) => void;
+ modelSearchRef: RefObject<HTMLInputElement | null>;
+ modelListRef: RefObject<HTMLDivElement | null>;
+ modelGroups: ComposerModelGroup[];
+ modelHighlight: number;
+ setModelHighlight: (index: number) => void;
+ selectedProviderId?: string;
+ selectedModelId?: string;
+ selectModel: (provider: ProviderPublic, modelId: string) => void | Promise<void>;
+}) {
+ const flatModels = modelGroups.flatMap(group => group.models);
+ return <>
+ <label className="composer-model-search">
+ <IconSearch size={13} aria-hidden="true" />
+ <span className="sr-only">{t("chat.searchModels")}</span>
+ <input
+ ref={modelSearchRef}
+ type="text"
+ value={query}
+ placeholder={t("chat.searchModels")}
+ aria-label={t("chat.searchModels")}
+ spellCheck={false}
+ autoCorrect="off"
+ autoCapitalize="off"
+ onChange={(event) => setQuery(event.target.value)}
+ />
+ </label>
+ <div className="composer-model-list" ref={modelListRef}>
+ {(() => {
+ let flatIndex = 0;
+ return modelGroups.map((group) => (
+ <div
+ key={group.provider.id}
+ className="composer-model-group"
+ role="group"
+ aria-label={group.providerDisplayName}
+ >
+ <div className="composer-model-group-label">{group.providerDisplayName}</div>
+ {group.models.map((model) => {
+ const index = flatIndex++;
+ const active =
+ selectedProviderId === group.provider.id &&
+ modelIdsMatch(selectedModelId ?? "", model.modelId);
+ const optionTitle = model.displayName || model.modelId;
+ return (
+ <button
+ key={`${group.provider.id}:${model.modelId}`}
+ type="button"
+ data-model-index={index}
+ title={optionTitle}
+ className={`composer-plus-item composer-model-option ${active ? "active" : ""} ${modelHighlight === index ? "kb-active" : ""}`}
+ role="menuitemradio"
+ aria-checked={active}
+ onMouseMove={() => setModelHighlight(index)}
+ onClick={() => void selectModel(group.provider, model.modelId)}
+ >
+ <span className="composer-model-option-main">
+ <span className="truncate">{optionTitle}</span>
+ <span className="composer-model-option-meta">
+ {composerModelBadges(model, group.provider).map((badge) => (
+ <span
+ key={badge}
+ className="composer-model-option-badge"
+ title={t(badge === "reasoning" ? "chat.modelBadgeReasoning" : "chat.modelBadgeVision")}
+ >
+ {t(badge === "reasoning" ? "chat.modelBadgeReasoning" : "chat.modelBadgeVision")}
+ </span>
+ ))}
+ {model.contextWindow ? (
+ <span className="composer-model-option-ctx">
+ {formatTokenCount(model.contextWindow)}
+ </span>
+ ) : null}
+ </span>
+ </span>
+ {active ? <IconCheck size={14} className="composer-model-check" aria-hidden="true" /> : null}
+ </button>
+ );
+ })}
+ </div>
+ ));
+ })()}
+ {flatModels.length === 0 ? (
+ <div className="composer-model-empty">{t("chat.noModelResults")}</div>
+ ) : null}
+ </div>
+ </>;
+}
diff --git a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
index 3cb942b06..504d41545 100644
--- a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
@@ -1,5 +1,6 @@
import type { TFunction } from "i18next";
-import { formatTokenCount, modelIdsMatch } from "@pi-desktop/shared";
+import type { ReactNode } from "react";
+import { ComposerModelList } from "./ComposerModelList";
import { AnchoredMenu } from "../../../components/settings/AnchoredMenu";
import {
IconBot,
@@ -7,11 +8,9 @@ import {
IconChevronDown,
IconChevronLeft,
IconChevronRight,
- IconSearch,
IconSparkles,
} from "../../../components/icons";
import { TooltipButton } from "../../../components/ui";
-import { composerModelBadges } from "../../../lib/composer-models";
import type { useComposerModelMenu } from "./hooks/useComposerModelMenu";
import { ThinkingLevelSlider } from "./ThinkingLevelSlider";
@@ -27,6 +26,7 @@ export type ComposerModelPickerProps = {
selectedModelId?: string;
controlsBlocked: boolean;
onCloseOtherMenus: () => void;
+ rootActions?: ReactNode;
};
/** Model/reasoning picker with its keyboard and focus contract intact. */
@@ -40,6 +40,7 @@ export function ComposerModelPicker({
selectedModelId,
controlsBlocked,
onCloseOtherMenus,
+ rootActions,
}: ComposerModelPickerProps) {
const {
open,
@@ -56,7 +57,6 @@ export function ComposerModelPicker({
modelListRef,
thinkingListRef,
modelGroups,
- flatModels,
thinkingMenuLevels,
showView,
selectModel,
@@ -114,6 +114,7 @@ export function ComposerModelPicker({
>
{view === "root" ? (
<div className="composer-menu-root" ref={rootMenuRef}>
+ {rootActions}
<button
type="button"
className="composer-menu-entry"
@@ -165,80 +166,13 @@ export function ComposerModelPicker({
<div className="composer-menu-separator" />
{view === "model" ? (
<>
- <label className="composer-model-search">
- <IconSearch size={13} aria-hidden="true" />
- <span className="sr-only">{t("chat.searchModels")}</span>
- <input
- ref={modelSearchRef}
- type="text"
- value={query}
- placeholder={t("chat.searchModels")}
- aria-label={t("chat.searchModels")}
- spellCheck={false}
- autoCorrect="off"
- autoCapitalize="off"
- onChange={(event) => setQuery(event.target.value)}
- />
- </label>
- <div className="composer-model-list" ref={modelListRef}>
- {(() => {
- let flatIndex = 0;
- return modelGroups.map((group) => (
- <div
- key={group.provider.id}
- className="composer-model-group"
- role="group"
- aria-label={group.providerDisplayName}
- >
- <div className="composer-model-group-label">{group.providerDisplayName}</div>
- {group.models.map((model) => {
- const index = flatIndex++;
- const active =
- selectedProviderId === group.provider.id &&
- modelIdsMatch(selectedModelId ?? "", model.modelId);
- const optionTitle = model.displayName || model.modelId;
- return (
- <button
- key={`${group.provider.id}:${model.modelId}`}
- type="button"
- data-model-index={index}
- title={optionTitle}
- className={`composer-plus-item composer-model-option ${active ? "active" : ""} ${modelHighlight === index ? "kb-active" : ""}`}
- role="menuitemradio"
- aria-checked={active}
- onMouseMove={() => setModelHighlight(index)}
- onClick={() => void selectModel(group.provider, model.modelId)}
- >
- <span className="composer-model-option-main">
- <span className="truncate">{optionTitle}</span>
- <span className="composer-model-option-meta">
- {composerModelBadges(model, group.provider).map((badge) => (
- <span
- key={badge}
- className="composer-model-option-badge"
- title={t(badge === "reasoning" ? "chat.modelBadgeReasoning" : "chat.modelBadgeVision")}
- >
- {t(badge === "reasoning" ? "chat.modelBadgeReasoning" : "chat.modelBadgeVision")}
- </span>
- ))}
- {model.contextWindow ? (
- <span className="composer-model-option-ctx">
- {formatTokenCount(model.contextWindow)}
- </span>
- ) : null}
- </span>
- </span>
- {active ? <IconCheck size={14} className="composer-model-check" aria-hidden="true" /> : null}
- </button>
- );
- })}
- </div>
- ));
- })()}
- {flatModels.length === 0 ? (
- <div className="composer-model-empty">{t("chat.noModelResults")}</div>
- ) : null}
- </div>
+ <ComposerModelList
+ t={t} query={query} setQuery={setQuery}
+ modelSearchRef={modelSearchRef} modelListRef={modelListRef}
+ modelGroups={modelGroups} modelHighlight={modelHighlight}
+ setModelHighlight={setModelHighlight} selectModel={selectModel}
+ selectedProviderId={selectedProviderId} selectedModelId={selectedModelId}
+ />
</>
) : (
<>
diff --git a/apps/desktop/src/features/chat/composer/ComposerPermissionPicker.tsx b/apps/desktop/src/features/chat/composer/ComposerPermissionPicker.tsx
new file mode 100644
index 000000000..6ee6fa036
--- /dev/null
+++ b/apps/desktop/src/features/chat/composer/ComposerPermissionPicker.tsx
@@ -0,0 +1,87 @@
+import type { Dispatch, SetStateAction } from "react";
+import type { TFunction } from "i18next";
+import type { GlobalPermissionMode, Mode } from "@pi-desktop/shared";
+import { AnchoredMenu } from "../../../components/settings/AnchoredMenu";
+import { TooltipButton } from "../../../components/ui";
+import { IconCheck, IconChevronDown } from "../../../components/icons";
+import { PERMISSION_MODE_I18N_KEYS } from "../../../lib/permission-mode-labels";
+
+/** Controlled permission UI shared by conversations and task drafts. */
+export function ComposerPermissionPicker({t, mode, composerPermissionMode,
+ permissionOpen, setPermissionOpen, controlsBlocked, onCloseOtherMenus, onSelect,
+}: {
+ t: TFunction;
+ mode: Mode;
+ composerPermissionMode: GlobalPermissionMode;
+ permissionOpen: boolean;
+ setPermissionOpen: Dispatch<SetStateAction<boolean>>;
+ controlsBlocked: boolean;
+ onCloseOtherMenus: () => void;
+ onSelect: (mode: GlobalPermissionMode) => void | Promise<void>;
+}) {
+ return (
+ <AnchoredMenu
+ className="composer-permission"
+ open={permissionOpen && mode !== "goal"}
+ onClose={() => setPermissionOpen(false)}
+ menuClassName="composer-permission-menu"
+ label={t("chat.permissionMode")}
+ role="menu"
+ align="start"
+ side="top"
+ trigger={(ref) => (
+ <TooltipButton
+ ref={ref}
+ type="button"
+ className={`icon-btn mode-chip ${permissionOpen ? "active" : ""}`}
+ tooltip={
+ mode === "goal"
+ ? `${t("chat.permissionMode")} · ${t("goal.autoWarning")}`
+ : mode === "plan" && composerPermissionMode === "auto"
+ ? `${t("chat.permissionMode")} · ${t("plan.autoWarning")}`
+ : t("chat.permissionMode")
+ }
+ ariaLabel={
+ mode === "goal"
+ ? `${t("chat.permissionMode")} · ${t("goal.autoWarning")}`
+ : mode === "plan" && composerPermissionMode === "auto"
+ ? `${t("chat.permissionMode")} · ${t("plan.autoWarning")}`
+ : t("chat.permissionMode")
+ }
+ aria-haspopup={mode === "goal" ? undefined : "menu"}
+ aria-expanded={mode === "goal" ? false : permissionOpen}
+ disabled={controlsBlocked || mode === "goal"}
+ onClick={() => {
+ onCloseOtherMenus();
+ setPermissionOpen((open) => !open);
+ }}
+ >
+ <span className="text-sm">
+ {t(PERMISSION_MODE_I18N_KEYS[composerPermissionMode])}
+ </span>
+ <IconChevronDown size={12} />
+ </TooltipButton>
+ )}
+ >
+ {(["ask", "accept-edits", "auto"] as const).map((candidate) => (
+ <button
+ key={candidate}
+ type="button"
+ role="menuitemradio"
+ aria-checked={composerPermissionMode === candidate}
+ disabled={controlsBlocked}
+ className={`composer-plus-item ${composerPermissionMode === candidate ? "active" : ""}`}
+ onClick={async () => {
+ setPermissionOpen(false);
+ await onSelect(candidate);
+ }}
+ >
+ <span className="flex-1 text-left">
+ {t(PERMISSION_MODE_I18N_KEYS[candidate])}
+ </span>
+ {composerPermissionMode === candidate ? <IconCheck size={13} /> : null}
+ </button>
+ ))}
+ </AnchoredMenu>
+ );
+}
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index ce81a9f81..2f27e84e6 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -8,13 +8,11 @@ import {
type SessionThinkingLevel,
} from "@pi-desktop/shared";
import type { AppState } from "../../../stores/app-store";
-import { AnchoredMenu } from "../../../components/settings/AnchoredMenu";
+import { ComposerPermissionPicker } from "./ComposerPermissionPicker";
import { ContextUsageInspector } from "../../../components/ContextUsageInspector";
import { TooltipButton } from "../../../components/ui";
import {
IconArrowUp,
- IconCheck,
- IconChevronDown,
IconPlus,
IconSparkles,
IconStop,
@@ -24,7 +22,6 @@ import { ModeIcon } from "./ComposerModeIcon";
import { ComposerModelPicker } from "./ComposerModelPicker";
import {
MODE_LABEL_KEYS,
- PERMISSION_MODE_I18N_KEYS,
nextMode,
} from "./model";
import type { useComposerModelMenu } from "./hooks/useComposerModelMenu";
@@ -153,59 +150,11 @@ export function ComposerToolbar({
</span>
</span>
</TooltipButton>
- <AnchoredMenu
- className="composer-permission"
- open={permissionOpen && mode !== "goal"}
- onClose={() => setPermissionOpen(false)}
- menuClassName="composer-permission-menu"
- label={t("chat.permissionMode")}
- role="menu"
- align="start"
- side="top"
- trigger={(ref) => (
- <TooltipButton
- ref={ref}
- type="button"
- className={`icon-btn mode-chip ${permissionOpen ? "active" : ""}`}
- tooltip={
- mode === "goal"
- ? `${t("chat.permissionMode")} · ${t("goal.autoWarning")}`
- : mode === "plan" && composerPermissionMode === "auto"
- ? `${t("chat.permissionMode")} · ${t("plan.autoWarning")}`
- : t("chat.permissionMode")
- }
- ariaLabel={
- mode === "goal"
- ? `${t("chat.permissionMode")} · ${t("goal.autoWarning")}`
- : mode === "plan" && composerPermissionMode === "auto"
- ? `${t("chat.permissionMode")} · ${t("plan.autoWarning")}`
- : t("chat.permissionMode")
- }
- aria-haspopup={mode === "goal" ? undefined : "menu"}
- aria-expanded={mode === "goal" ? false : permissionOpen}
- disabled={controlsBlocked || mode === "goal"}
- onClick={() => {
- modelMenu.setOpen(false);
- setPermissionOpen((open) => !open);
- }}
- >
- <span className="text-sm">
- {t(PERMISSION_MODE_I18N_KEYS[composerPermissionMode])}
- </span>
- <IconChevronDown size={12} />
- </TooltipButton>
- )}
- >
- {(["ask", "accept-edits", "auto"] as const).map((candidate) => (
- <button
- key={candidate}
- type="button"
- role="menuitemradio"
- aria-checked={composerPermissionMode === candidate}
- disabled={controlsBlocked}
- className={`composer-plus-item ${composerPermissionMode === candidate ? "active" : ""}`}
- onClick={async () => {
- setPermissionOpen(false);
+ <ComposerPermissionPicker t={t} mode={mode}
+ composerPermissionMode={composerPermissionMode}
+ permissionOpen={permissionOpen} setPermissionOpen={setPermissionOpen}
+ controlsBlocked={controlsBlocked} onCloseOtherMenus={() => modelMenu.setOpen(false)}
+ onSelect={async (candidate) => {
try {
await configureActiveSession({
mode,
@@ -219,15 +168,7 @@ export function ComposerToolbar({
variant: "error",
});
}
- }}
- >
- <span className="flex-1 text-left">
- {t(PERMISSION_MODE_I18N_KEYS[candidate])}
- </span>
- {composerPermissionMode === candidate ? <IconCheck size={13} /> : null}
- </button>
- ))}
- </AnchoredMenu>
+ }} />
</div>
<div className="composer-right">
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
index a9b07cd72..53167d5ee 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
@@ -34,6 +34,9 @@ type UseComposerModelMenuOptions = {
thinkingProvider: ProviderPublic | null | undefined;
thinkingLevel: SessionThinkingLevel;
controlsBlocked: boolean;
+ configureActiveSession: (configuration: {
+ mode: Mode; providerId?: string; modelId?: string; thinkingLevel: SessionThinkingLevel;
+ }) => Promise<void>;
};
export function useComposerModelMenu({
@@ -44,6 +47,7 @@ export function useComposerModelMenu({
thinkingProvider: resolvedThinkingProvider,
thinkingLevel,
controlsBlocked,
+ configureActiveSession,
}: UseComposerModelMenuOptions) {
const providers = useAppStore((s) => s.providers);
const imageGeneration = useAppStore((s) => s.settings?.imageGeneration);
@@ -54,7 +58,6 @@ export function useComposerModelMenu({
);
const providerModels = useAppStore((s) => s.providerModels);
const loadProviderModels = useAppStore((s) => s.loadProviderModels);
- const configureActiveSession = useAppStore((s) => s.configureActiveSession);
const showToast = useAppStore((s) => s.showToast);
const [open, setOpen] = useState(false);
const [view, setView] = useState<ComposerMenuView>("root");
diff --git a/apps/desktop/src/features/chat/composer/model.ts b/apps/desktop/src/features/chat/composer/model.ts
index a19cfa190..63a3f7a81 100644
--- a/apps/desktop/src/features/chat/composer/model.ts
+++ b/apps/desktop/src/features/chat/composer/model.ts
@@ -38,12 +38,7 @@ export const MODE_LABEL_KEYS: Record<Mode, string> = {
goal: "settings.modeGoal",
};
-export const PERMISSION_MODE_I18N_KEYS: Record<PermissionMode, string> = {
- inherit: "chat.permissionInherit",
- ask: "chat.permissionAsk",
- "accept-edits": "chat.permissionAcceptEdits",
- auto: "chat.permissionAuto",
-};
+export { PERMISSION_MODE_I18N_KEYS } from "../../../lib/permission-mode-labels";
export const THINKING_LEVELS: readonly ThinkingLevel[] = [
"off",
diff --git a/apps/desktop/src/features/scheduled/ScheduledEditor.tsx b/apps/desktop/src/features/scheduled/ScheduledEditor.tsx
index 4cc1c6de1..6b1066488 100644
--- a/apps/desktop/src/features/scheduled/ScheduledEditor.tsx
+++ b/apps/desktop/src/features/scheduled/ScheduledEditor.tsx
@@ -1,25 +1,41 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import type { ScheduledTask } from "@pi-desktop/shared";
+import type { GlobalPermissionMode, ProjectRecord, ScheduledTask } from "@pi-desktop/shared";
import { Button, Field, Input, Textarea } from "../../components/ui";
import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";
import { ScheduledWeekdaySelect } from "./ScheduledWeekdaySelect";
+import {
+ ScheduledExecutionSettings,
+ type ScheduledModelSelection,
+} from "./ScheduledExecutionSettings";
+import { useAppStore } from "../../stores/app-store";
import "./scheduled-editor.css";
-export type ScheduledDraft = Pick<ScheduledTask, "title" | "prompt" | "cadence" | "schedule">;
+export type ScheduledDraft = Pick<ScheduledTask, "title" | "prompt" | "cadence" | "schedule"> & {
+ workspacePath?: string;
+ permissionMode?: GlobalPermissionMode;
+ providerId?: string | null;
+ modelId?: string | null;
+ thinkingLevel?: ScheduledTask["thinkingLevel"] | null;
+};
export function ScheduledEditor({
task,
+ projects,
+ currentWorkspacePath,
busy,
save,
cancel,
}: {
task?: ScheduledTask;
+ projects: readonly ProjectRecord[];
+ currentWorkspacePath: string;
busy: boolean;
save: (draft: ScheduledDraft) => Promise<void>;
cancel: () => void;
}) {
const { t } = useTranslation();
+ const settings = useAppStore((state) => state.settings);
const [title, setTitle] = useState(task?.title ?? "");
const [prompt, setPrompt] = useState(task?.prompt ?? "");
const [cadence, setCadence] = useState<ScheduledTask["cadence"]>(task?.cadence ?? "manual");
@@ -28,6 +44,28 @@ export function ScheduledEditor({
const [weekdays, setWeekdays] = useState<number[]>(
task?.schedule?.weekdays ?? [task?.schedule?.weekday ?? 0],
);
+ const [workspacePath, setWorkspacePath] = useState(
+ task?.workspacePath || currentWorkspacePath || projects[0]?.path || "",
+ );
+ const [workspaceTouched, setWorkspaceTouched] = useState(false);
+ const [permissionMode, setPermissionMode] = useState<GlobalPermissionMode>(
+ task?.permissionMode ?? "ask",
+ );
+ const [permissionTouched, setPermissionTouched] = useState(false);
+ const defaultModel = !task && settings?.defaultProviderId && settings.defaultModelId
+ ? { providerId: settings.defaultProviderId, modelId: settings.defaultModelId }
+ : {};
+ const [modelSelection, setModelSelection] = useState<ScheduledModelSelection>(
+ task?.providerId && task.modelId
+ ? { providerId: task.providerId, modelId: task.modelId, thinkingLevel: task.thinkingLevel }
+ : { ...defaultModel, thinkingLevel: task?.thinkingLevel },
+ );
+ const [modelTouched, setModelTouched] = useState(false);
+ useEffect(() => {
+ if (workspacePath) return;
+ const fallback = currentWorkspacePath || projects[0]?.path;
+ if (fallback) setWorkspacePath(fallback);
+ }, [currentWorkspacePath, projects, workspacePath]);
const validTime = hour !== "" && minute !== "" && Number.isInteger(Number(hour)) &&
Number.isInteger(Number(minute)) && Number(hour) >= 0 && Number(hour) < 24 &&
Number(minute) >= 0 && Number(minute) < 60;
@@ -53,6 +91,23 @@ export function ScheduledEditor({
onSubmit={(event) => {
event.preventDefault();
if (busy || !valid) return;
+ const executionSettings: Pick<
+ ScheduledDraft,
+ "workspacePath" | "permissionMode" | "providerId" | "modelId" | "thinkingLevel"
+ > = {};
+ if (!task || task.workspacePath || workspaceTouched) {
+ if (workspacePath) executionSettings.workspacePath = workspacePath;
+ }
+ if (!task || task.permissionMode || permissionTouched) {
+ executionSettings.permissionMode = permissionMode;
+ }
+ if (!task || (task.providerId && task.modelId) || modelTouched) {
+ executionSettings.providerId = modelSelection.providerId ?? null;
+ executionSettings.modelId = modelSelection.modelId ?? null;
+ }
+ if (modelTouched || task?.thinkingLevel) {
+ executionSettings.thinkingLevel = modelSelection.thinkingLevel ?? null;
+ }
void save({
title: title.trim(),
prompt: prompt.trim(),
@@ -66,6 +121,7 @@ export function ScheduledEditor({
hour: Number(hour), minute: Number(minute), weekday: weekdays[0] ?? 0,
...(cadence === "weekly" ? { weekdays } : {}),
},
+ ...executionSettings,
});
}}
>
@@ -82,14 +138,41 @@ export function ScheduledEditor({
/>
</Field>
<Field label={t("scheduled.prompt")}>
- <Textarea
- required
- rows={4}
- value={prompt}
- onChange={(e) => setPrompt(e.target.value)}
- placeholder={t("scheduled.promptPlaceholder")}
- />
+ <div className="composer-shell scheduled-instruction-shell">
+ <Textarea
+ required
+ rows={4}
+ className="composer-input scheduled-instruction-input"
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder={t("scheduled.promptPlaceholder")}
+ />
+ <ScheduledExecutionSettings
+ workspacePath={workspacePath}
+ projects={projects}
+ permissionMode={permissionMode}
+ modelSelection={modelSelection}
+ busy={busy}
+ onWorkspaceChange={(path) => {
+ setWorkspacePath(path);
+ setWorkspaceTouched(true);
+ }}
+ onPermissionChange={(mode) => {
+ setPermissionMode(mode);
+ setPermissionTouched(true);
+ }}
+ onModelChange={(selection) => {
+ setModelSelection(selection);
+ setModelTouched(true);
+ }}
+ />
+ </div>
</Field>
+ {permissionMode === "auto" && (
+ <p className="dest-row-meta scheduled-permission-warning" role="status">
+ {t("scheduled.autoPermissionHint")}
+ </p>
+ )}
<div className="scheduled-fields">
<Field label={t("scheduled.cadence")}>
<SettingsMenuSelect
@@ -127,7 +210,6 @@ export function ScheduledEditor({
)}
{cadence === "hourly" && <p className="dest-row-meta">{t("scheduled.hourlyHint")}</p>}
<p className="dest-row-meta">{t("scheduled.localTimeHint")}</p>
- <p className="dest-row-meta">{task?.workspacePath ?? t("scheduled.projectHint")}</p>
<div className="flex gap-2">
<Button type="submit" variant="primary" disabled={busy || !valid}>
{t("scheduled.save")}
diff --git a/apps/desktop/src/features/scheduled/ScheduledExecutionSettings.tsx b/apps/desktop/src/features/scheduled/ScheduledExecutionSettings.tsx
new file mode 100644
index 000000000..842c02280
--- /dev/null
+++ b/apps/desktop/src/features/scheduled/ScheduledExecutionSettings.tsx
@@ -0,0 +1,95 @@
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ type GlobalPermissionMode,
+ type ProjectRecord,
+ type SessionThinkingLevel,
+} from "@pi-desktop/shared";
+import { IconFolder } from "../../components/icons";
+import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";
+import { useAppStore } from "../../stores/app-store";
+import { ScheduledModelPicker } from "./ScheduledModelPicker";
+import { ComposerPermissionPicker } from "../chat/composer/ComposerPermissionPicker";
+
+
+export type ScheduledModelSelection = {
+ providerId?: string;
+ modelId?: string;
+ thinkingLevel?: SessionThinkingLevel;
+};
+
+function projectLabel(path: string, name?: string): string {
+ if (name?.trim()) return name.trim();
+ const segments = path.replaceAll("\\", "/").split("/").filter(Boolean);
+ return segments.at(-1) || path;
+}
+
+export function ScheduledExecutionSettings({
+ workspacePath,
+ projects,
+ permissionMode,
+ modelSelection,
+ busy,
+ onWorkspaceChange,
+ onPermissionChange,
+ onModelChange,
+}: {
+ workspacePath: string;
+ projects: readonly ProjectRecord[];
+ permissionMode: GlobalPermissionMode;
+ modelSelection: ScheduledModelSelection;
+ busy: boolean;
+ onWorkspaceChange: (path: string) => void;
+ onPermissionChange: (mode: GlobalPermissionMode) => void;
+ onModelChange: (selection: ScheduledModelSelection) => void;
+}) {
+ const { t } = useTranslation();
+ const [permissionOpen, setPermissionOpen] = useState(false);
+ useEffect(() => { if (busy) setPermissionOpen(false); }, [busy]);
+ const currentWorkspacePath = useAppStore((state) => state.workspace?.path ?? "");
+ const projectOptions = useMemo(() => {
+ const seen = new Set<string>();
+ const result: Array<{ id: string; label: string }> = [];
+ const add = (path: string | null | undefined, name?: string) => {
+ const value = path?.trim();
+ if (!value) return;
+ const key = value.replaceAll("\\", "/").toLocaleLowerCase();
+ if (seen.has(key)) return;
+ seen.add(key);
+ result.push({ id: value, label: projectLabel(value, name) });
+ };
+ add(workspacePath);
+ add(currentWorkspacePath);
+ for (const project of projects) add(project.path, project.name);
+ return result;
+ }, [currentWorkspacePath, projects, workspacePath]);
+
+ return (
+ <div className="composer-toolbar scheduled-execution-toolbar">
+ <div className="composer-left">
+ <SettingsMenuSelect
+ className="scheduled-execution-project"
+ triggerClassName="icon-btn mode-chip scheduled-execution-trigger"
+ leading={<IconFolder size={14} />}
+ label={t("settings.selectProject")}
+ value={workspacePath}
+ disabled={busy || projectOptions.length === 0}
+ options={
+ projectOptions.length
+ ? projectOptions
+ : [{ id: "", label: t("settings.noProjects"), disabled: true }]
+ }
+ onChange={onWorkspaceChange}
+ />
+ <ComposerPermissionPicker t={t} mode="agent"
+ composerPermissionMode={permissionMode}
+ permissionOpen={permissionOpen} setPermissionOpen={setPermissionOpen}
+ controlsBlocked={busy} onCloseOtherMenus={() => {}}
+ onSelect={onPermissionChange} />
+ </div>
+ <div className="composer-right">
+ <ScheduledModelPicker value={modelSelection} disabled={busy} onChange={onModelChange} />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/scheduled/ScheduledModelPicker.tsx b/apps/desktop/src/features/scheduled/ScheduledModelPicker.tsx
new file mode 100644
index 000000000..437e3fda1
--- /dev/null
+++ b/apps/desktop/src/features/scheduled/ScheduledModelPicker.tsx
@@ -0,0 +1,52 @@
+import { useId, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { imageGenerationBindings } from "@pi-desktop/shared";
+import { useAppStore } from "../../stores/app-store";
+import { composerModelDisplayName, composerModelsForProvider } from "../../lib/composer-models";
+import { ComposerModelPicker } from "../chat/composer/ComposerModelPicker";
+import { useComposerModelMenu } from "../chat/composer/hooks/useComposerModelMenu";
+import { thinkingLevelForProvider, thinkingProviderForModel } from "../chat/composer/model";
+import type { ScheduledModelSelection } from "./ScheduledExecutionSettings";
+
+/** The same Composer view/controller, with a task-draft persistence callback. */
+export function ScheduledModelPicker({ value, disabled, onChange }: {
+ value: ScheduledModelSelection;
+ disabled: boolean;
+ onChange: (selection: ScheduledModelSelection) => void;
+}) {
+ const { t } = useTranslation();
+ const draftId = useId();
+ const providers = useAppStore(s => s.providers);
+ const providerModels = useAppStore(s => s.providerModels);
+ const settings = useAppStore(s => s.settings);
+ const provider = providers.find(p => p.id === value.providerId);
+ const images = useMemo(() => imageGenerationBindings(settings?.imageGenerationModels,
+ settings?.imageGeneration), [settings?.imageGenerationModels, settings?.imageGeneration]);
+ const selected = provider && composerModelsForProvider(provider, providerModels[provider.id], images)
+ .find(model => model.modelId === value.modelId);
+ const thinkingProvider = thinkingProviderForModel(provider, value.modelId,
+ provider ? providerModels[provider.id] : undefined);
+ const thinkingLevel = thinkingLevelForProvider(thinkingProvider, value.thinkingLevel ?? "off");
+ const controller = useComposerModelMenu({
+ mode: "agent", activeSessionId: draftId, provider, modelId: value.modelId,
+ thinkingProvider, thinkingLevel, controlsBlocked: disabled,
+ configureActiveSession: async configuration => {
+ onChange({providerId: configuration.providerId ?? value.providerId,
+ modelId: configuration.modelId ?? value.modelId,
+ thinkingLevel: configuration.thinkingLevel});
+ },
+ });
+ const label = selected && provider?.enabled
+ ? composerModelDisplayName(provider, selected.modelId, selected.displayName)
+ : value.providerId && value.modelId
+ ? t("scheduled.unavailableModel", {provider: value.providerId, model: value.modelId})
+ : t("settings.defaultModel");
+ return <ComposerModelPicker t={t} controller={controller} modelLabel={label}
+ thinkingLabel={thinkingLevel} thinkingLevel={thinkingLevel}
+ selectedProviderId={value.providerId} selectedModelId={value.modelId}
+ controlsBlocked={disabled} onCloseOtherMenus={() => {}}
+ rootActions={value.providerId ? <button type="button" className="composer-plus-item"
+ role="menuitem" disabled={disabled} onClick={() => {onChange({}); controller.setOpen(false);}}>
+ {t("settings.defaultModel")}
+ </button> : undefined} />;
+}
diff --git a/apps/desktop/src/features/scheduled/scheduled-editor.css b/apps/desktop/src/features/scheduled/scheduled-editor.css
index b69ea92fb..b870d3699 100644
--- a/apps/desktop/src/features/scheduled/scheduled-editor.css
+++ b/apps/desktop/src/features/scheduled/scheduled-editor.css
@@ -9,6 +9,106 @@
height: 36px;
border-radius: var(--radius-md);
}
+.scheduled-instruction-shell {
+ isolation: auto;
+ border-radius: var(--radius-lg);
+}
+
+.scheduled-instruction-input.field-textarea {
+ min-height: 104px;
+ max-height: none;
+ display: block;
+ resize: none;
+ overflow-y: auto;
+ border: 1px solid var(--ds-border-strong);
+ border-radius: var(--radius-lg);
+ padding: 12px 14px;
+ background: var(--ds-tile-hover);
+ box-shadow: none;
+}
+
+.scheduled-instruction-input.field-textarea:focus {
+ background: var(--ds-tile-hover);
+ box-shadow: none;
+}
+
+.scheduled-instruction-input.field-textarea::placeholder {
+ opacity: 1 !important;
+}
+
+.scheduled-execution-toolbar {
+ container-type: inline-size;
+ padding: 4px 8px 8px;
+}
+
+.scheduled-execution-toolbar .settings-menu-select-trigger-leading {
+ display: inline-flex;
+ flex: 0 0 auto;
+ align-items: center;
+ justify-content: center;
+ color: var(--ds-text-muted);
+}
+
+.scheduled-execution-toolbar .settings-menu-select-trigger.scheduled-execution-trigger {
+ max-width: 100%;
+ background: transparent;
+ box-shadow: none;
+}
+
+.scheduled-execution-toolbar .settings-menu-select-trigger.scheduled-execution-trigger:hover,
+.scheduled-execution-toolbar .settings-menu-select-trigger.scheduled-execution-trigger[aria-expanded="true"] {
+ background: var(--ds-bg-hover);
+ color: var(--ds-text-primary) !important;
+}
+
+.scheduled-execution-toolbar .settings-menu-select-trigger-label {
+ flex: 0 1 auto;
+ font-size: var(--text-sm);
+}
+
+.scheduled-execution-toolbar .settings-menu-select-trigger > svg {
+ width: 12px;
+ height: 12px;
+}
+
+.scheduled-execution-project {
+ max-width: min(190px, 42cqw);
+}
+
+.scheduled-execution-permission {
+ max-width: min(160px, 34cqw);
+}
+
+.scheduled-execution-model {
+ max-width: min(300px, 48cqw);
+}
+
+.scheduled-execution-toolbar .settings-menu-select-anchor,
+.scheduled-execution-toolbar .settings-menu-select-trigger {
+ min-width: 0;
+}
+
+@container (max-width: 440px) {
+ .scheduled-execution-project { max-width: 34cqw; }
+ .scheduled-execution-permission { max-width: 28cqw; }
+ .scheduled-execution-model { max-width: 30cqw; }
+}
+
+@container (max-width: 350px) {
+ .scheduled-execution-toolbar .settings-menu-select-trigger-label {
+ display: none;
+ }
+ .scheduled-execution-toolbar .settings-menu-select-trigger.scheduled-execution-trigger {
+ width: 28px;
+ padding: 0 !important;
+ }
+}
+
+.scheduled-instruction-shell,
+.scheduled-execution-toolbar {
+ width: 100%;
+}
+.scheduled-permission-warning { color: var(--ds-warning); }
.scheduled-weekday-trigger { max-width: min(300px, 100%); }
.scheduled-weekday-menu { min-width: 132px; }
.scheduled-weekday-option { min-height: 38px; }
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index daf193388..7085c3908 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -810,8 +810,20 @@ export const api = {
cadence?: ScheduledTask["cadence"];
enabled?: boolean;
schedule?: ScheduledTask["schedule"];
+ workspacePath?: string;
+ permissionMode?: ScheduledTask["permissionMode"];
+ thinkingLevel?: ScheduledTask["thinkingLevel"] | null;
+ providerId?: string | null;
+ modelId?: string | null;
}) => invoke<{ task: ScheduledTask }>(IPC.invoke.scheduledCreate, input),
- updateScheduled: (input: Partial<ScheduledTask> & { id: string }) =>
+ updateScheduled: (
+ input: Omit<Partial<ScheduledTask>, "providerId" | "modelId" | "thinkingLevel"> & {
+ id: string;
+ thinkingLevel?: ScheduledTask["thinkingLevel"] | null;
+ providerId?: string | null;
+ modelId?: string | null;
+ },
+ ) =>
invoke<{ task: ScheduledTask }>(IPC.invoke.scheduledUpdate, input),
deleteScheduled: (id: string) => invoke(IPC.invoke.scheduledDelete, id),
executeScheduled: (id: string) => invoke<{ sessionId: string }>(IPC.invoke.scheduledExecute, id),
diff --git a/apps/desktop/src/lib/permission-mode-labels.ts b/apps/desktop/src/lib/permission-mode-labels.ts
new file mode 100644
index 000000000..f7020d2a1
--- /dev/null
+++ b/apps/desktop/src/lib/permission-mode-labels.ts
@@ -0,0 +1,9 @@
+import type { PermissionMode } from "@pi-desktop/shared";
+
+/** One label mapping shared by Composer and task configuration surfaces. */
+export const PERMISSION_MODE_I18N_KEYS: Record<PermissionMode, string> = {
+ inherit: "chat.permissionInherit",
+ ask: "chat.permissionAsk",
+ "accept-edits": "chat.permissionAcceptEdits",
+ auto: "chat.permissionAuto",
+};
diff --git a/apps/desktop/src/pages/ScheduledPage.tsx b/apps/desktop/src/pages/ScheduledPage.tsx
index ef5d289cc..5cab936d6 100644
--- a/apps/desktop/src/pages/ScheduledPage.tsx
+++ b/apps/desktop/src/pages/ScheduledPage.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import type { ScheduledTask, ScheduledTaskRun } from "@pi-desktop/shared";
+import type { ProjectRecord, ScheduledTask, ScheduledTaskRun } from "@pi-desktop/shared";
import { useAppStore } from "../stores/app-store";
import { api } from "../lib/api";
import { Badge, Button, Panel } from "../components/ui";
@@ -12,8 +12,10 @@ export function ScheduledPage() {
const showToast = useAppStore((s) => s.showToast);
const selectSession = useAppStore((s) => s.selectSession);
const setPage = useAppStore((s) => s.setPage);
+ const currentWorkspacePath = useAppStore((s) => s.workspace?.path ?? "");
const [tasks, setTasks] = useState<ScheduledTask[]>([]);
const [runs, setRuns] = useState<ScheduledTaskRun[]>([]);
+ const [projects, setProjects] = useState<ProjectRecord[]>([]);
const [tab, setTab] = useState<"tasks" | "runs">("tasks");
const [editor, setEditor] = useState<ScheduledTask | "new" | null>(null);
const [busy, setBusy] = useState(false);
@@ -24,13 +26,15 @@ export function ScheduledPage() {
const refresh = useCallback(async () => {
const request = ++revision.current;
try {
- const [taskResult, runResult] = await Promise.all([
+ const [taskResult, runResult, projectResult] = await Promise.all([
api.listScheduled(),
api.listScheduledRuns(),
+ api.listProjects().catch(() => ({ projects: [] as ProjectRecord[] })),
]);
if (!mounted.current || request !== revision.current) return;
setTasks(taskResult.tasks);
setRuns(runResult.runs);
+ setProjects(projectResult.projects);
setError("");
setLoaded(true);
} catch (failure) {
@@ -132,6 +136,8 @@ export function ScheduledPage() {
<ScheduledEditor
key={editor === "new" ? "new" : editor.id}
task={editor === "new" ? undefined : editor}
+ projects={projects}
+ currentWorkspacePath={currentWorkspacePath}
busy={busy}
save={save}
cancel={() => setEditor(null)}
diff --git a/apps/desktop/test/composer-model-thinking-menu.test.mjs b/apps/desktop/test/composer-model-thinking-menu.test.mjs
index 2c6e00893..34555af2f 100644
--- a/apps/desktop/test/composer-model-thinking-menu.test.mjs
+++ b/apps/desktop/test/composer-model-thinking-menu.test.mjs
@@ -9,7 +9,8 @@ const [modelMenuSource, pickerSource, sliderSource] = await Promise.all([
readComposerModule("ComposerModelPicker.tsx"),
readComposerModule("ThinkingLevelSlider.tsx"),
]);
-const composerSource = `${modelMenuSource}\n${pickerSource}\n${sliderSource}`;
+const listSource = await readComposerModule("ComposerModelList.tsx");
+const composerSource = `${modelMenuSource}\n${pickerSource}\n${sliderSource}\n${listSource}`;
const stylesSource = await loadStyles();
test("Composer uses one model × reasoning popover with a root and in-place submenus", () => {
diff --git a/crates/host-core/src/rpc/scheduled_rpc.rs b/crates/host-core/src/rpc/scheduled_rpc.rs
index 366fa43b2..f0c31b32a 100644
--- a/crates/host-core/src/rpc/scheduled_rpc.rs
+++ b/crates/host-core/src/rpc/scheduled_rpc.rs
@@ -6,11 +6,12 @@ use crate::{scheduled, sessions};
mod project_tests;
pub(super) fn handle(st: &AppState, method: &str, params: Value) -> Result<Value, JsonRpcError> {
- handle_in_workspace(
+ handle_with_workspace_policy(
st,
method,
params,
st.workspace.get().map(|workspace| workspace.path),
+ true,
)
}
@@ -19,6 +20,16 @@ pub(super) fn handle_in_workspace(
method: &str,
params: Value,
workspace: Option<String>,
+) -> Result<Value, JsonRpcError> {
+ handle_with_workspace_policy(st, method, params, workspace, false)
+}
+
+fn handle_with_workspace_policy(
+ st: &AppState,
+ method: &str,
+ params: Value,
+ workspace: Option<String>,
+ allow_workspace_override: bool,
) -> Result<Value, JsonRpcError> {
match method {
"scheduled.list" => {
@@ -29,7 +40,13 @@ pub(super) fn handle_in_workspace(
"scheduled.create" => {
let mut params = params;
validate_schedule_input(&params)?;
- if params.get("schedule").is_some() {
+ validate_execution_input(&params)?;
+ if !allow_workspace_override {
+ if let Some(object) = params.as_object_mut() {
+ object.remove("workspacePath");
+ }
+ }
+ if params.get("schedule").is_some() && params.get("workspacePath").is_none() {
params["workspacePath"] = json!(workspace);
}
let task = scheduled::create_task(&st.db, &params)
@@ -39,6 +56,7 @@ pub(super) fn handle_in_workspace(
"scheduled.update" => {
let mut params = params;
validate_schedule_input(&params)?;
+ validate_execution_input(&params)?;
if matches!(
params.get("cadence").and_then(Value::as_str),
Some("daily" | "weekly")
@@ -58,7 +76,10 @@ pub(super) fn handle_in_workspace(
let id = params.get("id").and_then(Value::as_str).unwrap_or("");
let existing = scheduled::get_task(&st.db, id)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
- if existing
+ if allow_workspace_override && params.get("workspacePath").is_some() {
+ // The desktop form may explicitly move a task to another
+ // saved project. Conversation tools stay project-scoped.
+ } else if existing
.as_ref()
.is_some_and(|task| !task.workspace_bound && task.schedule.is_none())
{
@@ -149,23 +170,34 @@ pub(super) fn handle_in_workspace(
let options = sessions::SessionCreateOptions {
title: Some(task.title.clone()),
mode: Some("agent".into()),
- provider_id: settings
- .get("defaultProviderId")
- .and_then(|v| v.as_str())
- .map(str::to_string),
- model_id: settings
- .get("defaultModelId")
- .and_then(|v| v.as_str())
- .map(str::to_string),
+ thinking_level: task.thinking_level.clone(),
+ provider_id: task.provider_id.clone().or_else(|| {
+ settings
+ .get("defaultProviderId")
+ .and_then(|v| v.as_str())
+ .map(str::to_string)
+ }),
+ model_id: task.model_id.clone().or_else(|| {
+ settings
+ .get("defaultModelId")
+ .and_then(|v| v.as_str())
+ .map(str::to_string)
+ }),
project_path: if task.workspace_bound || task.schedule.is_some() {
task.workspace_path.clone()
} else {
st.workspace.get().map(|w| w.path)
},
- permission_mode: automatic.then(|| "ask".into()),
+ permission_mode: task
+ .permission_mode
+ .clone()
+ .or_else(|| automatic.then(|| "ask".into())),
..Default::default()
};
- let session = if automatic {
+ 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)
} else {
sessions::create_session(
@@ -248,6 +280,11 @@ fn validate_schedule_input(params: &Value) -> Result<(), JsonRpcError> {
Ok(())
}
+fn validate_execution_input(params: &Value) -> Result<(), JsonRpcError> {
+ scheduled::automation::validate_execution_input(params)
+ .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -483,6 +520,180 @@ mod tests {
assert_eq!(history["runs"][0]["status"], "completed");
}
+ #[test]
+ fn task_execution_settings_are_persisted_per_task_and_used_for_runs() {
+ let dir = tempfile::tempdir().unwrap();
+ let current_project = tempfile::tempdir().unwrap();
+ let selected_project = tempfile::tempdir().unwrap();
+ let mut state = AppState::open(dir.path()).unwrap();
+ state.workspace.set(current_project.path());
+ let selected_path =
+ crate::db::canonical_project_path(&selected_project.path().to_string_lossy()).unwrap();
+
+ let first = handle(
+ &state,
+ "scheduled.create",
+ json!({
+ "title":"Pinned task",
+ "prompt":"Review",
+ "cadence":"daily",
+ "schedule":{"hour":9,"minute":0,"weekday":0},
+ "workspacePath":selected_path,
+ "permissionMode":"accept-edits",
+ "providerId":"provider-pinned",
+ "modelId":"model-pinned",
+ "thinkingLevel":"high"
+ }),
+ )
+ .unwrap()["task"]
+ .clone();
+ let second = handle(
+ &state,
+ "scheduled.create",
+ json!({
+ "title":"Separate task",
+ "prompt":"Review separately",
+ "cadence":"manual",
+ "workspacePath":state.workspace.get().unwrap().path,
+ "permissionMode":"auto",
+ "providerId":"provider-other",
+ "modelId":"model-other",
+ "thinkingLevel":"omit"
+ }),
+ )
+ .unwrap()["task"]
+ .clone();
+
+ assert_eq!(first["workspacePath"], selected_path);
+ assert_eq!(first["permissionMode"], "accept-edits");
+ assert_eq!(first["providerId"], "provider-pinned");
+ assert_eq!(first["modelId"], "model-pinned");
+ assert_eq!(second["permissionMode"], "auto");
+ assert_eq!(second["providerId"], "provider-other");
+ assert_eq!(second["modelId"], "model-other");
+
+ state.db.conn().execute(
+ "UPDATE scheduled_tasks SET config_json = json_set(config_json, '$.nextRunAt', ?1) WHERE id = ?2",
+ rusqlite::params![crate::db::now_ms(), first["id"].as_str().unwrap()],
+ ).unwrap();
+ let run = handle(
+ &state,
+ "scheduled.run",
+ json!({"id":first["id"],"automatic":true}),
+ )
+ .unwrap();
+ let session = sessions::get_session(&state.db, run["sessionId"].as_str().unwrap())
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ session.summary.project_path.as_deref(),
+ Some(selected_path.as_str())
+ );
+ assert_eq!(session.summary.permission_mode, "accept-edits");
+ assert_eq!(
+ session.summary.provider_id.as_deref(),
+ Some("provider-pinned")
+ );
+ assert_eq!(session.summary.model_id.as_deref(), Some("model-pinned"));
+ assert_eq!(session.summary.thinking_level, "high");
+ handle(
+ &state,
+ "scheduled.finishRun",
+ json!({"runId":run["runId"],"status":"completed"}),
+ )
+ .unwrap();
+
+ let separate_run = handle(&state, "scheduled.run", json!({"id":second["id"]})).unwrap();
+ let separate_session =
+ sessions::get_session(&state.db, separate_run["sessionId"].as_str().unwrap())
+ .unwrap()
+ .unwrap();
+ assert_eq!(separate_session.summary.permission_mode, "auto");
+ assert_eq!(separate_session.summary.thinking_level, "omit");
+ assert_eq!(
+ separate_session.summary.provider_id.as_deref(),
+ Some("provider-other")
+ );
+ assert_eq!(
+ separate_session.summary.model_id.as_deref(),
+ Some("model-other")
+ );
+
+ handle(
+ &state,
+ "scheduled.update",
+ json!({"id":first["id"],"permissionMode":"ask"}),
+ )
+ .unwrap();
+ let saved = handle(&state, "scheduled.list", json!({})).unwrap();
+ let untouched = saved["tasks"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|task| task["id"] == second["id"])
+ .unwrap();
+ assert_eq!(untouched["permissionMode"], "auto");
+ assert_eq!(untouched["providerId"], "provider-other");
+ assert_eq!(untouched["modelId"], "model-other");
+ assert_eq!(untouched["thinkingLevel"], "omit");
+ handle(
+ &state,
+ "scheduled.update",
+ json!({"id":first["id"], "thinkingLevel":null}),
+ )
+ .unwrap();
+ assert!(
+ handle(&state, "scheduled.list", json!({})).unwrap()["tasks"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|task| task["id"] == first["id"])
+ .unwrap()
+ .get("thinkingLevel")
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn legacy_tasks_keep_their_previous_execution_defaults() {
+ let dir = tempfile::tempdir().unwrap();
+ let project = tempfile::tempdir().unwrap();
+ let mut state = AppState::open(dir.path()).unwrap();
+ state.workspace.set(project.path());
+ state
+ .db
+ .set_setting(
+ "app",
+ &json!({
+ "defaultProviderId":"provider-default",
+ "defaultModelId":"model-default",
+ "defaultPermissionMode":"auto"
+ }),
+ )
+ .unwrap();
+ let task = scheduled::create_task(
+ &state.db,
+ &json!({"title":"Legacy", "prompt":"Review", "cadence":"manual"}),
+ )
+ .unwrap();
+ let projected = handle(&state, "scheduled.list", json!({})).unwrap();
+ assert!(projected["tasks"][0].get("permissionMode").is_none());
+ assert!(projected["tasks"][0].get("providerId").is_none());
+ assert!(projected["tasks"][0].get("modelId").is_none());
+
+ let run = handle(&state, "scheduled.run", json!({"id":task.id})).unwrap();
+ let session = sessions::get_session(&state.db, run["sessionId"].as_str().unwrap())
+ .unwrap()
+ .unwrap();
+ assert_eq!(session.summary.permission_mode, "inherit");
+ assert_eq!(session.summary.thinking_level, "off");
+ assert_eq!(
+ session.summary.provider_id.as_deref(),
+ Some("provider-default")
+ );
+ assert_eq!(session.summary.model_id.as_deref(), Some("model-default"));
+ }
+
#[test]
fn invalid_schedule_does_not_mutate_task() {
let dir = tempfile::tempdir().unwrap();
@@ -503,5 +714,21 @@ mod tests {
)
.is_err());
assert!(scheduled::list_tasks(&state.db).unwrap().is_empty());
+ for invalid in [
+ json!({"prompt":"Review", "thinkingLevel":"invalid"}),
+ json!({
+ "prompt":"Review", "cadence":"manual", "permissionMode":"unrestricted"
+ }),
+ json!({
+ "prompt":"Review", "cadence":"manual", "providerId":"provider-only"
+ }),
+ json!({
+ "prompt":"Review", "cadence":"manual", "providerId":"", "modelId":"model"
+ }),
+ ] {
+ let error = handle(&state, "scheduled.create", invalid).unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");
+ }
+ assert!(scheduled::list_tasks(&state.db).unwrap().is_empty());
}
}
diff --git a/crates/host-core/src/scheduled.rs b/crates/host-core/src/scheduled.rs
index 98dfb1a14..6e92978e0 100644
--- a/crates/host-core/src/scheduled.rs
+++ b/crates/host-core/src/scheduled.rs
@@ -32,6 +32,14 @@ pub struct ScheduledTask {
pub next_run_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub workspace_path: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub permission_mode: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub provider_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub model_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub thinking_level: Option<String>,
/// Presence distinguishes a saved project (including null) from legacy tasks.
#[serde(skip)]
pub(crate) workspace_bound: bool,
@@ -114,7 +122,11 @@ fn config_with_mode(mut config: Value, mode: &str) -> String {
}
fn task_config_json(value: &Value) -> String {
- config_with_mode(config_value(config_input(value)), &task_mode(value))
+ let mut config = config_value(config_input(value));
+ if automation::validate_execution_input(value).is_ok() {
+ automation::configure_execution(&mut config, value);
+ }
+ config_with_mode(config, &task_mode(value))
}
fn merge_config(base: &mut Value, incoming: &Value) {
@@ -164,6 +176,20 @@ fn task_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<ScheduledTask> {
.get("calendarConfigured")
.and_then(Value::as_bool)
.unwrap_or(matches!(cadence.as_str(), "daily" | "weekly"));
+ let provider_id = config
+ .get("providerId")
+ .and_then(Value::as_str)
+ .filter(|value| !value.trim().is_empty())
+ .map(str::to_string);
+ let model_id = config
+ .get("modelId")
+ .and_then(Value::as_str)
+ .filter(|value| !value.trim().is_empty())
+ .map(str::to_string);
+ let (provider_id, model_id) = match (provider_id, model_id) {
+ (Some(provider), Some(model)) => (Some(provider), Some(model)),
+ _ => (None, None),
+ };
Ok(ScheduledTask {
id: row.get(0)?,
title: row.get(1)?,
@@ -187,6 +213,18 @@ fn task_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<ScheduledTask> {
.get("workspacePath")
.and_then(Value::as_str)
.and_then(crate::db::canonical_project_path),
+ permission_mode: config
+ .get("permissionMode")
+ .and_then(Value::as_str)
+ .filter(|mode| matches!(*mode, "ask" | "accept-edits" | "auto"))
+ .map(str::to_string),
+ provider_id,
+ model_id,
+ thinking_level: config
+ .get("thinkingLevel")
+ .and_then(Value::as_str)
+ .filter(|level| sessions::is_valid_thinking_level(level))
+ .map(str::to_string),
})
}
@@ -508,6 +546,9 @@ mod tests {
"prompt": "nightly check",
"cadence": "daily",
"enabled": false,
+ "permissionMode": "auto",
+ "providerId": "provider-imported",
+ "modelId": "model-imported",
"createdAt": "2025-06-01T00:00:00Z",
"updatedAt": "2025-06-02T00:00:00Z",
"lastRunAt": "2025-06-03T00:00:00Z"
@@ -519,6 +560,9 @@ mod tests {
assert_eq!(task.title, "Nightly");
assert!(!task.enabled);
assert_eq!(task.mode, "agent");
+ assert_eq!(task.permission_mode.as_deref(), Some("auto"));
+ assert_eq!(task.provider_id.as_deref(), Some("provider-imported"));
+ assert_eq!(task.model_id.as_deref(), Some("model-imported"));
assert_eq!(
ts_to_ms(&task.last_run_at.unwrap()),
ts_to_ms("2025-06-03T00:00:00Z")
diff --git a/crates/host-core/src/scheduled/automation.rs b/crates/host-core/src/scheduled/automation.rs
index 74581d729..f419f8cb3 100644
--- a/crates/host-core/src/scheduled/automation.rs
+++ b/crates/host-core/src/scheduled/automation.rs
@@ -5,7 +5,76 @@ use serde_json::{json, Value};
use super::{get_task, timing::Schedule};
use crate::db::{now_ms, Database};
+const TASK_PERMISSION_MODES: [&str; 3] = ["ask", "accept-edits", "auto"];
+
+pub fn validate_execution_input(input: &Value) -> Result<()> {
+ if let Some(value) = input.get("thinkingLevel") {
+ if !value.is_null()
+ && !value
+ .as_str()
+ .is_some_and(crate::sessions::is_valid_thinking_level)
+ {
+ bail!("thinkingLevel must be a supported session thinking level or null");
+ }
+ }
+ if let Some(value) = input.get("permissionMode") {
+ if !value.is_null()
+ && !value
+ .as_str()
+ .is_some_and(|mode| TASK_PERMISSION_MODES.contains(&mode))
+ {
+ bail!("permissionMode must be ask, accept-edits, auto, or null");
+ }
+ }
+ let provider = input.get("providerId");
+ let model = input.get("modelId");
+ if provider.is_some() || model.is_some() {
+ let paired_null = provider.is_some_and(Value::is_null) && model.is_some_and(Value::is_null);
+ let paired_text = provider
+ .and_then(Value::as_str)
+ .is_some_and(|value| !value.trim().is_empty() && value.chars().count() <= 256)
+ && model
+ .and_then(Value::as_str)
+ .is_some_and(|value| !value.trim().is_empty() && value.chars().count() <= 256);
+ if !paired_null && !paired_text {
+ bail!("providerId and modelId must be nonempty strings together, or both null");
+ }
+ }
+ Ok(())
+}
+
+pub(crate) fn configure_execution(config: &mut Value, input: &Value) {
+ let object = config
+ .as_object_mut()
+ .expect("scheduled task config is an object");
+ if let Some(level) = input.get("thinkingLevel") {
+ if level.is_null() {
+ object.remove("thinkingLevel");
+ } else {
+ object.insert("thinkingLevel".into(), level.clone());
+ }
+ }
+ if let Some(value) = input.get("permissionMode") {
+ if value.is_null() {
+ object.remove("permissionMode");
+ } else if let Some(mode) = value.as_str() {
+ object.insert("permissionMode".into(), json!(mode));
+ }
+ }
+ if input.get("providerId").is_some() || input.get("modelId").is_some() {
+ if input.get("providerId").is_some_and(Value::is_null) {
+ object.remove("providerId");
+ object.remove("modelId");
+ } else {
+ object.insert("providerId".into(), input["providerId"].clone());
+ object.insert("modelId".into(), input["modelId"].clone());
+ }
+ }
+}
+
pub fn configure(config: &mut Value, input: &Value, cadence: &str, now: i64) -> Result<()> {
+ validate_execution_input(input)?;
+ configure_execution(config, input);
if let Some(schedule) = input.get("schedule") {
let previous = config.get("schedule").cloned();
if schedule.is_null() {
diff --git a/docs/adr/0304-scheduled-task-execution-settings.md b/docs/adr/0304-scheduled-task-execution-settings.md
new file mode 100644
index 000000000..1331e47fe
--- /dev/null
+++ b/docs/adr/0304-scheduled-task-execution-settings.md
@@ -0,0 +1,74 @@
+# ADR 0304: Keep scheduled-task execution settings task-owned
+
+- Status: Accepted for implementation
+- Date: 2026-09-22
+- Amends: `scheduled-desktop-automations.md`
+
+## Context
+
+Scheduled tasks already own their prompt, cadence and project binding, but they
+did not own the rest of their execution configuration. Automatic runs always
+used Ask permission mode and resolved the app's current default provider/model
+when each run started. Editing a global default could therefore change an
+unrelated saved task, and the Scheduled form could not move a task to another
+saved project.
+
+The conversation composer already defines the supported permission choices and
+the configured provider/model catalog. Scheduled tasks should use those same
+choices without sharing mutable draft or session state with a conversation or
+another task.
+
+## Decision
+
+Store optional `permissionMode`, `providerId` and `modelId` fields alongside the
+existing `workspacePath` in each task's Host-owned `config_json`. Provider and
+model are an all-or-nothing pair. The Scheduled form uses the same configured
+model filtering, aliases and permission labels as the conversation composer,
+but writes a separate copy to the selected task.
+
+New tasks default to the current project, Ask permission mode and the current
+default provider/model when those values exist. Users may explicitly choose
+another saved project, permission mode or configured model. Both Run now and
+automatic runs create their session from the task-owned values.
+
+Compatibility remains additive:
+
+- a task without `providerId`/`modelId` continues to resolve the app defaults at
+ run time;
+- a legacy automatic task without `permissionMode` continues to use Ask;
+- a legacy manual task without `permissionMode` keeps its previous inherited
+ permission behavior;
+- existing workspace-capture and project-removal rules remain unchanged;
+- an unavailable saved model remains visible and preserved instead of silently
+ changing to another model.
+
+Only the trusted desktop management surface may retarget a task. Conversation
+tools remain scoped to their calling session's project and do not gain project,
+model or permission parameters.
+
+
+Tasks also persist optional `thinkingLevel` using the existing session values
+(including `off` and `omit`). The full Composer model/reasoning picker and
+controller are reused with a task-draft configuration callback. Both manual and
+automatic runs apply the saved level. Missing or cleared levels retain the
+legacy `off` behavior; no database migration is required.
+
+## Consequences
+
+No table migration is required because `config_json` is the existing extension
+boundary. Older versions ignore the additive fields and fall back to their
+previous execution behavior. Selecting Auto is an explicit per-task choice and
+can run restricted actions without waiting for approval; Ask remains the default
+for new and legacy automatic tasks.
+
+The public scheduled-task projection and desktop IPC gain optional fields, so
+Host, shared types, renderer and contract tests must change together.
+
+## Alternatives
+
+Keeping global defaults as the only source was rejected because changing one
+setting can retarget every automation. Adding physical columns was rejected
+because the existing validated JSON boundary already owns optional task
+configuration. Backfilling old rows was rejected because it would turn their
+dynamic default behavior into a fixed selection during upgrade.
+
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 52c6336d4..0f1fb2b4a 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -218,7 +218,7 @@ Each ADR includes:
| 0194 | Optional subagent thinking override | Accepted for implementation |
| 0195 | Viewport-fixed work panel toggle | Accepted (amends 0068 / 0085) |
| 0196 | Show provider retry causes in the active-turn status | Accepted (amends 0175) |
-| 0197 | Publish a Windows Portable Package | Accepted (amends 0022 / D126 / D603) |
+| 0197 | Publish a Windows Portable Executable | Accepted (amends 0022 / D126) |
| 0198 | Name every quiet interval on the live activity row | Accepted (amends 0175 / 0186) |
| 0200 | Host-owned plugin session import and ownership API | Accepted |
| 0201 | Explicit plugin project ids and host-owned session refresh | Accepted |
@@ -330,10 +330,14 @@ Each ADR includes:
| 0299 | [Subagent context budget and delegate compaction](0299-subagent-context-budget.md) | Accepted for implementation (amends ADR 0064; extends ADR 0062 / ADR 0279) |
| 0300 | [Host-owned encrypted portable configuration sync](0300-host-owned-encrypted-portable-configuration-sync.md) | Accepted for implementation |
| 0301 | [Explicit append-only WebDAV compatibility mode](0301-explicit-append-only-webdav-compatibility-mode.md) | Accepted for implementation |
-| 0302 | [A failed compaction keeps the recent window, and an oversized summary is chunked](0302-compaction-fallback-recent-window-and-chunked-summary.md) | Accepted for implementation (issue #827; amends ADR 0049 / ADR 0282) |
-| 0303 | [A skill package carries resources far above the document cap](0303-skill-package-resource-limits.md) | Accepted for implementation (amends ADR 0300) |
+| 0302 | [A failed compaction keeps the recent window, and an oversized summary is chunked](0302-compaction-fallback-recent-window-and-chunked-summary.md) | Accepted for implementation |
+| 0303 | [A skill package carries resources far above the document cap](0303-skill-package-resource-limits.md) | Accepted for implementation |
+| 0304 | [Keep scheduled-task execution settings task-owned](0304-scheduled-task-execution-settings.md) | Accepted for implementation (amends scheduled-desktop-automations) |
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
| provider-display-order | [Provider display order](provider-display-order.md) | Accepted |
| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](registry-header-variable-spelling.md) | Proposed |
| provider-system-certificates | [Desktop sidecar uses OS-trusted certificates](provider-system-certificates.md) | Accepted |
| image-generation-capability | [Image generation as a configured Agent capability](image-generation-capability.md) | Accepted |
+
+
+
diff --git a/docs/adr/scheduled-desktop-automations.md b/docs/adr/scheduled-desktop-automations.md
index da43bbd45..4d8286dac 100644
--- a/docs/adr/scheduled-desktop-automations.md
+++ b/docs/adr/scheduled-desktop-automations.md
@@ -1,6 +1,6 @@
# ADR: Desktop-owned automation dispatch with Host-owned schedules
-- Status: Accepted for implementation
+- Status: Accepted for implementation; amended by ADR 0304
- Date: 2026-09-20
## Context
@@ -27,10 +27,12 @@ Old cadence-only records remain unarmed until explicitly configured. Existing
scheduled.run retains its prepare-only response; additive scheduledExecute IPC
dispatches a turn, and scheduledListRuns exposes the existing run ledger.
-Automatic runs use Ask permission mode. They may wait for a user in their result
-conversation; this feature never grants approval. Plan/Goal rejection remains.
-The default provider/model are resolved at execution time. Retain the task's
-project even when the foreground workspace changes.
+Automatic runs use the task's saved permission mode and default to Ask when the
+field is absent. Ask runs may wait for a user in their result conversation;
+selecting Auto is an explicit per-task choice under ADR 0304. Plan/Goal rejection
+remains. A saved provider/model pair is used when present; otherwise the app
+defaults are resolved at execution time. Retain the task's project even when the
+foreground workspace changes.
Expose Scheduled through a footer clock action as well as global search.
The page has task and run-history views, editing, pause/resume, Run now and
@@ -80,3 +82,4 @@ The UI offers four time periods (09:00, 14:00, 19:00, 22:00) to keep setup
simple. AI tools retain precise local time configuration, and the form preserves
those custom times. Direct database access or renderer-mediated tool mutation
would duplicate ownership or bypass permission gates and is rejected.
+
diff --git a/docs/guide/automations.md b/docs/guide/automations.md
index 159a2298a..7d3f5547b 100644
--- a/docs/guide/automations.md
+++ b/docs/guide/automations.md
@@ -19,9 +19,10 @@ New tasks start in Manual. Choose a recurring cadence to enable automation.
a day. At least one day is required. Choose one of the same four time periods.
- **Manual:** run only when you select Run now.
-Daily and weekly schedules use the computer's local timezone. The current project is saved
-when you first configure a schedule. Runs use the current default model; changing
-the foreground project does not move an existing automation.
+Daily and weekly schedules use the computer's local timezone. Choose the project,
+permission mode and model in the task form. These choices are saved only for that
+task, so changing another task or the app default does not retarget it. Auto can
+run restricted actions without asking; use it only for tasks you trust.
Keep PI-Desktop running. Quitting the app stops scheduling. Missed occurrences
are skipped; startup never launches a backlog. A task does not overlap its own
@@ -31,8 +32,9 @@ the turn using the normal conversation controls.
**Run history** shows the latest 100 runs. **Run now** executes immediately and
opens this history view; **Open conversation** opens the result transcript.
-Automatic runs use Ask permission mode and never approve restricted operations
-for you. Review prompts and the configured provider's cost before enabling tasks.
+New tasks start with Ask permission mode and the current default model selected.
+Existing tasks created before these selectors keep their previous behavior until
+you change them. Review prompts and the configured provider's cost before enabling tasks.
Existing tasks remain manual until you edit them and explicitly save a schedule.
Plan and Goal tasks cannot run unattended. No OS background service, cloud
@@ -41,7 +43,7 @@ scheduler or cron-expression support is installed.
## Release note (unreleased)
Scheduled tasks now execute while the desktop is running, with hourly intervals and time/weekday
-configuration, editing, pause/resume, a visible clock entry and run history.
+configuration, per-task project/permission/model choices, editing, pause/resume, a visible clock entry and run history.
Existing data stays readable; old cadence-only records do not start automatically.
## Manage tasks in a conversation
@@ -55,3 +57,9 @@ cannot use these tools. Tasks from another project are not visible or writable.
An exact time set by AI appears as Custom in the form. Editing the name or
prompt preserves it; selecting a period explicitly replaces it with that
period's default time.
+
+Tasks also persist optional `thinkingLevel` using the existing session values
+(including `off` and `omit`). The full Composer model/reasoning picker and
+controller are reused with a task-draft configuration callback. Both manual and
+automatic runs apply the saved level. Missing or cleared levels retain the
+legacy `off` behavior; no database migration is required.
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index 7daeb3b9a..82377083d 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -1047,8 +1047,19 @@ behavior. Invalid or empty selections are rejected before mutation. No table
migration is needed. Daily/weekly schedules use the host local timezone; hourly
schedules compute `nextRunAt = now + 3_600_000`, ignoring calendar fields. Absence
of `schedule` leaves legacy tasks unarmed. No physical schema change is made.
-Task wire fields project `schedule`, RFC3339 `nextRunAt` and `workspacePath`.
-See [the automation ADR](../../adr/scheduled-desktop-automations.md).
+Task wire fields project `schedule`, RFC3339 `nextRunAt`, `workspacePath` and the
+optional task-owned `permissionMode` plus paired `providerId`/`modelId` values.
+These additive values stay in `config_json`; no physical migration is required.
+Missing model fields retain run-time app-default resolution. Missing permission
+keeps legacy behavior: Ask for automatic runs and inherited permission for Run now.
+See [the automation ADR](../../adr/scheduled-desktop-automations.md) and
+[ADR 0304](../../adr/0304-scheduled-task-execution-settings.md).
+
+Tasks also persist optional `thinkingLevel` using the existing session values
+(including `off` and `omit`). The full Composer model/reasoning picker and
+controller are reused with a task-draft configuration callback. Both manual and
+automatic runs apply the saved level. Missing or cleared levels retain the
+legacy `off` behavior; no database migration is required.
Scheduled task `config_json.mode` is a durable operating-mode value. There is
intentionally no physical `scheduled_tasks.mode` column. The v7→v8
@@ -1584,3 +1595,4 @@ Hourly rows retain their fields but require explicit calendar confirmation
when converted. Known intent survives cadence changes and database reopen.
This additive JSON key needs no table or schema-version migration. Older
versions ignore the key and cannot enforce the new conversion guard.
+
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 34e823c99..4e485750a 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1212,6 +1212,21 @@ a schedule. Update takes an existing ID and partial fields, preserving all
unspecified configuration. Exact local times remain supported despite the
UI's four period presets. No new DB schema or transport is introduced.
+### Scheduled tasks: task-owned execution settings
+
+Desktop create/update may save `workspacePath`, `permissionMode` and a paired
+`providerId`/`modelId` on one task. Run now and automatic execution use those
+values when present. Missing fields preserve legacy project capture, app-default
+model resolution and permission behavior. Invalid permission values and partial
+model pairs are rejected before mutation. Conversation tools do not expose these
+fields and remain bound to the calling session's project. See ADR 0304.
+
+Tasks also persist optional `thinkingLevel` using the existing session values
+(including `off` and `omit`). The full Composer model/reasoning picker and
+controller are reused with a task-draft configuration callback. Both manual and
+automatic runs apply the saved level. Missing or cleared levels retain the
+legacy `off` behavior; no database migration is required.
+
### Scheduled tasks: independent task dispatch
The Electron runner admits independent due tasks without awaiting another task's prompt setup. Local in-flight ownership is keyed by task ID and Host instance until setup settles; Host remains authoritative for enabled, due and overlap checks. A replaced Host's completion cannot clear its successor's local ownership. Stop prevents new polls; admitted work keeps the existing execution/failure lifecycle. Failures remain observable and the 90-second late policy is unchanged.
@@ -1261,3 +1276,4 @@ notification carrying that same snapshot. Approval and rejection require the
current entity digest, so a security-relevant edit cannot reuse an older local
decision. Disconnect deletes only local credentials, vault keys, metadata and
staging files; remote objects remain intact.
+
diff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.md
index aab53e246..8ac25b7b0 100644
--- a/docs/spec/04-ux/01-ui-ia.md
+++ b/docs/spec/04-ux/01-ui-ia.md
@@ -249,7 +249,7 @@ title, status badge, branch meta, external link, and "Review with agent"
### 3.4 Scheduled
Tasks and Run history views, with an explicit create/edit form, a cadence dropdown, time,
-next occurrence, saved project, pause/resume and delete confirmation. Hourly
+next occurrence, saved project, per-task permission/model selection, pause/resume and delete confirmation. Hourly
schedules repeat at one-hour intervals without a time selector. Daily schedules
use a themed time-period dropdown: Morning 09:00, Afternoon 14:00, Evening
19:00, Night 22:00. The form does not expose hour/minute editing. AI tools may
@@ -269,12 +269,25 @@ occurrences more than 90 seconds late or overlapping a running task. Startup
rearms future occurrences only. Hourly schedules wait a full hour after saving,
enabling, startup or the preceding automatic admission; Run now leaves the
automatic occurrence unchanged. Legacy cadence-only tasks require explicit
-schedule configuration. The current project is captured when first configured;
+schedule configuration. New tasks explicitly save the selected project, Ask
+permission mode and the current default provider/model. Each selector writes only
+to that task. The prompt is labelled Instruction, and these three selectors sit
+inside its bottom toolbar using the same shell, chip and anchored-menu treatment
+as the main Composer. Both surfaces render the same controlled permission picker
+and searchable, provider-grouped model list with capability badges. The task model
+chip displays the model name or alias without a provider prefix. Task selection
+callbacks update only the task draft, never the active conversation or app defaults.
+The instruction input has its own rounded border and tonal
+background above the toolbar, with no native resize handle; longer text scrolls
+inside the input. Existing tasks without provider/model fields continue following the
+app defaults; unavailable saved models remain visible and are not silently replaced.
+Selecting Auto warns that restricted actions may run without asking. The current
+project is captured when first configured when no explicit selection exists;
subsequent foreground project changes do not retarget it. This includes Manual
tasks and tasks saved without a project: Run now, renaming, and cadence changes
preserve that binding, including after restart. Only legacy tasks without a saved
-binding capture the current project on their first explicit configuration. Automatic runs use
-Ask permissions and may wait for input in their conversation.
+binding capture the current project on their first explicit configuration. Legacy automatic
+runs without a saved permission mode use Ask and may wait for input in their conversation.
New tasks default to Agent. A migrated Plan or Goal task is allowed to remain
stored, but an unattended run is explicitly rejected before provider, artifact,
or queue work with `PLAN_REQUIRES_INTERACTIVE_SESSION`; it cannot display or
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index f42874a85..0346f74b6 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -50,9 +50,15 @@
### E2E-SCHEDULED-desktop-automation-lifecycle
+- **Additional coverage:** Shared model/reasoning root menu, searchable model submenu,
+ keyboard model selection, selecting and reopening `high`, unchanged application
+ defaults, and the saved thinking level on the executed session.
+
+
- **Preconditions:** Isolated desktop profile, built task candidate, local SSE
fixture model; no real provider credentials or paid API.
-- **Steps:** Open the footer clock; create a daily Morning task at 09:00; edit its name;
+- **Steps:** Open the footer clock; create a daily Morning task at 09:00; select
+ another saved project, Auto permission and a non-default configured model; edit its name;
select a daily time period from four fixed defaults; open the weekday menu,
select custom days, save and reopen; reject empty days; verify the four defaults,
arrows, Home/End, Enter, Escape/Tab and outside dismissal; select hourly without time
@@ -62,13 +68,18 @@
conversation, use model tool calls to discover, create, list, update to 15:30
and delete a task. Verify the custom time appears in the form and survives
renaming. The model is a local deterministic fixture, not a live provider.
-- **Expected:** Configuration persists, next time is visible, paused tasks do
+- **Expected:** Project, permission and exact provider/model persist on that task,
+ reopen with the same values and reach the sidecar without changing another task.
+ The project, permission and model controls remain inside the Instruction field's
+ Composer-style bottom toolbar, including at the narrow viewport, with no horizontal overflow.
+ Legacy rows without the new fields retain their previous defaults. Configuration
+ persists, next time is visible, paused tasks do
not dispatch, both execution paths reach the real Agent sidecar, history links
to the persisted transcript, and automatic execution does not require a
renderer prompt. Host tests additionally prove duplicate admission rejection,
stale/missed occurrence handling, invalid input rejection and recovery.
- **Specs:** 04-ux/01-ui-ia §3.4; 03-runtime/04-data-storage §4.11;
- ADR scheduled-desktop-automations.
+ ADR scheduled-desktop-automations; ADR 0304.
- **Acceptance:** Scheduled task execution and recoverable run history.
- **Milestone:** Post-MVP desktop automations.
- **Status:** Automated in `node scripts/e2e-scheduled.mjs`; run against the
@@ -14589,3 +14600,4 @@ renderer's durable transcript reads. No real model or provider is contacted.
`node --test apps/desktop/test/plugin-timeout-budgets.test.mjs`,
`pnpm --filter @pi-desktop/shared test`, and
`pnpm --filter @pi-desktop/host-runtime test`.
+
diff --git a/docs/zh-CN/guide/automations.md b/docs/zh-CN/guide/automations.md
index 076ec5bfa..f370e172e 100644
--- a/docs/zh-CN/guide/automations.md
+++ b/docs/zh-CN/guide/automations.md
@@ -15,23 +15,23 @@ description: 配置本地周期任务并查看运行结果。
新任务保留「手动」默认值,明确选择周期后才启用自动执行。
-每天、每周按电脑本地时区执行,首次设置周期时保存当前项目,运行时使用当前默认模型。
-之后切换前台项目不会改变已有任务的项目绑定。
+每天、每周按电脑本地时区执行。可在任务表单中选择项目、权限和模型;这些值只保存到当前
+任务,修改其他任务或应用默认值不会串联影响它。全自动可以不经询问执行受限操作,只应用于可信任务。
请保持 PI-Desktop 运行。退出后不会继续执行,重启不补跑错过的时段,同一任务
不会重叠运行。「暂停」只停止后续触发,不取消当前运行;如需停止,打开对应
会话使用正常的停止按钮。
「运行记录」显示最近 100 次运行。立即运行后进入运行记录,可打开会话查看结果
-或处理授权。自动任务使用 Ask 权限模式,不会自动批准受限操作。启用前请核对
-提示词和所选服务的费用。
+或处理授权。新任务默认使用 Ask 权限和当前默认模型;旧任务在主动修改这些选项前保持
+原有行为。启用前请核对提示词和所选服务的费用。
旧任务只有明确编辑并保存周期后才会自动执行。Plan 和 Goal 模式不支持无人值守
执行。本版不安装后台系统服务,不包含云端调度或 Cron 表达式。
## 更新说明(尚未发布)
-补齐应用运行期间的自动执行、每小时间隔循环、时分设置和星期多选、编辑、暂停/启用、侧边栏
+补齐应用运行期间的自动执行、每小时间隔循环、时分设置、星期多选、任务级项目/权限/模型选择、编辑、暂停/启用、侧边栏
时钟入口和运行记录。旧数据保持兼容,仅设置了周期的旧任务不会自动启动。
## 在对话中管理任务
@@ -42,3 +42,7 @@ Plan/Goal 模式不支持这些工具。不能查看或修改其他项目的
AI 设置的具体时间会在表单中显示为自定义时间。修改名称、提示词时保留它;
只有明确选择某个时段,才替换成该时段的默认时间。
+
+任务还可独立保存 `thinkingLevel`,取值与会话相同(包括 `off` 和 `omit`)。
+模型和推理等级直接复用主对话框的完整选择器及交互逻辑,仅将保存回调接到任务草稿。
+未配置此字段的旧任务仍以 `off` 运行;清空字段恢复旧行为,不需要数据库迁移。
diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.md
index 3e01d233c..87830a11b 100644
--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md
+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md
@@ -891,11 +891,17 @@ CREATE INDEX idx_task_runs ON task_runs(task_id, started_at DESC);
```
生成会话的运行通过 `session_id` 免费获取其转录本。
-`config_json` 保存 `schedule: {hour, minute, weekday}`、毫秒时间戳 `nextRunAt`
-和 `workspacePath`。每天、每周按宿主本地时区计算。每小时采用 `nextRunAt = now + 3_600_000`,
+`config_json` 保存 `schedule: {hour, minute, weekday}`、毫秒时间戳 `nextRunAt`、
+`workspacePath`,以及可选的任务级 `permissionMode` 与成对的 `providerId`/`modelId`。
+这些新增字段无需物理表迁移。缺少模型字段时仍在运行时读取应用默认值;缺少权限字段时,
+自动运行继续使用 Ask,立即运行继续继承全局权限。每天、每周按宿主本地时区计算。每小时采用 `nextRunAt = now + 3_600_000`,
忽略日历时间字段。可选 `weekdays` 保存 1–7 个不重复的 0–6 整数,覆盖每周的旧 `weekday`;
缺失时保留单日语义,空数组、重复或越界值在写入前拒绝。无需表结构迁移。
-无 `schedule` 的旧任务不会自动运行;无需修改表或迁移数据库。
+无 `schedule` 的旧任务不会自动运行;无需修改表或迁移数据库。见 ADR 0304。
+
+任务还可独立保存 `thinkingLevel`,取值与会话相同(包括 `off` 和 `omit`)。
+模型和推理等级直接复用主对话框的完整选择器及交互逻辑,仅将保存回调接到任务草稿。
+未配置此字段的旧任务仍以 `off` 运行;清空字段恢复旧行为,不需要数据库迁移。
计划任务 `config_json.mode` 是持久操作模式值。有
故意没有物理 `scheduled_tasks.mode` 列。 v7→v8
@@ -1331,3 +1337,4 @@ preference does not rewrite provider configuration or require a schema migration
schedule 就推断为日历配置;旧版 Hourly 行保留字段,但转换时需要明确确认日历时间。
已知意图在周期切换和数据库重开后仍然保留。该新增 JSON 字段不需要表或 schema
版本迁移;旧版本会忽略它,也无法执行新的转换保护。
+
diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
index a088f1a6b..bc92c41d1 100644
--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md
@@ -987,6 +987,17 @@ Host 重新检查会话的持久化模式,按调用会话的项目限制访问
每天/每周自动任务需 schedule。修改使用已存在的 ID 并保留未指定字段。界面虽只提供四个
时段,工具仍支持具体本地时间。不新增数据库 schema 或传输协议。
+### 定时任务:任务级执行设置
+
+桌面端 create/update 可为单个任务保存 `workspacePath`、`permissionMode` 和成对的
+`providerId`/`modelId`。立即运行与自动运行在字段存在时均使用这些值;字段缺失时保留旧版
+项目捕获、应用默认模型和权限行为。非法权限与不完整模型组合在写入前拒绝。对话工具不暴露
+这些字段,仍限制在调用会话所属项目。见 ADR 0304。
+
+任务还可独立保存 `thinkingLevel`,取值与会话相同(包括 `off` 和 `omit`)。
+模型和推理等级直接复用主对话框的完整选择器及交互逻辑,仅将保存回调接到任务草稿。
+未配置此字段的旧任务仍以 `off` 运行;清空字段恢复旧行为,不需要数据库迁移。
+
### 定时任务:独立分发到期任务
Electron runner 无需等待其他任务的提示词准备完成,即可准入彼此独立的到期任务。
@@ -1019,3 +1030,4 @@ schedule,Manual 转 Hourly 继续使用现有默认间隔行为。
保存和读取工作区绑定时统一使用现有项目路径规范化规则。在 Windows 上,
斜杠方向、大小写、末尾分隔符和扩展路径前缀的差异不会再让同项目会话看不到任务。
缺失的旧版绑定与显式 null 仍保持不同语义;其他项目的工具不能查询或修改绑定任务。
+
diff --git a/docs/zh-CN/spec/04-ux/01-ui-ia.md b/docs/zh-CN/spec/04-ux/01-ui-ia.md
index 2c8a5a213..4e7c68a06 100644
--- a/docs/zh-CN/spec/04-ux/01-ui-ia.md
+++ b/docs/zh-CN/spec/04-ux/01-ui-ia.md
@@ -209,7 +209,7 @@
(创建聊天回合)。需要活动工作区和 `gh`。
### 3. 4 预定
-任务与运行记录两个视图,支持创建、编辑、暂停、启用和确认删除。周期保留下拉选择,并与时分统一为自定义主题菜单。每小时按一小时间隔执行,不显示时间选择;保存、启用、启动或上次自动准入后重新计时。
+任务与运行记录两个视图,支持创建、编辑、暂停、启用和确认删除。表单可为每个任务单独选择项目、权限和模型。周期保留下拉选择,并与时分统一为自定义主题菜单。每小时按一小时间隔执行,不显示时间选择;保存、启用、启动或上次自动准入后重新计时。
每天通过下拉框选择上午 09:00、下午 14:00、晚上 19:00、夜间 22:00;
界面不提供时分编辑,AI 可设置具体时间,非预设值显示为自定义时间,其他字段的编辑不得覆盖它。每周通过独立下拉面板多选周一至周日,
右侧显示选中标记,不提供快捷组合。至少选择一天才能保存。支持方向键、Home/End、Enter/Space
@@ -219,12 +219,12 @@
结果会话查看真实记录或处理授权。显示最近 100 次运行的运行中、完成、失败、中断状态。
应用必须保持运行。每 30 秒检查一次,超过 90 秒的错过时段与重叠运行被跳过;
-重启只安排未来时段。旧任务需明确保存周期后才自动执行。首次设置时保存当前项目,
+重启只安排未来时段。旧任务需明确保存周期后才自动执行。新任务保存所选项目、Ask 权限和当前默认 provider/model;这些值只属于当前任务。任务文本标为“指令”,项目、权限和模型选择器嵌在指令框底部,并复用主 Composer 的容器、芯片和锚定菜单样式。两处直接共用权限选择组件和支持搜索、服务商分组、能力标记的模型列表。任务的模型按钮只显示模型名或别名,不拼接服务商名称;选择结果只更新任务草稿,不更改当前对话或应用默认设置。指令输入区域使用独立圆角边框及与底栏不同的底色,不显示原生缩放手柄,长文本在输入区内滚动。缺少模型字段的旧任务继续跟随应用默认值,已保存但不可用的模型保留显示且不会被静默替换。选择 Auto 时明确提示受限操作可能无需询问。没有显式选择时,首次设置仍保存当前项目,
前台项目切换不会改变绑定。
Manual tasks, including tasks saved without a project, retain that binding across
Run now, renaming, cadence changes, and restart. Only legacy tasks without a
saved binding capture the current project on their first explicit configuration.
-自动执行使用 Ask 权限模式,不自动授权或抢占当前页面。
+缺少已存权限字段的旧自动任务仍使用 Ask,不自动抢占当前页面。
新任务默认为 Agent。允许保留已迁移的 Plan 或 Goal 任务
已存储,但在提供商、工件之前明确拒绝无人值守的运行,
或使用 `PLAN_REQUIRES_INTERACTIVE_SESSION` 排队工作;它无法显示或
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.md
index 11380db7d..78002e77a 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
@@ -8359,19 +8359,22 @@ the latest destination. These assertions measure work counts, not device FPS.
### E2E-SCHEDULED-desktop-automation-lifecycle
+- **补充覆盖:** 共用模型/推理等级首层菜单、可搜索模型子菜单、键盘选择、保存重开 `high`、应用默认设置不变,以及运行会话中的已存推理等级。
+
+
- **前提:** 独立桌面配置、构建后的任务候选版本、本地 SSE 模拟模型;不使用真实
服务凭据或付费 API。
-- **步骤:** 点击页脚时钟;创建每天上午 09:00 的任务;编辑名称;暂停/启用;立即运行;
+- **步骤:** 点击页脚时钟;创建每天上午 09:00 的任务;选择另一个已保存项目、Auto 权限和非默认模型;编辑名称;暂停/启用;立即运行;
打开结果会话;验证周期/四个时段主题下拉菜单、星期多选及选中标记、保存回显、空选择与固定时间;
验证方向键、Home/End、Enter、Escape/Tab 和外部点击关闭;
验证每小时无时间输入且首次等待一小时;设置每天任务在下一个真实分钟执行;
观察自动完成;删除已结束的任务。普通 Agent 对话经模型工具调用发现、创建、查询、
修改任务到 15:30,再删除;验证页面显示具体时间,改名保存不覆盖。模型为本地确定性夹具。
-- **预期:** 配置持久化并显示下次时间;暂停后不触发;手动与自动入口均调用真实
+- **预期:** 项目、权限和精确 provider/model 只保存在该任务,重新打开仍显示相同值并实际传到 sidecar,其他任务不受影响;项目、权限和模型控件保持嵌在“指令”框的 Composer 风格底栏中,窄窗口也不产生横向溢出;缺少新增字段的旧记录保持原默认行为。配置持久化并显示下次时间;暂停后不触发;手动与自动入口均调用真实
Agent sidecar;历史记录链接到持久化会话;自动执行不依赖渲染器发送提示词。
宿主测试补充验证重复准入、错过时段、无效输入和重启恢复。
- **规格:** 04-ux/01-ui-ia §3.4;03-runtime/04-data-storage §4.11;
- ADR scheduled-desktop-automations。
+ ADR scheduled-desktop-automations;ADR 0304。
- **验收:** 定时执行与可恢复的运行历史。
- **里程碑:** MVP 后的桌面自动化。
- **状态:** `node scripts/e2e-scheduled.mjs` 自动化覆盖;按 AGENTS.md 在任务候选
@@ -8694,3 +8697,4 @@ the latest destination. These assertions measure work counts, not device FPS.
`node --test apps/desktop/test/session-transcript-empty-read.test.mjs`、
`node --test apps/desktop/test/plugin-timeout-budgets.test.mjs`、
`pnpm --filter @pi-desktop/shared test`、`pnpm --filter @pi-desktop/host-runtime test`。
+
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 0f2eecaea..a0b71c87a 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -1538,8 +1538,11 @@ sklm: {
"legacyHint": "Zeitplan bearbeiten und speichern, um automatische Ausführungen zu aktivieren.",
"time": "Uhrzeit",
"weekday": "Wochentag",
- "localTimeHint": "Verwendet die lokale Zeitzone. PI-Desktop muss geöffnet bleiben; verpasste Ausführungen werden übersprungen. Eingeschränkte Aktionen erfordern eine Genehmigung.",
+ "localTimeHint": "Verwendet die lokale Zeitzone. PI-Desktop muss geöffnet bleiben; verpasste Ausführungen werden übersprungen.",
"projectHint": "Das aktuelle Projekt wird gespeichert. Ausführungen verwenden das Standardmodell.",
+ "executionSettingsHint": "Projekt, Berechtigungsmodus und Modell werden nur für diese Aufgabe gespeichert.",
+ "autoPermissionHint": "Auto kann eingeschränkte Aktionen ohne Nachfrage ausführen. Verwenden Sie es nur für vertrauenswürdige Aufgaben.",
+ "unavailableModel": "{{provider}} / {{model}} (nicht verfügbar)",
"save": "Aufgabe speichern",
"cancel": "Abbrechen",
"runs": "Ausführungsverlauf",
@@ -1560,7 +1563,7 @@ sklm: {
"title": "Geplant",
"emptyTitle": "Keine geplanten Aufgaben",
"create": "Aufgabe erstellen",
- "prompt": "Eingabeaufforderung",
+ "prompt": "Anweisung",
"promptPlaceholder": "z.B. Fassen Sie jeden Morgen den Git-Status und offene Probleme zusammen.",
"cadence": "Kadenz",
"cadenceManual": "Manuell",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 9423e4605..f2eb08cd5 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -1557,8 +1557,11 @@ sklm: {
legacyHint: "Edit and save a schedule to enable automatic runs.",
time: "Time",
weekday: "Day of the week",
- localTimeHint: "Uses this computer’s local timezone. Keep PI-Desktop running; missed runs are skipped. Automatic runs ask before restricted actions.",
+ localTimeHint: "Uses this computer’s local timezone. Keep PI-Desktop running; missed runs are skipped.",
projectHint: "The current project is saved with this schedule. Runs use the default model.",
+ executionSettingsHint: "Project, permission mode, and model are saved only for this task.",
+ autoPermissionHint: "Auto can run restricted actions without asking. Use it only for tasks you trust.",
+ unavailableModel: "{{provider}} / {{model}} (unavailable)",
save: "Save task",
cancel: "Cancel",
runs: "Run history",
@@ -1579,7 +1582,7 @@ sklm: {
title: "Scheduled",
emptyTitle: "No scheduled tasks",
create: "Create task",
- prompt: "Prompt",
+ prompt: "Instruction",
promptPlaceholder: "e.g. Summarize git status and open issues every morning",
cadence: "Cadence",
cadenceManual: "Manual",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 8d504fb8b..797b77947 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -1538,8 +1538,11 @@ sklm: {
"legacyHint": "Edita y guarda la programación para activar las ejecuciones automáticas.",
"time": "Hora",
"weekday": "Día de la semana",
- "localTimeHint": "Usa la zona horaria local. Mantén PI-Desktop abierto; las ejecuciones omitidas no se recuperan. Las acciones restringidas requieren autorización.",
+ "localTimeHint": "Usa la zona horaria local. Mantén PI-Desktop abierto; las ejecuciones omitidas no se recuperan.",
"projectHint": "Se guarda el proyecto actual. Se utiliza el modelo predeterminado.",
+ "executionSettingsHint": "El proyecto, el modo de permisos y el modelo se guardan solo para esta tarea.",
+ "autoPermissionHint": "El modo automático puede ejecutar acciones restringidas sin preguntar. Úsalo solo para tareas de confianza.",
+ "unavailableModel": "{{provider}} / {{model}} (no disponible)",
"save": "Guardar tarea",
"cancel": "Cancelar",
"runs": "Historial",
@@ -1560,7 +1563,7 @@ sklm: {
"title": "Programado",
"emptyTitle": "No hay tareas programadas",
"create": "Crear tarea",
- "prompt": "Mensaje",
+ "prompt": "Instrucción",
"promptPlaceholder": "p.e. Resumir el estado de git y los problemas abiertos cada mañana",
"cadence": "Cadencia",
"cadenceManual": "Manual",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 0dfb1a3b5..5113d15d5 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -1538,8 +1538,11 @@ sklm: {
"legacyHint": "Modifiez et enregistrez la planification pour activer les exécutions automatiques.",
"time": "Heure",
"weekday": "Jour de la semaine",
- "localTimeHint": "Utilise le fuseau horaire local. Gardez PI-Desktop ouvert ; les exécutions manquées sont ignorées. Les actions restreintes nécessitent une autorisation.",
+ "localTimeHint": "Utilise le fuseau horaire local. Gardez PI-Desktop ouvert ; les exécutions manquées sont ignorées.",
"projectHint": "Le projet actuel est enregistré. Le modèle par défaut est utilisé.",
+ "executionSettingsHint": "Le projet, le mode d’autorisation et le modèle sont enregistrés uniquement pour cette tâche.",
+ "autoPermissionHint": "Le mode Auto peut exécuter des actions restreintes sans confirmation. Utilisez-le uniquement pour des tâches fiables.",
+ "unavailableModel": "{{provider}} / {{model}} (indisponible)",
"save": "Enregistrer la tâche",
"cancel": "Annuler",
"runs": "Historique",
@@ -1560,7 +1563,7 @@ sklm: {
"title": "Planifié",
"emptyTitle": "Aucune tâche planifiée",
"create": "Créer une tâche",
- "prompt": "Invite",
+ "prompt": "Instruction",
"promptPlaceholder": "par ex. Résumez l'état de git et les problèmes ouverts chaque matin",
"cadence": "Cadence",
"cadenceManual": "Manuel",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 55a78d048..5172928a3 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -1554,8 +1554,11 @@ sklm: {
legacyHint: "자동 실행을 활성화하려면 일정을 편집하고 저장하세요.",
time: "시간",
weekday: "요일",
- localTimeHint: "컴퓨터의 현지 시간대를 사용합니다. 앱을 실행 상태로 유지하세요. 놓친 실행은 건너뛰며 제한된 작업은 승인이 필요합니다.",
+ localTimeHint: "컴퓨터의 현지 시간대를 사용합니다. 앱을 실행 상태로 유지하세요. 놓친 실행은 건너뜁니다.",
projectHint: "현재 프로젝트를 저장하고 기본 모델로 실행합니다.",
+ executionSettingsHint: "프로젝트, 권한 모드, 모델은 이 작업에만 저장됩니다.",
+ autoPermissionHint: "자동 모드는 묻지 않고 제한된 작업을 실행할 수 있습니다. 신뢰하는 작업에만 사용하세요.",
+ unavailableModel: "{{provider}} / {{model}} (현재 사용할 수 없음)",
save: "작업 저장",
cancel: "취소",
runs: "실행 기록",
@@ -1576,7 +1579,7 @@ sklm: {
title: "예약됨",
emptyTitle: "예약된 작업 없음",
create: "작업 만들기",
- prompt: "프롬프트",
+ prompt: "지시사항",
promptPlaceholder: "예: 매일 아침 git status와 열린 이슈 요약",
cadence: "반복 주기",
cadenceManual: "수동",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index ccd90c65f..6945f3690 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -1544,8 +1544,11 @@ sklm: {
legacyHint: "Otomatik çalıştırmayı etkinleştirmek için programı düzenleyip kaydedin.",
time: "Saat",
weekday: "Haftanın günü",
- localTimeHint: "Yerel saat dilimini kullanır. PI-Desktop açık kalmalıdır; kaçırılan çalıştırmalar atlanır. Kısıtlı işlemler izin gerektirir.",
+ localTimeHint: "Yerel saat dilimini kullanır. PI-Desktop açık kalmalıdır; kaçırılan çalıştırmalar atlanır.",
projectHint: "Geçerli proje kaydedilir. Varsayılan model kullanılır.",
+ executionSettingsHint: "Proje, izin modu ve model yalnızca bu görev için kaydedilir.",
+ autoPermissionHint: "Otomatik mod, kısıtlı işlemleri sormadan çalıştırabilir. Yalnızca güvendiğiniz görevlerde kullanın.",
+ unavailableModel: "{{provider}} / {{model}} (kullanılamıyor)",
save: "Görevi kaydet",
cancel: "İptal",
runs: "Çalıştırma geçmişi",
@@ -1566,7 +1569,7 @@ sklm: {
title: "Zamanlanmış",
emptyTitle: "Zamanlanmış görev yok",
create: "Görev oluştur",
- prompt: "İstem",
+ prompt: "Talimat",
promptPlaceholder: "örn. Her sabah git durumunu ve açık konuları özetle",
cadence: "Sıklık",
cadenceManual: "Elle",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index f63a6ed77..8c86df932 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -1523,8 +1523,11 @@ sklm: {
legacyHint: "请编辑并保存执行周期,以启用自动执行。",
time: "执行时间",
weekday: "星期",
- localTimeHint: "按电脑本地时区执行。请保持 PI-Desktop 运行;错过的任务不补跑。受限操作仍需授权。",
+ localTimeHint: "按电脑本地时区执行。请保持 PI-Desktop 运行;错过的任务不补跑。",
projectHint: "保存时绑定当前项目,执行时使用默认模型。",
+ executionSettingsHint: "项目、权限和模型只保存到当前任务,不会影响其他任务。",
+ autoPermissionHint: "全自动可在无人确认时执行受限操作,请只用于可信任务。",
+ unavailableModel: "{{provider}} / {{model}}(当前不可用)",
save: "保存任务",
cancel: "取消",
runs: "运行记录",
@@ -1545,7 +1548,7 @@ sklm: {
title: "定时任务",
emptyTitle: "暂无已安排任务",
create: "创建任务",
- prompt: "提示词",
+ prompt: "指令",
promptPlaceholder: "例如:每天早上总结 git 状态和未处理的 issue",
cadence: "周期",
cadenceManual: "手动",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 693177d71..6c3c55bff 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -1523,8 +1523,11 @@ sklm: {
legacyHint: "請編輯並儲存執行週期,以啟用自動執行。",
time: "執行時間",
weekday: "星期",
- localTimeHint: "依電腦本地時區執行。請保持 PI-Desktop 執行;錯過的任務不補跑。受限操作仍需授權。",
+ localTimeHint: "依電腦本地時區執行。請保持 PI-Desktop 執行;錯過的任務不補跑。",
projectHint: "儲存時綁定目前專案,執行時使用預設模型。",
+ executionSettingsHint: "專案、權限和模型只儲存到目前任務,不會影響其他任務。",
+ autoPermissionHint: "全自動可在無人確認時執行受限操作,請只用於可信任務。",
+ unavailableModel: "{{provider}} / {{model}}(目前無法使用)",
save: "儲存任務",
cancel: "取消",
runs: "執行記錄",
@@ -1545,7 +1548,7 @@ sklm: {
title: "已安排",
emptyTitle: "暫無已安排任務",
create: "建立任務",
- prompt: "提示詞",
+ prompt: "指令",
promptPlaceholder: "例如:每天早上總結 git 狀態和未處理的 issue",
cadence: "週期",
cadenceManual: "手動",
diff --git a/packages/shared/src/protocol.test.ts b/packages/shared/src/protocol.test.ts
index 7f9175def..bdd009095 100644
--- a/packages/shared/src/protocol.test.ts
+++ b/packages/shared/src/protocol.test.ts
@@ -120,10 +120,22 @@ describe("Plan protocol contracts", () => {
cadence: "manual",
mode: normalizeMode("chat"),
enabled: true,
+ permissionMode: "accept-edits",
+ thinkingLevel: "high",
+ providerId: "provider-1",
+ modelId: "model-1",
+ workspacePath: "C:/work/project",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
expect(task.mode).toBe("plan");
+ expect(task).toMatchObject({
+ permissionMode: "accept-edits",
+ thinkingLevel: "high",
+ providerId: "provider-1",
+ modelId: "model-1",
+ workspacePath: "C:/work/project",
+ });
});
it("keeps approval actions and target permission modes typed", () => {
diff --git a/packages/shared/src/types/platform.ts b/packages/shared/src/types/platform.ts
index ea274969d..0fd4e5455 100644
--- a/packages/shared/src/types/platform.ts
+++ b/packages/shared/src/types/platform.ts
@@ -1,5 +1,7 @@
/** Shared public types grouped by the owning application domain. */
import type { Mode } from "./common.js";
+import type { GlobalPermissionMode } from "./permissions.js";
+import type { SessionThinkingLevel } from "./models.js";
export type AppVersionInfo = {
name: string;
@@ -112,4 +114,9 @@ export type ScheduledTask = {
schedule?: ScheduledTaskSchedule | null;
nextRunAt?: string;
workspacePath?: string;
+ /** Explicit task-owned execution settings. Missing fields preserve legacy behavior. */
+ permissionMode?: GlobalPermissionMode;
+ thinkingLevel?: SessionThinkingLevel;
+ providerId?: string;
+ modelId?: string;
};
diff --git a/scripts/e2e-scheduled.mjs b/scripts/e2e-scheduled.mjs
index 37ad854c4..cdc0bad0d 100644
--- a/scripts/e2e-scheduled.mjs
+++ b/scripts/e2e-scheduled.mjs
@@ -14,8 +14,10 @@ import { scheduledModelFixture } from "./e2e/scheduled-model.mjs";
const root = mkdtempSync(join(tmpdir(), "pi-scheduled-e2e-"));
const dataDir = join(root, "data"),
- project = join(root, "project");
+ project = join(root, "project"),
+ alternateProject = join(root, "project-alt");
mkdirSync(project);
+mkdirSync(alternateProject);
// The Host canonicalizes the workspace path it is given, and macOS hands out
// `TMPDIR` under the `/var` symlink, so compare resolved paths on both sides.
const canonical = (value) => realpathSync(value).replaceAll("\\", "/").toLowerCase();
@@ -37,6 +39,23 @@ const { provider } = await host.call("providers.create", {
defaultModelId: "fixture",
apiStyle: "chat_completions",
});
+const { provider: alternateProvider } = await host.call("providers.create", {
+ name: "Scheduled alternate model",
+ vendorKey: "custom",
+ type: "openai_compatible",
+ protocol: "openai_compatible",
+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`,
+ authKind: "none",
+ defaultModelId: "fixture-alt",
+ models: [{ id: "fixture-alt", contextWindow: 128000, maxTokens: 8192,
+ thinkingLevels: ["off", "low", "high"], defaultThinkingLevel: "off" }],
+ apiStyle: "chat_completions",
+});
+await host.call("session.create", {
+ title: "Alternate project seed",
+ mode: "agent",
+ projectPath: alternateProject,
+});
await host.call("settings.set", {
language: "en",
defaultProviderId: provider.id,
@@ -209,6 +228,36 @@ try {
await fill("form textarea", "Summarize the current project status.");
assert.equal(await evaluate(`document.querySelector('button[aria-label="Cadence"]').textContent.trim()`), "Manual");
await choose("Cadence", "Daily");
+ await choose("Select project", "project-alt");
+ await click("Permission mode", "button[aria-haspopup]", true);
+ await waitFor(() => evaluate(`!!document.querySelector('.composer-permission-menu.is-open')`), 5000, "shared permission menu");
+ await click("Auto", '.composer-permission-menu [role="menuitemradio"]');
+ assert.ok(await evaluate(`document.body.innerText.includes('Auto can run restricted actions')`));
+ await click(await evaluate(`document.querySelector('.scheduled-execution-toolbar .composer-model-thinking-chip').getAttribute('aria-label')`), 'button[aria-haspopup]', true);
+ await waitFor(() => evaluate(`!!document.querySelector('.composer-model-menu.is-open .composer-menu-root')`), 5000, "measured root menu");
+ await evaluate(`document.querySelector('.composer-menu-root .composer-menu-entry').click()`);
+ await waitFor(() => evaluate(`document.activeElement?.getAttribute('aria-label') === 'Search models'`), 5000, "model search focus");
+ await fill('.composer-model-search input', 'fixture-alt');
+ await waitFor(() => evaluate(`document.querySelectorAll('.composer-model-option').length === 1`), 5000, "filtered model");
+ await key("ArrowDown", 40);
+ await key("Enter", 13);
+ await waitFor(() => evaluate(`!!document.querySelector('.composer-menu-root')`), 5000, "task model selection returns to root");
+ await evaluate(`[...document.querySelectorAll('.composer-menu-entry')].find(e => e.textContent.includes('Reasoning')).click()`);
+ await click("high", '.composer-thinking-list [role="menuitemradio"]');
+ await key("Escape", 27);
+ const unchangedDefaults = await invoke("settingsGet");
+ assert.equal(unchangedDefaults.defaultProviderId, provider.id, "task selection cannot change the conversation default provider");
+ assert.equal(unchangedDefaults.defaultModelId, "fixture", "task selection cannot change the conversation default model");
+ assert.equal(
+ await evaluate(`document.querySelector('.scheduled-instruction-shell > .scheduled-execution-toolbar') !== null`),
+ true,
+ "task execution controls stay inside the instruction composer",
+ );
+ assert.equal(
+ await evaluate(`[...document.querySelectorAll('form label')].some((label) => label.innerText.trim().startsWith('Instruction'))`),
+ true,
+ "the task prompt is presented as an instruction",
+ );
await openSelect("Time");
assert.deepEqual(await evaluate(`[...document.querySelectorAll('[role="option"]')].map(e=>e.textContent.trim())`), ["Morning", "Afternoon", "Evening", "Night"]);
await key("ArrowDown", 40);
@@ -220,6 +269,33 @@ try {
}
assert.equal(await evaluate(`document.querySelectorAll('form input[type="number"],form input[type="time"]').length`),0);
await screenshot("after-editor.png");
+ const previousTheme = await evaluate(`document.documentElement.dataset.theme`);
+ await evaluate(`document.documentElement.dataset.theme = 'dark'`);
+ await waitFor(() => evaluate(`getComputedStyle(document.querySelector('.scheduled-instruction-input')).resize === 'none'`), 5000, "instruction resize disabled");
+ assert.equal(await evaluate(`(() => {
+ const input = document.querySelector('.scheduled-instruction-input');
+ const style = getComputedStyle(input);
+ return style.backgroundColor !== 'rgba(0, 0, 0, 0)' &&
+ style.backgroundColor !== getComputedStyle(input.parentElement).backgroundColor &&
+ parseFloat(style.borderBottomWidth) > 0 &&
+ getComputedStyle(input, '::placeholder').opacity === '1';
+ })()`), true, "instruction has its own background, border and visible placeholder");
+ await screenshot("after-editor-dark.png");
+ await evaluate(`document.documentElement.dataset.theme = ${JSON.stringify(previousTheme)}`);
+ await send("Emulation.setDeviceMetricsOverride", {
+ width: 760,
+ height: 800,
+ deviceScaleFactor: 1,
+ mobile: false,
+ });
+ await waitFor(() => evaluate(`window.innerWidth <= 780`), 5000, "narrow scheduled editor");
+ assert.equal(
+ await evaluate(`document.documentElement.scrollWidth <= document.documentElement.clientWidth`),
+ true,
+ );
+ await screenshot("after-editor-narrow.png");
+ await send("Emulation.clearDeviceMetricsOverride");
+ await waitFor(() => evaluate(`window.innerWidth > 780`), 5000, "wide scheduled editor");
await click("Save task");
let task;
await waitFor(
@@ -233,8 +309,23 @@ try {
assert.equal(task.schedule.minute, 0);
assert.equal(task.schedule.hour, 9);
assert.ok(task.nextRunAt);
- assert.equal(canonical(task.workspacePath), canonical(project));
+ assert.equal(canonical(task.workspacePath), canonical(alternateProject));
+ assert.equal(task.permissionMode, "auto");
+ assert.equal(task.providerId, alternateProvider.id);
+ assert.equal(task.modelId, "fixture-alt");
+ assert.equal(task.thinkingLevel, "high");
await click("Edit task");
+ assert.equal(await evaluate(`document.querySelector('button[aria-label="Select project"]').textContent.trim()`), "project-alt");
+ assert.equal(await evaluate(`document.querySelector('button[aria-label="Permission mode"]').textContent.trim()`), "Auto");
+ assert.equal(await evaluate(`document.querySelector('.scheduled-execution-toolbar .composer-model-thinking-model').textContent.trim()`), "fixture-alt");
+ assert.equal(await evaluate(`document.querySelector('.scheduled-execution-toolbar .composer-model-thinking-level').textContent.trim()`), "high");
+ await click(await evaluate(`document.querySelector('.scheduled-execution-toolbar .composer-model-thinking-chip').getAttribute('aria-label')`), 'button[aria-haspopup]', true);
+ await waitFor(() => evaluate(`!!document.querySelector('.composer-model-menu.is-open')`), 5000, "composer model menu");
+ await screenshot("after-model-menu.png");
+ await evaluate(`document.querySelector('.composer-menu-root .composer-menu-entry').click()`);
+ await waitFor(() => evaluate(`!!document.querySelector('.composer-model-search')`), 5000, "shared model submenu");
+ await screenshot("after-model-search.png");
+ await key("Escape", 27);
await choose("Cadence", "Weekly");
await openSelect("Day of the week");
assert.equal(await evaluate(`document.querySelectorAll('[role="option"]').length`), 7);
@@ -297,7 +388,10 @@ try {
30_000,
"manual run completion",
);
+ const executedSession = await invoke("sessionGet", { id: runs[0].sessionId });
+ assert.equal(executedSession.session.thinkingLevel, "high", "saved thinking level reaches the executed session");
assert.ok(model.calls > 0, "real sidecar reached the local model");
+ assert.ok(model.requestedModels.includes("fixture-alt"), "task-owned model reached the sidecar");
await waitFor(
() => evaluate(`document.body.innerText.includes('Completed')`),
15_000,
diff --git a/scripts/e2e/scheduled-model.mjs b/scripts/e2e/scheduled-model.mjs
index aac2eb197..9651a7de6 100644
--- a/scripts/e2e/scheduled-model.mjs
+++ b/scripts/e2e/scheduled-model.mjs
@@ -7,6 +7,7 @@ export function scheduledModelFixture() {
let taskId;
let pending;
let calls = 0;
+ const requestedModels = [];
const results = [];
const scenarios = {
create: ["ScheduledTaskCreate", "ScheduledTaskList"],
@@ -16,10 +17,19 @@ export function scheduledModelFixture() {
};
const handler = async (req, res) => {
try {
+ if (req.method === "GET" && req.url?.endsWith("/models")) {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({
+ object: "list",
+ data: ["fixture", "fixture-alt"].map((id) => ({ id, object: "model" })),
+ }));
+ return;
+ }
let body = "";
for await (const part of req) body += part;
const request = JSON.parse(body);
calls++;
+ requestedModels.push(request.model);
if (pending) {
const message = request.messages.find((item) => item.role === "tool" && item.tool_call_id === pending.id);
assert.ok(message, `model receives ${pending.name} result`);
@@ -71,6 +81,7 @@ export function scheduledModelFixture() {
return {
handler,
get calls() { return calls; },
+ get requestedModels() { return requestedModels; },
get results() { return results; },
get taskId() { return taskId; },
setScenario(value) { assert.ok(scenarios[value]); scenario = value; step = 0; pending = undefined; },