@runappsai/agent 0.1.11 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chat.d.ts CHANGED
@@ -1,4 +1,6 @@
1
+ import { type FileDialog } from "./dom.js";
1
2
  import { type SelectBox } from "./select.js";
3
+ import { type ScheduleStore, type ScheduleLimits } from "./schedule.js";
2
4
  import { CHAT_PALETTES, type ChatPalette, type ChatVars } from "./chat-theme.js";
3
5
  import { Agent } from "./index.js";
4
6
  import type { ModelProvider, RunAppsClientLike, Workspace, AgentOptions, AgentUI, RunResult } from "./index.js";
@@ -102,6 +104,16 @@ export interface ChatOptions extends Omit<AgentOptions, "workspace"> {
102
104
  * text files go inline. `false` turns the feature off.
103
105
  */
104
106
  attachments?: boolean;
107
+ /**
108
+ * The dialog for picking files (attach, upload, skill zips) and saving
109
+ * them (downloads from the Files panel, the transcript). Default: the
110
+ * RunApps platform's dialog when the page has it (`puter.ui.openFiles` /
111
+ * `saveFile`, from the shim), which offers the user's files and this
112
+ * device; else the browser's own chooser and downloads. An app that
113
+ * loads the shim on first use passes its own; `false` keeps the
114
+ * browser's.
115
+ */
116
+ fileDialog?: FileDialog | false;
105
117
  /** Where attached files are saved in the directory (default `/uploads`). */
106
118
  uploadsDir?: string;
107
119
  /**
@@ -112,6 +124,24 @@ export interface ChatOptions extends Omit<AgentOptions, "workspace"> {
112
124
  * own; `false` hides it, `true` shows it anyway.
113
125
  */
114
126
  webSearch?: boolean;
127
+ /**
128
+ * Scheduled tasks (default off): a *Scheduled* button in the header lists
129
+ * them (add, edit, pause, run now, delete, open a task's conversation),
130
+ * and the agent gets tools to list, add, change and remove them. A task
131
+ * is a prompt run at set times — once, every N minutes, daily at a time
132
+ * (on chosen weekdays), or by cron — in a conversation of its own. They
133
+ * run only while the app is open, each when it is due and the chat is
134
+ * idle (nothing running, no question open, the user not typing); one
135
+ * missed while the page was closed runs once on the next visit. Kept per
136
+ * app in localStorage unless `store` is given. `minMinutes` (default 5)
137
+ * is the shortest repeat, `maxTasks` (default 20) the most tasks;
138
+ * `tools: false` leaves the agent without the tools (the user manages
139
+ * them alone).
140
+ */
141
+ schedule?: boolean | (ScheduleLimits & {
142
+ store?: ScheduleStore;
143
+ tools?: boolean;
144
+ });
115
145
  /**
116
146
  * Called when a link in the conversation (a reply, its thinking, a tool
117
147
  * card) is clicked, before the chat's own handling: return `true` when you
@@ -121,7 +151,16 @@ export interface ChatOptions extends Omit<AgentOptions, "workspace"> {
121
151
  onLink?: (href: string, text: string) => boolean | void;
122
152
  /** A tool card's file path becomes a link that calls this. */
123
153
  onOpenFile?: (path: string) => void;
124
- /** The "Tool permissions" choice in the settings panel (default on). `false` for an app that decides when to ask itself (its own settings, its tools' `confirm`). */
154
+ /**
155
+ * The user's say over tool permissions (default on): an "Always allow
156
+ * (this app)" answer on each permission question, which lets every tool
157
+ * run without asking from then on, and the "Tool permissions" choice in
158
+ * the settings panel, where it is turned off again. The choice is kept per app; the app's `permissions`
159
+ * ("ask" by default, "auto" to start in auto) is what a user who never
160
+ * chose gets. `false` for an app that decides when to ask itself (its own
161
+ * settings, its tools' `confirm`); hidden as well when `permissions` is a
162
+ * function or the chat was given its own `agent`.
163
+ */
125
164
  permissionsSetting?: boolean;
126
165
  /**
127
166
  * Your app's own state to put back on a rewind (an editor's text, a form):
package/dist/chat.js CHANGED
@@ -13,8 +13,9 @@
13
13
  // in the DOM, so a long history costs nothing to open.
14
14
  import { escapeHTML } from "./markdown.js";
15
15
  import { VirtualList } from "./vlist.js";
16
- import { downloadBlob, h, I, modal, modalConfirm, renderMD } from "./dom.js";
16
+ import { chooseFiles, downloadBlob, h, I, modal, modalConfirm, renderMD, setFileDialog } from "./dom.js";
17
17
  import { selectBox, SELECT_CSS } from "./select.js";
18
+ import { Scheduler, scheduleTools, localSchedules, makeTask, changeTask, describeSchedule, formatLocalTime, nextRun, checkSchedule, parseLocalTime } from "./schedule.js";
18
19
  import { DEFAULT_COMPACTION, resolveSettings } from "./compaction.js";
19
20
  import { filesPanel, freePath } from "./files-panel.js";
20
21
  import { debugPanel } from "./debug-panel.js";
@@ -40,7 +41,7 @@ const STRINGS = {
40
41
  attach: "Attach files", drop: "Drop files to attach", tooLarge: "is too large (max 20 MB)", remove: "Remove",
41
42
  toolsRunning: "Running", toolsDone: "Ran {n} tool calls", toolsDone1: "Ran 1 tool call", toolsFailed: "{n} failed",
42
43
  actRead: "read {n} file(s)", actList: "listed {n} folder(s)", actSearch: "searched {n} time(s)", actWrite: "wrote {n} file(s)", actEdit: "edited {n} file(s)", actDelete: "deleted {n} file(s)", actRun: "ran {n} snippet(s)", actAsk: "asked you {n} time(s)", actOther: "used {name}", actWeb: "searched the web {n} time(s)", actBrowse: "read {n} web page(s)", ingWeb: "Searching the web", ingBrowse: "Reading",
43
- web: "Web", webOn: "Web search: on", webOff: "Web search: off", webHint: "When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed",
44
+ web: "Web", webOn: "Web search: on", webOff: "Web search: off", webHint: "When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed", permAlways: "Always allow (this app)", sched: "Scheduled", schedNew: "New task", schedNone: "No scheduled tasks yet. Ask the AI (\"every weekday at 9, summarise the news\") or add one.", schedHint: "Tasks run only while this app is open, and wait until the chat is idle. A run missed while it was closed happens once when you next open it.", schedName: "Name", schedPrompt: "What to do", schedWhen: "When", schedOnce: "Once", schedEvery: "Every", schedDaily: "Daily / weekly", schedCron: "Cron", schedMin: "minutes", schedHour: "hours", schedDay: "days", schedCronHint: "minute hour day month weekday, e.g. 0 9 * * 1-5", schedNext: "Next {time}", schedNoNext: "Will not run again", schedPaused: "Paused", schedRunning: "Running", schedLast: "Last {time} · {status}", schedOk: "done", schedErr: "failed", schedStopped: "stopped", schedRunNow: "Run now", schedPause: "Pause", schedResume: "Resume", schedEdit: "Edit", schedOpen: "Open its conversation", schedDel: "Delete task", schedDelMsg: "Delete \"{name}\"? Its conversation stays.", schedSave: "Save", schedBusy: "Another scheduled task is running; try again when it ends.", schedByAI: "by AI", schedRunHead: "⏰ Scheduled task \"{name}\" · {time}\n(Running unattended: the user may not be watching.)", schedStarted: "Scheduled task \"{name}\" started", schedFailed: "Scheduled task \"{name}\" failed: {error}", schedNamePh: "e.g. Morning news digest", schedPromptPh: "What the AI should do each time. Write it to stand alone: the run does not see this conversation.", schedDayNames: "Sun,Mon,Tue,Wed,Thu,Fri,Sat", tSchedList: "Scheduled tasks", tSchedAdd: "Schedule \"{name}\"", tSchedUpdate: "Change scheduled task", tSchedRemove: "Remove scheduled task", permAutoNote: "Auto-run is on: the AI will no longer ask before deleting, overwriting or publishing. Turn it off in Settings → Tool permissions.",
44
45
  runCode: "Run code", ingRead: "Reading", ingList: "Listing", ingSearch: "Searching", ingWrite: "Writing", ingEdit: "Editing", ingDelete: "Deleting", ingRun: "Running code", ingAsk: "Asking you", ingOther: "Running", current: "Current", jumpEnd: "Jump to the latest",
45
46
  sTabModel: "Model", sTabContext: "Context", sCompact: "When the context is nearly full", sCompactSummary: "Summarise older turns (one extra model call)", sCompactTrim: "Only trim: drop old tool results, then the oldest turns", sCompactAt: "Start when fewer tokens than this are left", sKeepRecent: "Keep this many of the newest tokens word for word", sDefaultN: "Default ({n})", sCompactNote: "{model}: starts with {at} tokens left and keeps about {keep} word for word (capped at 20% / 40% of its {window} window)", sCompactNoteTrim: "{model}: trims with fewer than {at} tokens left (capped at 20% of its {window} window)", autoTrim: "Auto-trim", debug: "Debug", dCalls: "Calls", dRequests: "Requests", dEvents: "Events", dContext: "Context", dTools: "Tools", dClear: "Clear the record", dFilter: "Filter by type",
46
47
  dNoCalls: "No tool calls yet.", dNoRequests: "No model requests yet. Each call to the model is listed here with what was sent and what came back.", dNoEvents: "No events yet.",
@@ -80,7 +81,7 @@ const STRINGS = {
80
81
  attach: "添加附件", drop: "松开即可添加附件", tooLarge: "太大了(最大 20 MB)", remove: "移除",
81
82
  toolsRunning: "正在执行", toolsDone: "执行了 {n} 个工具调用", toolsDone1: "执行了 1 个工具调用", toolsFailed: "{n} 个失败",
82
83
  actRead: "读取了 {n} 个文件", actList: "查看了 {n} 个目录", actSearch: "搜索了 {n} 次", actWrite: "写入了 {n} 个文件", actEdit: "修改了 {n} 个文件", actDelete: "删除了 {n} 个文件", actRun: "运行了 {n} 段代码", actAsk: "询问了你 {n} 次", actOther: "调用了 {name}", actWeb: "联网搜索了 {n} 次", actBrowse: "阅读了 {n} 个网页", ingWeb: "正在联网搜索", ingBrowse: "正在阅读",
83
- web: "联网", webOn: "联网搜索:已开启", webOff: "联网搜索:已关闭", webHint: "开启后 AI 可以搜索和阅读网页,查资料和最新信息;每次搜索、每读一个网页按次计费",
84
+ web: "联网", webOn: "联网搜索:已开启", webOff: "联网搜索:已关闭", webHint: "开启后 AI 可以搜索和阅读网页,查资料和最新信息;每次搜索、每读一个网页按次计费", permAlways: "以后都允许(本应用)", sched: "定时任务", schedNew: "新建", schedNone: "还没有定时任务。可以直接让 AI 安排(比如「每个工作日早上 9 点整理新闻」),或点新建。", schedHint: "定时任务只在本应用页面打开时运行,并等对话空闲时才开始;页面关闭期间错过的,下次打开时补跑一次。", schedName: "名称", schedPrompt: "要做什么", schedWhen: "时间", schedOnce: "一次", schedEvery: "每隔", schedDaily: "每天 / 每周", schedCron: "Cron", schedMin: "分钟", schedHour: "小时", schedDay: "天", schedCronHint: "分 时 日 月 周,如 0 9 * * 1-5", schedNext: "下次 {time}", schedNoNext: "不会再运行", schedPaused: "已暂停", schedRunning: "运行中", schedLast: "上次 {time} · {status}", schedOk: "完成", schedErr: "失败", schedStopped: "已停止", schedRunNow: "立即运行", schedPause: "暂停", schedResume: "恢复", schedEdit: "编辑", schedOpen: "打开它的对话", schedDel: "删除任务", schedDelMsg: "删除「{name}」?它的对话会保留。", schedSave: "保存", schedBusy: "另一个定时任务正在运行,结束后再试。", schedByAI: "AI 创建", schedRunHead: "⏰ 定时任务「{name}」 · {time}\n(无人值守运行:用户可能不在旁边。)", schedStarted: "定时任务「{name}」开始运行", schedFailed: "定时任务「{name}」失败:{error}", schedNamePh: "如:早间新闻摘要", schedPromptPh: "每次运行时 AI 要做的事。写完整:运行时看不到这段对话。", schedDayNames: "日,一,二,三,四,五,六", tSchedList: "查看定时任务", tSchedAdd: "安排定时任务「{name}」", tSchedUpdate: "修改定时任务", tSchedRemove: "删除定时任务", permAutoNote: "已开启自动执行:删除、覆盖、发布等操作也不再询问。可在设置 → 工具权限里关闭。",
84
85
  runCode: "运行代码", ingRead: "正在读取", ingList: "正在查看", ingSearch: "正在搜索", ingWrite: "正在写入", ingEdit: "正在修改", ingDelete: "正在删除", ingRun: "正在运行代码", ingAsk: "正在询问你", ingOther: "正在执行", current: "当前", jumpEnd: "回到最新",
85
86
  sTabModel: "模型", sTabContext: "上下文", sCompact: "上下文快满时", sCompactSummary: "把较早的对话写成摘要(多一次模型调用)", sCompactTrim: "只裁剪:先删旧的工具结果,再删最早的对话", sCompactAt: "剩余少于多少 tokens 时开始", sKeepRecent: "原样保留最近多少 tokens", sDefaultN: "默认({n})", sCompactNote: "{model}:剩余 {at} tokens 时开始,原样保留约 {keep} tokens(最多为上下文 {window} 的 20% / 40%)", sCompactNoteTrim: "{model}:剩余少于 {at} tokens 时裁剪(最多为上下文 {window} 的 20%)", autoTrim: "自动裁剪", debug: "调试", dCalls: "调用", dRequests: "请求", dEvents: "事件", dContext: "上下文", dTools: "工具", dClear: "清空记录", dFilter: "按类型过滤",
86
87
  dNoCalls: "还没有工具调用。", dNoRequests: "还没有模型请求。每次调用模型都会记在这里,包括发了什么、收到什么。", dNoEvents: "还没有事件。",
@@ -169,6 +170,25 @@ const CSS = tokenCSS() + `
169
170
  .ra-skm .ra-mi small{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;white-space:normal;line-height:1.45;margin-top:1px}
170
171
  .ra-skm .ra-skf{padding:8px 8px 4px;margin-top:4px;border-top:1px solid var(--ra-border);font-size:11.5px;color:var(--ra-fg-muted);line-height:1.5}
171
172
  .ra-skm.drop{outline:2px dashed var(--ra-accent);outline-offset:-4px}
173
+ .ra-schm .ra-skb.on{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
174
+ .ra-schm .ra-mi.ra-off .ra-mtt{color:var(--ra-fg-muted)}
175
+ .ra-schm .ra-mi small.ra-bad{color:var(--ra-red)}
176
+ .ra-schm .ra-mi small{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp:none}
177
+ .ra-schf{display:flex;flex-direction:column;gap:10px;padding:6px 8px 6px}
178
+ .ra-schf .ra-schh{font-size:13px;font-weight:600}
179
+ .ra-schf .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
180
+ .ra-chat .ra-schf input:not([type=checkbox]),.ra-chat .ra-schf textarea{font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;padding:6px 10px;min-height:34px;box-sizing:border-box;outline:0;width:100%;margin:0}
181
+ .ra-chat .ra-schf textarea{min-height:88px;resize:vertical;line-height:1.5}
182
+ .ra-chat .ra-schf input:focus,.ra-chat .ra-schf textarea:focus{border-color:var(--ra-accent);box-shadow:0 0 0 3px var(--ra-accent-subtle)}
183
+ .ra-schf .ra-row{display:flex;gap:8px;align-items:center}
184
+ .ra-schf .ra-row>*{flex:1;min-width:0}
185
+ .ra-schf .ra-row.ra-col2{flex-direction:column;align-items:stretch}
186
+ .ra-schf .ra-days{display:flex;gap:4px}
187
+ .ra-chat .ra-schf .ra-days button{flex:1;height:28px;border-radius:6px;border:1px solid var(--ra-border);font-size:12px;color:var(--ra-fg-muted)}
188
+ .ra-chat .ra-schf .ra-days button.on{background:var(--ra-accent-subtle);border-color:transparent;color:var(--ra-accent-fg);font-weight:600}
189
+ .ra-schf .ra-note{font-size:11.5px;color:var(--ra-fg-muted)}
190
+ .ra-schf .ra-note.err{color:var(--ra-red)}
191
+ .ra-schf .ra-btns{display:flex;justify-content:flex-end;gap:6px}
172
192
  .ra-set{padding:10px 12px;display:flex;flex-direction:column;gap:10px;width:min(360px,calc(100% - 24px))}
173
193
  /* The settings panel takes the chat's height under the header (a host may add fields of its own). */
174
194
  .ra-chat .ra-set{max-height:calc(100% - 72px)}
@@ -1020,8 +1040,9 @@ export function renderChat(target, opts) {
1020
1040
  injectStyles();
1021
1041
  const lang = pickLocale(opts.locale);
1022
1042
  const t = STRINGS[lang];
1023
- const { toolSettings, client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, webSearch: webSearchOpt, ...agentOpts } = opts;
1043
+ const { toolSettings, client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, fileDialog: fileDialogOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, webSearch: webSearchOpt, schedule: scheduleOpt, ...agentOpts } = opts;
1024
1044
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
1045
+ setFileDialog(fileDialogOpt);
1025
1046
  const provider = providerOpt ? toProvider(providerOpt) : clientOpt ? toProvider(clientOpt) : givenAgent?.provider ?? null;
1026
1047
  const project = provider?.name ?? agentOpts.appName ?? "app";
1027
1048
  // Shell.
@@ -1086,6 +1107,10 @@ export function renderChat(target, opts) {
1086
1107
  return (n) => { b.textContent = String(n); b.style.display = n ? "" : "none"; btn.title = n ? `${label} · ${n}` : label; };
1087
1108
  };
1088
1109
  const setSkillCount = countBadge(skillsBtn, t.skills);
1110
+ const schedBtn = h("button", "ra-btn ghost");
1111
+ schedBtn.type = "button";
1112
+ schedBtn.innerHTML = I.clock() + `<span>${escapeHTML(t.sched)}</span>`;
1113
+ const setSchedCount = countBadge(schedBtn, t.sched);
1089
1114
  const histBtn = h("button", "ra-btn ghost");
1090
1115
  histBtn.type = "button";
1091
1116
  histBtn.innerHTML = I.hist() + `<span>${escapeHTML(t.history)}</span>`;
@@ -1112,14 +1137,14 @@ export function renderChat(target, opts) {
1112
1137
  setBtn.title = t.settings;
1113
1138
  setBtn.setAttribute("aria-label", t.settings);
1114
1139
  // In a narrow chat the labels fold away and only the icons show: each button keeps its name.
1115
- for (const [btn, label] of [[debugBtn, t.debug], [filesBtn, t.files], [skillsBtn, t.skills], [histBtn, t.history], [newBtn, t.newChat], [clearBtn, t.clearChat]]) {
1140
+ for (const [btn, label] of [[debugBtn, t.debug], [filesBtn, t.files], [skillsBtn, t.skills], [schedBtn, t.sched], [histBtn, t.history], [newBtn, t.newChat], [clearBtn, t.clearChat]]) {
1116
1141
  btn.setAttribute("aria-label", label);
1117
1142
  if (!btn.title)
1118
1143
  btn.title = label;
1119
1144
  }
1120
1145
  for (const el of [...(headerActions ?? []), ...(headerEnd ?? []), ...(composerTop ? [composerTop] : []), ...(emptyState instanceof HTMLElement ? [emptyState] : [])])
1121
1146
  el.classList.add("ra-host");
1122
- head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, histBtn, newBtn, clearBtn, ...(headerActions ?? []), setBtn, ...(headerEnd ?? []));
1147
+ head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, schedBtn, histBtn, newBtn, clearBtn, ...(headerActions ?? []), setBtn, ...(headerEnd ?? []));
1123
1148
  if (title === false)
1124
1149
  head.style.display = "none";
1125
1150
  const log = h("div", "ra-log");
@@ -1245,6 +1270,36 @@ export function renderChat(target, opts) {
1245
1270
  for (const a of live.values())
1246
1271
  applyWeb(a);
1247
1272
  });
1273
+ // 自动执行: every tool runs without asking, turned on from a permission question or the settings; kept per app (the app's `permissions` until the user chooses).
1274
+ const PERM_KEY = `__runapps_agent_chat:${project}:perm`;
1275
+ const permOwn = !givenAgent && typeof agentOpts.permissions !== "function";
1276
+ const permShown = permOwn && permissionsSetting !== false;
1277
+ let permChoice = (() => { if (!permShown)
1278
+ return null; try {
1279
+ const v = localStorage.getItem(PERM_KEY);
1280
+ if (v === "ask" || v === "auto")
1281
+ return v;
1282
+ }
1283
+ catch { /* private mode */ } return null; })();
1284
+ const permAuto = () => (permChoice ?? agentOpts.permissions ?? "ask") === "auto";
1285
+ /** Sets the user's choice (null: back to the app's) on every open session, kept per app. */
1286
+ const setPerm = (p, quiet = false) => {
1287
+ const was = permAuto();
1288
+ permChoice = p;
1289
+ if (permShown) {
1290
+ try {
1291
+ if (p)
1292
+ localStorage.setItem(PERM_KEY, p);
1293
+ else
1294
+ localStorage.removeItem(PERM_KEY);
1295
+ }
1296
+ catch { /* private mode */ }
1297
+ }
1298
+ for (const a of live.values())
1299
+ a.configure({ permissions: p ?? agentOpts.permissions ?? "ask" });
1300
+ if (!quiet && !was && permAuto())
1301
+ ui.notify(t.permAutoNote);
1302
+ };
1248
1303
  left.append(attachBtn, webBtn, ...hostActions, hint);
1249
1304
  bar.append(left, acts);
1250
1305
  box.append(cmds, files, ta, bar, fileInput);
@@ -1297,6 +1352,8 @@ export function renderChat(target, opts) {
1297
1352
  let cmdIndex = 0;
1298
1353
  let cmdFrame = null;
1299
1354
  let unsub = [];
1355
+ /** Run once when the chat is unmounted. */
1356
+ const unmountHooks = [];
1300
1357
  let menu = null;
1301
1358
  let mounted = true;
1302
1359
  // A short chat (a phone held sideways, a small panel) keeps the transcript readable: the composer is compact.
@@ -1352,7 +1409,8 @@ export function renderChat(target, opts) {
1352
1409
  const wake = (id, shown = true) => { const w = waiters.get(id); waiters.delete(id); waiting.delete(id); w?.forEach((f) => f(shown)); };
1353
1410
  /** The chat's dialogs for one session: a question from a session that is not on screen waits until it is (or its run stops). */
1354
1411
  const uiFor = (id) => ({
1355
- confirm: async (title, message, o) => ((await whenCurrent(id, o?.signal)) ? ui.confirm(title, message, o) : false),
1412
+ // A permission question gets "Always allow (this app)", which turns auto-run on (a tool's own `always` keeps its place).
1413
+ confirm: async (title, message, o) => ((await whenCurrent(id, o?.signal)) ? ui.confirm(title, message, o?.permission && permShown && !o.always ? { ...o, always: { label: t.permAlways, onChoose: () => setPerm("auto") } } : o) : false),
1356
1414
  select: async (title, options, o) => ((await whenCurrent(id, o?.signal)) ? ui.select(title, options, o) : null),
1357
1415
  input: async (title, o) => ((await whenCurrent(id, o?.signal)) ? ui.input(title, o) : null),
1358
1416
  notify: (m, l) => ui.notify(m, l),
@@ -1360,7 +1418,7 @@ export function renderChat(target, opts) {
1360
1418
  /** Whether rewinding may restore files: only a directory of the session's own, kept in IndexedDB (not a folder on disk, not shared). */
1361
1419
  const restorable = (a) => !!a.workspace && typeof wsOpt === "function" && !a.workspace.root;
1362
1420
  const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || a.queued.length > 0 || waiting.has(a.id)));
1363
- const titleOfAgent = (a) => { const text = titleOf({ v: 2, id: a.id, messages: a.messages, usage: a.usage, droppedTurns: 0, savedAt: 0 }); return text === UNTITLED ? t.untitled : text.length > 40 ? text.slice(0, 37) + "…" : text; };
1421
+ const titleOfAgent = (a) => { const text = a.title ?? titleOf({ v: 2, id: a.id, messages: a.messages, usage: a.usage, droppedTurns: 0, savedAt: 0 }); return text === UNTITLED ? t.untitled : text.length > 40 ? text.slice(0, 37) + "…" : text; };
1364
1422
  const markBackground = () => histBtn.classList.toggle("ra-bg", background().length > 0);
1365
1423
  /** The Chats count: the conversations, open one included, shown once there is another (redrawn after a run, a switch, a delete). */
1366
1424
  let histTimer = null;
@@ -2519,7 +2577,14 @@ export function renderChat(target, opts) {
2519
2577
  },
2520
2578
  };
2521
2579
  /** Every tool the chat's agents get: the host's, plus the built-in suggestion tool. */
2522
- const chatTools = [...(agentOpts.tools ?? []), ...(nextPrompt ? [nextPromptTool] : [])];
2580
+ // Scheduled tasks: the store, and the agent's tools over it (their cards in the chat's language).
2581
+ const schedCfg = scheduleOpt ? (scheduleOpt === true ? {} : scheduleOpt) : null;
2582
+ const schedStore = schedCfg ? schedCfg.store ?? localSchedules(`__runapps_agent_chat:${project}:schedules`) : null;
2583
+ const schedLabels = { schedule_list: () => t.tSchedList, schedule_add: (a) => t.tSchedAdd.replace("{name}", a.name ?? ""), schedule_update: () => t.tSchedUpdate, schedule_remove: () => t.tSchedRemove };
2584
+ const schedTools = schedStore && schedCfg.tools !== false
2585
+ ? scheduleTools(schedStore, { ...schedCfg, onChange: () => refreshSched() }).map((x) => ({ ...x, display: { ...x.display, icon: I.clock(), label: schedLabels[x.name] } }))
2586
+ : [];
2587
+ const chatTools = [...(agentOpts.tools ?? []), ...(nextPrompt ? [nextPromptTool] : []), ...schedTools];
2523
2588
  const hiddenTools = new Set(chatTools.filter((x) => x.display?.hidden).map((x) => x.name));
2524
2589
  /** Send is there only while idle with something to send (text, a file, context); steer and follow-up only while busy with something to send. */
2525
2590
  const syncSend = () => {
@@ -2722,7 +2787,7 @@ export function renderChat(target, opts) {
2722
2787
  renderFiles();
2723
2788
  ta.focus();
2724
2789
  };
2725
- attachBtn.addEventListener("click", () => fileInput.click());
2790
+ attachBtn.addEventListener("click", () => chooseFiles(fileInput, (picked) => void addFiles(picked)));
2726
2791
  fileInput.addEventListener("change", () => { void addFiles(fileInput.files); fileInput.value = ""; });
2727
2792
  ta.addEventListener("paste", (e) => {
2728
2793
  const items = Array.from(e.clipboardData?.files ?? []);
@@ -2999,7 +3064,6 @@ export function renderChat(target, opts) {
2999
3064
  }
3000
3065
  catch { /* private mode */ } };
3001
3066
  let userSettings = givenAgent ? {} : readSettings();
3002
- let permChoice = null; // not persisted: allowing everything is a per-page decision
3003
3067
  const hasSettings = opts.settings ?? !givenAgent;
3004
3068
  let settingsTab = 0;
3005
3069
  if (!hasSettings)
@@ -3252,7 +3316,7 @@ export function renderChat(target, opts) {
3252
3316
  }
3253
3317
  userSettings = {};
3254
3318
  writeSettings({});
3255
- permChoice = null;
3319
+ setPerm(null, true);
3256
3320
  for (const ag of live.values())
3257
3321
  applyTo(ag, {}, null);
3258
3322
  closeMenu();
@@ -3274,8 +3338,8 @@ export function renderChat(target, opts) {
3274
3338
  }
3275
3339
  if (effortSel.value && !effortSel.disabled)
3276
3340
  next.reasoningEffort = effortSel.value;
3277
- if (perm.value === "ask" || perm.value === "auto")
3278
- permChoice = perm.value;
3341
+ if ((perm.value === "ask" || perm.value === "auto") && perm.value !== (permAuto() ? "auto" : "ask"))
3342
+ setPerm(perm.value);
3279
3343
  const summarize = sumSel.value === "summary";
3280
3344
  if (summarize !== hostCompaction.summarize)
3281
3345
  next.summarize = summarize;
@@ -3396,7 +3460,7 @@ export function renderChat(target, opts) {
3396
3460
  });
3397
3461
  document.addEventListener("click", onDocClick, true);
3398
3462
  function onDocClick(e) { if (e.target?.closest?.(".ra-selp"))
3399
- return; if (menu && !menu.contains(e.target) && !histBtn.contains(e.target) && !setBtn.contains(e.target) && !skillsBtn.contains(e.target) && !useBtn.contains(e.target))
3463
+ return; if (menu && !menu.contains(e.target) && !histBtn.contains(e.target) && !setBtn.contains(e.target) && !skillsBtn.contains(e.target) && !schedBtn.contains(e.target) && !useBtn.contains(e.target))
3400
3464
  closeMenu(); }
3401
3465
  /* --- skills menu --- */
3402
3466
  const skillInput = h("input");
@@ -3457,7 +3521,7 @@ export function renderChat(target, opts) {
3457
3521
  const up = h("button", "ra-btn xs solid");
3458
3522
  up.type = "button";
3459
3523
  up.innerHTML = I.upload(13) + `<span>${escapeHTML(t.uploadZip)}</span>`;
3460
- up.addEventListener("click", () => skillInput.click());
3524
+ up.addEventListener("click", () => chooseFiles(skillInput, (picked) => void installZips(picked)));
3461
3525
  if (!ws.userSkillsDir)
3462
3526
  up.style.display = "none";
3463
3527
  head.append(h("span", "", skills.length ? `${t.skills} · ${skills.length}` : t.skills), up);
@@ -3519,6 +3583,291 @@ export function renderChat(target, opts) {
3519
3583
  mine.addEventListener("drop", (e) => { e.preventDefault(); e.stopPropagation(); mine.classList.remove("drop"); void installZips(e.dataTransfer?.files); });
3520
3584
  };
3521
3585
  skillsBtn.addEventListener("click", () => void openSkills());
3586
+ /* --- scheduled tasks --- */
3587
+ if (!schedStore)
3588
+ schedBtn.style.display = "none";
3589
+ const schedLimits = { minMinutes: schedCfg?.minMinutes, maxTasks: schedCfg?.maxTasks };
3590
+ const dayNames = t.schedDayNames.split(",");
3591
+ const zhWords = /[\u4e00-\u9fff]/.test(t.sched);
3592
+ const fmtShort = (ms) => { const s = formatLocalTime(ms); return s.slice(0, 4) === String(new Date().getFullYear()) ? s.slice(5) : s; };
3593
+ /** Runs one task: in its own conversation (made on its first run), or the one conversation when the chat keeps only one. */
3594
+ const runScheduled = async (task) => {
3595
+ await ready;
3596
+ const text = `${t.schedRunHead.replace("{name}", task.name).replace("{time}", formatLocalTime(Date.now()))}\n\n${task.prompt}`;
3597
+ let a;
3598
+ if (givenAgent || oneChat)
3599
+ a = agent ?? givenAgent;
3600
+ else {
3601
+ const sid = task.session ?? `sched_${task.id}`;
3602
+ if (!task.session) {
3603
+ const cur = await schedStore.get(task.id);
3604
+ if (cur)
3605
+ await schedStore.put({ ...cur, session: sid });
3606
+ }
3607
+ a = agent?.id === sid ? agent : live.get(sid) ?? await makeAgent(sid);
3608
+ if (a !== agent) {
3609
+ await a.ready();
3610
+ live.set(sid, a);
3611
+ watchBackground(a);
3612
+ }
3613
+ }
3614
+ // Its own conversation is named after it (the first message would be the run's header).
3615
+ if (!givenAgent && !oneChat)
3616
+ a.setTitle(`⏰ ${task.name}`);
3617
+ ui.notify(t.schedStarted.replace("{name}", task.name));
3618
+ const r = a === agent ? await promptFromHost(text) : await a.prompt(text);
3619
+ refreshHistCount();
3620
+ if (r.reason === "error" || r.reason === "max_turns")
3621
+ ui.notify(t.schedFailed.replace("{name}", task.name).replace("{error}", r.error?.message ?? r.reason), "warning");
3622
+ return { status: r.reason === "done" ? "ok" : r.reason === "aborted" ? "stopped" : "error", ...(r.error ? { note: r.error.message } : r.reason === "max_turns" ? { note: "turn limit" } : {}), ...(r.usage?.total_cost ? { cost: r.usage.total_cost } : {}) };
3623
+ };
3624
+ /** Idle: nothing running in any conversation, no question open, not switching, the user not typing. */
3625
+ const schedIdle = () => mounted && !switching && !!agent && asked === 0 && waiting.size === 0
3626
+ && ![...live.values()].some((a) => a.busy || a.queued.length > 0)
3627
+ && !(document.activeElement === ta && ta.value.trim());
3628
+ const scheduler = schedStore ? new Scheduler({ store: schedStore, run: runScheduled, idle: schedIdle, lockPrefix: `__runapps_agent_chat:${project}:schedules`, onChange: () => refreshSched() }) : null;
3629
+ if (scheduler) {
3630
+ // Each run that ends is a moment the chat may have become idle: look again.
3631
+ const again = () => setTimeout(() => void scheduler.tick(), 1500);
3632
+ let lastBusy = false;
3633
+ const poll = setInterval(() => { const b = !schedIdle(); if (lastBusy && !b)
3634
+ again(); lastBusy = b; }, 3000);
3635
+ unmountHooks.push(() => { clearInterval(poll); scheduler.stop(); });
3636
+ }
3637
+ let schedView = "list";
3638
+ const refreshSched = () => {
3639
+ if (!schedStore)
3640
+ return;
3641
+ void schedStore.list().then((all) => {
3642
+ setSchedCount(all.filter((x) => x.enabled).length);
3643
+ if (menu?.classList.contains("ra-schm") && schedView === "list")
3644
+ drawSchedList(menu);
3645
+ }).catch(() => undefined);
3646
+ };
3647
+ const openSched = () => {
3648
+ if (menu) {
3649
+ const was = menu.classList.contains("ra-schm");
3650
+ closeMenu();
3651
+ if (was)
3652
+ return;
3653
+ }
3654
+ if (!schedStore)
3655
+ return;
3656
+ const mine = h("div", "ra-menu ra-skm ra-schm");
3657
+ menu = mine;
3658
+ placeMenu(mine);
3659
+ void drawSchedList(mine);
3660
+ };
3661
+ const drawSchedList = async (mine) => {
3662
+ schedView = "list";
3663
+ let all = [];
3664
+ try {
3665
+ all = await schedStore.list();
3666
+ }
3667
+ catch (err) {
3668
+ ui.notify(err.message, "error");
3669
+ }
3670
+ if (menu !== mine)
3671
+ return;
3672
+ all.sort((a, b) => (a.enabled === b.enabled ? (a.next ?? Infinity) - (b.next ?? Infinity) : a.enabled ? -1 : 1));
3673
+ mine.replaceChildren();
3674
+ const head = h("div", "ra-skh");
3675
+ const add = h("button", "ra-btn xs solid");
3676
+ add.type = "button";
3677
+ add.innerHTML = I.plus(13) + `<span>${escapeHTML(t.schedNew)}</span>`;
3678
+ add.addEventListener("click", () => drawSchedForm(mine, null));
3679
+ head.append(h("span", "", all.length ? `${t.sched} · ${all.length}` : t.sched), add);
3680
+ mine.append(head);
3681
+ if (!all.length)
3682
+ mine.append(h("div", "ra-none", t.schedNone));
3683
+ const statusWord = { ok: t.schedOk, error: t.schedErr, stopped: t.schedStopped };
3684
+ for (const task of all) {
3685
+ const row = h("div", "ra-mi" + (task.enabled ? "" : " ra-off"));
3686
+ const b = h("button");
3687
+ b.type = "button";
3688
+ b.title = t.schedEdit;
3689
+ const name = h("span", "ra-mt");
3690
+ const running = scheduler?.running.has(task.id);
3691
+ if (running)
3692
+ name.append(h("span", "ra-spin"));
3693
+ name.append(h("span", "ra-mtt", task.name));
3694
+ if (running)
3695
+ name.append(h("span", "ra-skb on", t.schedRunning));
3696
+ else if (!task.enabled)
3697
+ name.append(h("span", "ra-skb", t.schedPaused));
3698
+ if (task.by === "agent")
3699
+ name.append(h("span", "ra-skb", t.schedByAI));
3700
+ const when = `${describeSchedule(task.schedule, zhWords ? "zh" : "en")} · ${task.enabled && task.next ? t.schedNext.replace("{time}", fmtShort(task.next)) : task.enabled ? t.schedNoNext : t.schedPaused}`;
3701
+ b.append(name, h("small", "", when));
3702
+ if (task.last)
3703
+ b.append(h("small", task.last.status === "ok" ? "" : "ra-bad", t.schedLast.replace("{time}", fmtShort(task.last.at)).replace("{status}", statusWord[task.last.status] + (task.last.note ? ` (${task.last.note})` : ""))));
3704
+ b.addEventListener("click", () => drawSchedForm(mine, task));
3705
+ const act = (icon, title, fn, cls = "ra-x ra-ia") => { const x = h("button", cls); x.type = "button"; x.innerHTML = icon; x.title = title; x.setAttribute("aria-label", title); x.addEventListener("click", (e) => { e.stopPropagation(); fn(); }); return x; };
3706
+ const runB = act(I.play(), t.schedRunNow, () => {
3707
+ void scheduler.runNow(task.id).then((ok) => { if (!ok)
3708
+ ui.notify(t.schedBusy, "warning"); });
3709
+ setTimeout(refreshSched, 100);
3710
+ });
3711
+ const pauseB = act(task.enabled ? I.pause() : I.clock(13), task.enabled ? t.schedPause : t.schedResume, async () => {
3712
+ try {
3713
+ const cur = await schedStore.get(task.id);
3714
+ if (cur)
3715
+ await schedStore.put(changeTask(cur, { enabled: !cur.enabled }, schedLimits));
3716
+ }
3717
+ catch (err) {
3718
+ ui.notify(err.message, "error");
3719
+ }
3720
+ refreshSched();
3721
+ });
3722
+ const openB = act(I.message(), t.schedOpen, () => { closeMenu(); if (task.session)
3723
+ void resume(task.session).catch((err) => ui.notify(err.message, "error")); });
3724
+ if (!task.session || givenAgent || oneChat)
3725
+ openB.style.display = "none";
3726
+ const del = act(I.trash(), t.schedDel, async () => {
3727
+ closeMenu();
3728
+ if (!(await modalConfirm(root, t.schedDel, t.schedDelMsg.replace("{name}", task.name), { danger: true, ok: t.delete, cancel: t.cancel })))
3729
+ return;
3730
+ try {
3731
+ await schedStore.delete(task.id);
3732
+ }
3733
+ catch (err) {
3734
+ ui.notify(err.message, "error");
3735
+ }
3736
+ refreshSched();
3737
+ }, "ra-x");
3738
+ row.append(b, runB, pauseB, openB, del);
3739
+ mine.append(row);
3740
+ }
3741
+ mine.append(h("div", "ra-skf", t.schedHint));
3742
+ };
3743
+ /** The add / edit form, in the same menu. */
3744
+ const drawSchedForm = (mine, task) => {
3745
+ schedView = "form";
3746
+ for (const b of menuSelects.splice(0))
3747
+ b.close();
3748
+ mine.replaceChildren();
3749
+ const form = h("div", "ra-schf");
3750
+ const field = (label, ...els) => { const l = h("div", "ra-fld"); l.append(h("span", "", label), ...els); return l; };
3751
+ const nameIn = h("input");
3752
+ nameIn.type = "text";
3753
+ nameIn.placeholder = t.schedNamePh;
3754
+ nameIn.value = task?.name ?? "";
3755
+ const promptIn = h("textarea");
3756
+ promptIn.placeholder = t.schedPromptPh;
3757
+ promptIn.value = task?.prompt ?? "";
3758
+ const s0 = task?.schedule ?? { type: "daily", time: "09:00" };
3759
+ const typeSel = selectBox(root, { options: [{ value: "once", label: t.schedOnce }, { value: "every", label: t.schedEvery }, { value: "daily", label: t.schedDaily }, { value: "cron", label: t.schedCron }], value: s0.type });
3760
+ menuSelects.push(typeSel);
3761
+ // once
3762
+ const atIn = h("input");
3763
+ atIn.type = "datetime-local";
3764
+ const at0 = s0.type === "once" ? parseLocalTime(s0.at) : Date.now() + 3600_000;
3765
+ atIn.value = formatLocalTime(Number.isFinite(at0) ? at0 : Date.now() + 3600_000).replace(" ", "T");
3766
+ // every
3767
+ const everyN = h("input");
3768
+ everyN.type = "number";
3769
+ everyN.min = "1";
3770
+ everyN.step = "1";
3771
+ const m0 = s0.type === "every" ? s0.minutes : 60;
3772
+ const unit0 = m0 % 1440 === 0 ? "1440" : m0 % 60 === 0 ? "60" : "1";
3773
+ everyN.value = String(m0 / Number(unit0));
3774
+ const unitSel = selectBox(root, { options: [{ value: "1", label: t.schedMin }, { value: "60", label: t.schedHour }, { value: "1440", label: t.schedDay }], value: unit0 });
3775
+ menuSelects.push(unitSel);
3776
+ const everyRow = h("div", "ra-row");
3777
+ everyRow.append(everyN, unitSel.el);
3778
+ // daily
3779
+ const timeIn = h("input");
3780
+ timeIn.type = "time";
3781
+ timeIn.value = s0.type === "daily" ? s0.time : "09:00";
3782
+ const days = new Set(s0.type === "daily" && s0.days?.length ? s0.days : [0, 1, 2, 3, 4, 5, 6]);
3783
+ const dayRow = h("div", "ra-days");
3784
+ // Monday first.
3785
+ for (const d of [1, 2, 3, 4, 5, 6, 0]) {
3786
+ const db = h("button", days.has(d) ? "on" : "", dayNames[d]);
3787
+ db.type = "button";
3788
+ db.addEventListener("click", () => { if (days.has(d)) {
3789
+ if (days.size > 1)
3790
+ days.delete(d);
3791
+ }
3792
+ else
3793
+ days.add(d); db.classList.toggle("on", days.has(d)); preview(); });
3794
+ dayRow.append(db);
3795
+ }
3796
+ const dailyBox = h("div", "ra-row ra-col2");
3797
+ dailyBox.append(timeIn, dayRow);
3798
+ // cron
3799
+ const cronIn = h("input");
3800
+ cronIn.type = "text";
3801
+ cronIn.placeholder = "0 9 * * 1-5";
3802
+ cronIn.value = s0.type === "cron" ? s0.cron : "";
3803
+ const cronBox = h("div", "ra-fld");
3804
+ cronBox.append(cronIn, h("span", "ra-note", t.schedCronHint));
3805
+ const whenBox = h("div", "ra-fld");
3806
+ const note = h("div", "ra-note");
3807
+ const build = () => {
3808
+ switch (typeSel.value) {
3809
+ case "once": return { type: "once", at: atIn.value.replace("T", " ") };
3810
+ case "every": return { type: "every", minutes: Math.round(Number(everyN.value) * Number(unitSel.value)) };
3811
+ case "cron": return { type: "cron", cron: cronIn.value.trim() };
3812
+ default: return { type: "daily", time: timeIn.value, ...(days.size < 7 ? { days: [...days].sort((a, b) => a - b) } : {}) };
3813
+ }
3814
+ };
3815
+ const preview = () => {
3816
+ const sc = build();
3817
+ const problem = checkSchedule(sc, schedLimits.minMinutes ?? 5);
3818
+ const nx = problem ? null : nextRun(sc, Date.now());
3819
+ note.textContent = problem ?? (nx ? t.schedNext.replace("{time}", formatLocalTime(nx)) : t.schedNoNext);
3820
+ note.classList.toggle("err", !!problem || !nx);
3821
+ save.disabled = !!problem || !nx || !nameIn.value.trim() || !promptIn.value.trim();
3822
+ };
3823
+ const showType = () => {
3824
+ const v = typeSel.value;
3825
+ whenBox.replaceChildren(typeSel.el, ...(v === "once" ? [atIn] : v === "every" ? [everyRow] : v === "cron" ? [cronBox] : [dailyBox]));
3826
+ preview();
3827
+ };
3828
+ typeSel.el.addEventListener("change", showType);
3829
+ unitSel.el.addEventListener("change", preview);
3830
+ for (const el of [nameIn, promptIn, atIn, everyN, timeIn, cronIn])
3831
+ el.addEventListener("input", preview);
3832
+ const btns = h("div", "ra-btns");
3833
+ const cancel = h("button", "ra-btn xs ghost", t.cancel);
3834
+ cancel.type = "button";
3835
+ const save = h("button", "ra-btn xs solid", t.schedSave);
3836
+ save.type = "button";
3837
+ cancel.addEventListener("click", () => { for (const b of menuSelects.splice(0))
3838
+ b.close(); void drawSchedList(mine); });
3839
+ save.addEventListener("click", async () => {
3840
+ try {
3841
+ const fields = { name: nameIn.value, prompt: promptIn.value, schedule: build() };
3842
+ if (task) {
3843
+ const cur = await schedStore.get(task.id);
3844
+ if (!cur)
3845
+ throw new Error("gone");
3846
+ await schedStore.put(changeTask(cur, { ...fields, enabled: true }, schedLimits));
3847
+ }
3848
+ else {
3849
+ if ((await schedStore.list()).length >= (schedLimits.maxTasks ?? 20))
3850
+ throw new Error(`${schedLimits.maxTasks ?? 20} tasks at most`);
3851
+ await schedStore.put(makeTask({ ...fields, by: "user" }, schedLimits));
3852
+ }
3853
+ for (const b of menuSelects.splice(0))
3854
+ b.close();
3855
+ await drawSchedList(mine);
3856
+ refreshSched();
3857
+ }
3858
+ catch (err) {
3859
+ note.textContent = err.message;
3860
+ note.classList.add("err");
3861
+ }
3862
+ });
3863
+ btns.append(cancel, save);
3864
+ form.append(h("div", "ra-schh", task ? t.schedEdit : t.schedNew), field(t.schedName, nameIn), field(t.schedPrompt, promptIn), field(t.schedWhen, whenBox), note, btns);
3865
+ mine.append(form);
3866
+ showType();
3867
+ queueMicrotask(() => (task ? promptIn : nameIn).focus());
3868
+ };
3869
+ schedBtn.addEventListener("click", () => openSched());
3870
+ refreshSched();
3522
3871
  const fail = (err) => ui.notify(err.message, "error");
3523
3872
  let compacting = false;
3524
3873
  /** The conversation as Markdown: what was said, and the tools each turn called. */
@@ -4331,6 +4680,10 @@ export function renderChat(target, opts) {
4331
4680
  const firstId = agentOpts.id ?? (typeof resumeOpt === "string" ? resumeOpt : resumeOpt === false ? undefined : readLast(project) ?? undefined);
4332
4681
  const starting = givenAgent ? Promise.resolve(givenAgent) : makeAgent(firstId);
4333
4682
  const ready = starting.then((a) => attach(a));
4683
+ // Scheduled tasks start once the first conversation is open.
4684
+ if (scheduler)
4685
+ void ready.then(() => { if (mounted)
4686
+ scheduler.start(); }).catch(() => undefined);
4334
4687
  ready.catch((err) => {
4335
4688
  // No session could be opened (the workspace factory or the agent threw): say so instead of a dead chat.
4336
4689
  addError(`${err.message}`);
@@ -4385,6 +4738,12 @@ export function renderChat(target, opts) {
4385
4738
  clearTimeout(histTimer);
4386
4739
  for (const u of unsub)
4387
4740
  u();
4741
+ for (const u of unmountHooks.splice(0)) {
4742
+ try {
4743
+ u();
4744
+ }
4745
+ catch { /* keep going */ }
4746
+ }
4388
4747
  ui.cancelAll(true);
4389
4748
  closeMenu();
4390
4749
  document.removeEventListener("click", onDocClick, true);