@runappsai/agent 0.1.11 → 0.2.0

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.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,11 +41,12 @@ 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.",
47
48
  dSystem: "System prompt", dMessages: "Messages sent to the model", dPayload: "Request", dResponse: "Response", dRun: "Run", dTurn: "Turn {n}", sent: "sent", justNow: "Just now", minutesAgo: "{n} min ago", hoursAgo: "{n} h ago", context: "context", copy: "Copy", copied: "Copied", rewind: "Rewind to here", rewindTitle: "Rewind to this message", regen: "Answer again", regenTitle: "Answer this question again", regenMsg: "This answer and what follows are dropped and the question is sent again.", delTurn: "Delete", delTurnTitle: "Delete this question and its answer?", delTurnMsg: "They are removed from the conversation; files stay as they are.", replyCost: "Cost: {cost}", replyUsage: "{in} in · {out} out · {calls} calls",
49
+ older: "Load earlier messages", olderBusy: "Wait for the reply to finish, then load earlier messages.",
48
50
  rewindMsg: "The conversation after it is dropped and the message goes back into the composer.", rewindFiles: "Also restore the directory's files to that moment", rewindGone: "This message is no longer in the conversation.", rewindSnapshot: "{n} files ({size}) as they were at {time}", rewindPartial: "Files over 2 MB were not in the snapshot and stay as they are.", rewindGoneFile: "{path} is no longer in the directory.",
49
51
  running: "running", waitingAnswer: "waiting for your answer", finished: "finished", bgLimit: "{n} conversations are already running in the background; stop one before switching away from this one.",
50
52
  settings: "Settings", sVision: "sees pictures", sVisionYes: "sees pictures", sVisionNo: "text only", noVision: "{model} cannot see pictures: they are saved as files, but the model will not see what is in them.", sEffort: "Thinking", sEffortDefault: "Model default", sEffortNone: "this model does not expose a thinking level", sModel: "Model", sDefault: "Platform default", sMaxTurns: "Max turns per run", sMaxTokens: "Max output per reply", sPrice: "Price", sPriceLine: "input {in} · output {out} per M tokens", sPerCall: "{amount} per call", sAuto: "Model's maximum", sCustomN: "Set a number", filter: "Filter…", sPerms: "Tool permissions", sAsk: "Ask before destructive tools", sAutoPerm: "Allow everything", sCustom: "Decided by the app",
@@ -61,7 +63,7 @@ const STRINGS = {
61
63
  worked: "Worked for {t}", workedNoTime: "Work", sec: "{s}s", minSec: "{m}m {s}s", hourMin: "{h}h {m}m",
62
64
  command: "Command", user: "User", compacting: "Compacting the context…", nothingToCompact: "Nothing to compact yet", busyCmd: "Wait for the current task to finish, or stop it, first", nothingToExport: "Nothing to export yet", nothingToContinue: "Nothing to continue",
63
65
  unknownModel: "No model named \"{name}\"", modelSet: "Model: {name}", effortSet: "Thinking: {name}", effortLevels: "Thinking levels of {model}: {levels}", unknownEffort: "\"{name}\" is not a thinking level of {model} ({levels})", debugOff: "Debug mode is off",
64
- cmdsTitle: "Commands", cmdsMore: "Templates (/name) and skills (/skill:name) are listed as you type.", autoCompact: "Auto-compaction", autoCompactAt: "when less than {n} tokens are left", directory: "Directory", messagesLabel: "Messages",
66
+ cmdsTitle: "Commands", cmdsMore: "Templates (/name) and skills (/skill:name) are listed as you type.", autoCompact: "Auto-compaction", autoCompactAt: "when less than {n} tokens are left", autoCompactFull: "when the context is full", directory: "Directory", messagesLabel: "Messages",
65
67
  cmdArgs: { compact: "[focus]", model: "[name]", effort: "[level]" },
66
68
  cmd: { help: "Show these commands", new: "Start a new conversation", resume: "Open a saved conversation", compact: "Summarise older turns now; add what the summary must keep", continue: "Continue the last run", model: "Switch model; no name opens the settings", effort: "Set the thinking level", context: "Context use, model and spending", export: "Download the conversation as Markdown", files: "Open the file manager", settings: "Open the settings", debug: "Show or hide the debug panel" },
67
69
  },
@@ -80,11 +82,12 @@ const STRINGS = {
80
82
  attach: "添加附件", drop: "松开即可添加附件", tooLarge: "太大了(最大 20 MB)", remove: "移除",
81
83
  toolsRunning: "正在执行", toolsDone: "执行了 {n} 个工具调用", toolsDone1: "执行了 1 个工具调用", toolsFailed: "{n} 个失败",
82
84
  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 可以搜索和阅读网页,查资料和最新信息;每次搜索、每读一个网页按次计费",
85
+ 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
86
  runCode: "运行代码", ingRead: "正在读取", ingList: "正在查看", ingSearch: "正在搜索", ingWrite: "正在写入", ingEdit: "正在修改", ingDelete: "正在删除", ingRun: "正在运行代码", ingAsk: "正在询问你", ingOther: "正在执行", current: "当前", jumpEnd: "回到最新",
85
87
  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
88
  dNoCalls: "还没有工具调用。", dNoRequests: "还没有模型请求。每次调用模型都会记在这里,包括发了什么、收到什么。", dNoEvents: "还没有事件。",
87
89
  dSystem: "系统提示词", dMessages: "发给模型的消息", dPayload: "请求内容", dResponse: "响应", dRun: "运行", dTurn: "第 {n} 轮", sent: "已发送", justNow: "刚刚", minutesAgo: "{n} 分钟前", hoursAgo: "{n} 小时前", context: "上下文", copy: "复制", copied: "已复制", rewind: "回退到这里", rewindTitle: "回退到这条消息", regen: "重新回答", regenTitle: "重新回答这个问题", regenMsg: "这个回答及之后的对话会被删除,问题重新发送。", delTurn: "删除", delTurnTitle: "删除这一轮问答?", delTurnMsg: "这条提问和它的回答会从对话中删除,文件不受影响。", replyCost: "费用:{cost}", replyUsage: "输入 {in} · 输出 {out} · {calls} 次调用",
90
+ older: "加载更早的消息", olderBusy: "等这次回复结束后再加载更早的消息。",
88
91
  rewindMsg: "它之后的对话会被删除,消息内容放回输入框。", rewindFiles: "同时把目录里的文件恢复到那一刻", rewindGone: "这条消息已不在对话里(可能已被压缩)。", rewindSnapshot: "{time} 时的 {n} 个文件({size})", rewindPartial: "超过 2 MB 的文件没进快照,会保持原样。", rewindGoneFile: "{path} 已不在目录里。",
89
92
  running: "运行中", waitingAnswer: "等待你回答", finished: "已完成", bgLimit: "后台已有 {n} 个会话在运行,先停掉一个再切换。",
90
93
  settings: "设置", sVision: "可看图", sVisionYes: "可看图", sVisionNo: "仅文字", noVision: "{model} 不能看图:图片已保存为文件,但模型看不到图里的内容。", sEffort: "思考强度", sEffortDefault: "模型默认", sEffortNone: "这个模型没有思考强度可调", sModel: "模型", sDefault: "平台默认", sMaxTurns: "每次运行最大轮数", sMaxTokens: "单次回复最大输出", sPrice: "单价", sPriceLine: "每百万 tokens 输入 {in} · 输出 {out}", sPerCall: "每次调用 {amount}", sAuto: "模型上限", sCustomN: "自定义", filter: "搜索…", sPerms: "工具权限", sAsk: "破坏性操作先询问", sAutoPerm: "全部自动允许", sCustom: "由应用决定",
@@ -101,7 +104,7 @@ const STRINGS = {
101
104
  worked: "已工作 {t}", workedNoTime: "工作过程", sec: "{s}秒", minSec: "{m}分{s}秒", hourMin: "{h}小时{m}分",
102
105
  command: "命令", user: "用户", compacting: "正在压缩上下文…", nothingToCompact: "暂时没有可压缩的内容", busyCmd: "请等当前任务结束(或先停止)", nothingToExport: "还没有可导出的内容", nothingToContinue: "没有可继续的内容",
103
106
  unknownModel: "没有名为“{name}”的模型", modelSet: "模型:{name}", effortSet: "思考强度:{name}", effortLevels: "{model} 的思考强度:{levels}", unknownEffort: "“{name}”不是 {model} 的思考强度({levels})", debugOff: "调试模式未开启",
104
- cmdsTitle: "命令", cmdsMore: "模板(/名称)和 Skill(/skill:名称)在输入时列出。", autoCompact: "自动压缩", autoCompactAt: "剩余不足 {n} tokens 时", directory: "目录", messagesLabel: "消息",
107
+ cmdsTitle: "命令", cmdsMore: "模板(/名称)和 Skill(/skill:名称)在输入时列出。", autoCompact: "自动压缩", autoCompactAt: "剩余不足 {n} tokens 时", autoCompactFull: "上下文用满时", directory: "目录", messagesLabel: "消息",
105
108
  cmdArgs: { compact: "[重点]", model: "[名称]", effort: "[档位]" },
106
109
  cmd: { help: "显示这些命令", new: "开始新对话", resume: "打开保存的对话", compact: "立即压缩较早的对话,可附上要保留的重点", continue: "继续上一次运行", model: "切换模型,不带名称则打开设置", effort: "设置思考强度", context: "上下文占用、模型和花费", export: "把对话下载为 Markdown", files: "打开文件管理", settings: "打开设置", debug: "显示或隐藏调试面板" },
107
110
  },
@@ -169,6 +172,25 @@ const CSS = tokenCSS() + `
169
172
  .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
173
  .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
174
  .ra-skm.drop{outline:2px dashed var(--ra-accent);outline-offset:-4px}
175
+ .ra-schm .ra-skb.on{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
176
+ .ra-schm .ra-mi.ra-off .ra-mtt{color:var(--ra-fg-muted)}
177
+ .ra-schm .ra-mi small.ra-bad{color:var(--ra-red)}
178
+ .ra-schm .ra-mi small{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp:none}
179
+ .ra-schf{display:flex;flex-direction:column;gap:10px;padding:6px 8px 6px}
180
+ .ra-schf .ra-schh{font-size:13px;font-weight:600}
181
+ .ra-schf .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
182
+ .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}
183
+ .ra-chat .ra-schf textarea{min-height:88px;resize:vertical;line-height:1.5}
184
+ .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)}
185
+ .ra-schf .ra-row{display:flex;gap:8px;align-items:center}
186
+ .ra-schf .ra-row>*{flex:1;min-width:0}
187
+ .ra-schf .ra-row.ra-col2{flex-direction:column;align-items:stretch}
188
+ .ra-schf .ra-days{display:flex;gap:4px}
189
+ .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)}
190
+ .ra-chat .ra-schf .ra-days button.on{background:var(--ra-accent-subtle);border-color:transparent;color:var(--ra-accent-fg);font-weight:600}
191
+ .ra-schf .ra-note{font-size:11.5px;color:var(--ra-fg-muted)}
192
+ .ra-schf .ra-note.err{color:var(--ra-red)}
193
+ .ra-schf .ra-btns{display:flex;justify-content:flex-end;gap:6px}
172
194
  .ra-set{padding:10px 12px;display:flex;flex-direction:column;gap:10px;width:min(360px,calc(100% - 24px))}
173
195
  /* The settings panel takes the chat's height under the header (a host may add fields of its own). */
174
196
  .ra-chat .ra-set{max-height:calc(100% - 72px)}
@@ -323,6 +345,8 @@ const CSS = tokenCSS() + `
323
345
  @keyframes ra-shimmer{from{background-position:100% 0}to{background-position:0 0}}
324
346
  @media (prefers-reduced-motion:reduce){.ra-pending>span{animation:none;color:var(--ra-fg-muted);background:none}}
325
347
  .ra-time{text-align:center;font-size:12px;color:var(--ra-fg-muted);padding:14px 0 2px}
348
+ .ra-olderrow{display:flex;justify-content:center;padding:6px 0 2px}
349
+ .ra-chat .ra-older{font-size:12px;color:var(--ra-fg-muted)}
326
350
  .ra-work{border-bottom:1px solid var(--ra-border);padding-bottom:6px;margin-bottom:4px}
327
351
  .ra-work>summary{display:inline-flex;align-items:center;gap:4px;font-size:13px;color:var(--ra-fg-muted);cursor:pointer;list-style:none;user-select:none;padding:2px 0}
328
352
  .ra-work>summary::-webkit-details-marker{display:none}
@@ -375,6 +399,8 @@ const CSS = tokenCSS() + `
375
399
  .ra-tool>summary .ra-chev{color:var(--ra-fg-muted);transition:transform .15s}
376
400
  .ra-tool[open]>summary .ra-chev{transform:rotate(90deg)}
377
401
  .ra-tool .ra-ticon{width:20px;height:20px;border-radius:4px;background:var(--ra-accent-subtle);color:var(--ra-accent-fg);display:inline-flex;align-items:center;justify-content:center}
402
+ .ra-tool .ra-ticon[data-tone="warning"]{background:var(--ra-warn-bg);color:var(--ra-warn-fg)}
403
+ .ra-tool .ra-ticon[data-tone="danger"]{background:var(--ra-red-subtle);color:var(--ra-red)}
378
404
  .ra-tool.fail .ra-ticon{background:var(--ra-red-subtle);color:var(--ra-red)}
379
405
  .ra-tool .ra-tname{font-weight:600;white-space:nowrap}
380
406
  .ra-tool .ra-tname.own{font-weight:500;min-width:0;overflow:hidden;text-overflow:ellipsis}
@@ -426,6 +452,9 @@ const CSS = tokenCSS() + `
426
452
  .ra-q .ra-opt small{display:block;color:var(--ra-fg-muted);font-size:12px}
427
453
  .ra-q .ra-field{border:1px solid var(--ra-border);border-radius:6px;padding:6px 10px;background:var(--ra-bg);width:100%;font-size:14px}
428
454
  .ra-q .ra-field:focus{border-color:var(--ra-accent)}
455
+ .ra-q .ra-field.bad{border-color:var(--ra-red)}
456
+ .ra-q .ra-form{display:flex;flex-direction:column;gap:8px;margin:2px 0 4px}
457
+ .ra-q .ra-ff{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--ra-fg-muted)}
429
458
  .ra-q textarea.ra-field{min-height:96px;max-height:200px;resize:vertical}
430
459
  .ra-btns{display:flex;justify-content:flex-end;gap:8px}
431
460
  .ra-cbody{margin:2px 0 10px;max-height:min(60vh,560px);overflow:auto;min-width:0}
@@ -926,11 +955,62 @@ function inlineUI(askArea, toasts, t, onChange) {
926
955
  }
927
956
  card.append(list);
928
957
  const row = h("div", "ra-btns");
929
- row.append(btn(t.cancel, "ghost", () => done(null)), btn(t.ok, "solid", () => {
930
- const picked = inputs.filter((i) => i.checked).map((i) => (i.value === "__other__" ? (other?.value.trim() ?? "") : i.value)).filter(Boolean);
931
- if (picked.length)
932
- done(picked);
933
- }));
958
+ const pickedNow = () => inputs.filter((i) => i.checked).map((i) => (i.value === "__other__" ? (other?.value.trim() ?? "") : i.value)).filter(Boolean);
959
+ // How many may be picked (several choices only): OK waits until the count fits.
960
+ const min = opts.multi ? opts.min ?? 1 : 1, max = opts.multi ? opts.max : undefined;
961
+ const fits = (n) => n >= min && (max === undefined || n <= max);
962
+ const okBtn = btn(t.ok, "solid", () => { const picked = pickedNow(); if (fits(picked.length))
963
+ done(picked); });
964
+ if (opts.multi && (opts.min !== undefined || opts.max !== undefined)) {
965
+ const sync = () => { okBtn.disabled = !fits(pickedNow().length); };
966
+ list.addEventListener("change", sync);
967
+ list.addEventListener("input", sync);
968
+ sync();
969
+ }
970
+ row.append(btn(t.cancel, "ghost", () => done(null)), okBtn);
971
+ card.append(row);
972
+ }, null, opts.signal),
973
+ form: (title, fields, opts = {}) => open((card, done) => {
974
+ head(card, title, opts.message);
975
+ const box = h("div", "ra-form");
976
+ const inputs = fields.map((f) => {
977
+ const label = h("label", "ra-ff");
978
+ label.append(h("span", "", (f.label ?? f.name) + (f.required ? " *" : "")));
979
+ const input = h("input", "ra-field");
980
+ input.type = f.type === "number" ? "number" : "text";
981
+ input.name = f.name;
982
+ if (f.type === "number")
983
+ input.step = "any";
984
+ if (f.placeholder)
985
+ input.placeholder = f.placeholder;
986
+ if (f.initial !== undefined)
987
+ input.value = String(f.initial);
988
+ label.append(input);
989
+ box.append(label);
990
+ return { f, input };
991
+ });
992
+ const submit = () => {
993
+ const out = {};
994
+ for (const { f, input } of inputs) {
995
+ const raw = input.value.trim();
996
+ const bad = (!raw && f.required) || (!!raw && f.type === "number" && !Number.isFinite(Number(raw)));
997
+ input.classList.toggle("bad", bad);
998
+ if (bad) {
999
+ input.focus();
1000
+ return;
1001
+ }
1002
+ if (raw)
1003
+ out[f.name] = f.type === "number" ? Number(raw) : raw;
1004
+ }
1005
+ done(out);
1006
+ };
1007
+ box.addEventListener("keydown", (ev) => { const e = ev; if (e.key === "Enter" && !e.isComposing) {
1008
+ e.preventDefault();
1009
+ submit();
1010
+ } });
1011
+ card.append(box);
1012
+ const row = h("div", "ra-btns");
1013
+ row.append(btn(t.cancel, "ghost", () => done(null)), btn(opts.ok ?? t.submit, "solid", submit));
934
1014
  card.append(row);
935
1015
  }, null, opts.signal),
936
1016
  input: (title, opts = {}) => open((card, done) => {
@@ -1020,8 +1100,11 @@ export function renderChat(target, opts) {
1020
1100
  injectStyles();
1021
1101
  const lang = pickLocale(opts.locale);
1022
1102
  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;
1103
+ 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, queue: queueOpt, replyActions, clearButton, commands: commandsOpt, uploadImage, headerStart, ...agentOpts } = opts;
1104
+ // Steering and queueing while a run is going (off: the composer only offers Stop then, and what is typed stays in it).
1105
+ const canQueue = queueOpt !== false;
1024
1106
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
1107
+ setFileDialog(fileDialogOpt);
1025
1108
  const provider = providerOpt ? toProvider(providerOpt) : clientOpt ? toProvider(clientOpt) : givenAgent?.provider ?? null;
1026
1109
  const project = provider?.name ?? agentOpts.appName ?? "app";
1027
1110
  // Shell.
@@ -1086,6 +1169,10 @@ export function renderChat(target, opts) {
1086
1169
  return (n) => { b.textContent = String(n); b.style.display = n ? "" : "none"; btn.title = n ? `${label} · ${n}` : label; };
1087
1170
  };
1088
1171
  const setSkillCount = countBadge(skillsBtn, t.skills);
1172
+ const schedBtn = h("button", "ra-btn ghost");
1173
+ schedBtn.type = "button";
1174
+ schedBtn.innerHTML = I.clock() + `<span>${escapeHTML(t.sched)}</span>`;
1175
+ const setSchedCount = countBadge(schedBtn, t.sched);
1089
1176
  const histBtn = h("button", "ra-btn ghost");
1090
1177
  histBtn.type = "button";
1091
1178
  histBtn.innerHTML = I.hist() + `<span>${escapeHTML(t.history)}</span>`;
@@ -1101,7 +1188,7 @@ export function renderChat(target, opts) {
1101
1188
  clearBtn.style.display = "none";
1102
1189
  // One conversation, no list of them (sessions: false, or the host's own agent): Clear stands in for New chat, and shows only when there is something to clear.
1103
1190
  let oneChat = false;
1104
- const syncClear = () => { clearBtn.style.display = oneChat && agent?.messages.length ? "" : "none"; };
1191
+ const syncClear = () => { clearBtn.style.display = clearButton !== false && oneChat && agent?.messages.length ? "" : "none"; };
1105
1192
  // How full the context is, as a ring; a click opens the numbers and the spending.
1106
1193
  const useBtn = h("button", "ra-btn ghost ra-usebtn");
1107
1194
  useBtn.type = "button";
@@ -1112,14 +1199,14 @@ export function renderChat(target, opts) {
1112
1199
  setBtn.title = t.settings;
1113
1200
  setBtn.setAttribute("aria-label", t.settings);
1114
1201
  // 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]]) {
1202
+ 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
1203
  btn.setAttribute("aria-label", label);
1117
1204
  if (!btn.title)
1118
1205
  btn.title = label;
1119
1206
  }
1120
- for (const el of [...(headerActions ?? []), ...(headerEnd ?? []), ...(composerTop ? [composerTop] : []), ...(emptyState instanceof HTMLElement ? [emptyState] : [])])
1207
+ for (const el of [...(headerStart ?? []), ...(headerActions ?? []), ...(headerEnd ?? []), ...(composerTop ? [composerTop] : []), ...(emptyState instanceof HTMLElement ? [emptyState] : [])])
1121
1208
  el.classList.add("ra-host");
1122
- head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, histBtn, newBtn, clearBtn, ...(headerActions ?? []), setBtn, ...(headerEnd ?? []));
1209
+ head.append(...(headerStart ?? []), titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, schedBtn, histBtn, newBtn, clearBtn, ...(headerActions ?? []), setBtn, ...(headerEnd ?? []));
1123
1210
  if (title === false)
1124
1211
  head.style.display = "none";
1125
1212
  const log = h("div", "ra-log");
@@ -1245,6 +1332,36 @@ export function renderChat(target, opts) {
1245
1332
  for (const a of live.values())
1246
1333
  applyWeb(a);
1247
1334
  });
1335
+ // 自动执行: 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).
1336
+ const PERM_KEY = `__runapps_agent_chat:${project}:perm`;
1337
+ const permOwn = !givenAgent && typeof agentOpts.permissions !== "function";
1338
+ const permShown = permOwn && permissionsSetting !== false;
1339
+ let permChoice = (() => { if (!permShown)
1340
+ return null; try {
1341
+ const v = localStorage.getItem(PERM_KEY);
1342
+ if (v === "ask" || v === "auto")
1343
+ return v;
1344
+ }
1345
+ catch { /* private mode */ } return null; })();
1346
+ const permAuto = () => (permChoice ?? agentOpts.permissions ?? "ask") === "auto";
1347
+ /** Sets the user's choice (null: back to the app's) on every open session, kept per app. */
1348
+ const setPerm = (p, quiet = false) => {
1349
+ const was = permAuto();
1350
+ permChoice = p;
1351
+ if (permShown) {
1352
+ try {
1353
+ if (p)
1354
+ localStorage.setItem(PERM_KEY, p);
1355
+ else
1356
+ localStorage.removeItem(PERM_KEY);
1357
+ }
1358
+ catch { /* private mode */ }
1359
+ }
1360
+ for (const a of live.values())
1361
+ a.configure({ permissions: p ?? agentOpts.permissions ?? "ask" });
1362
+ if (!quiet && !was && permAuto())
1363
+ ui.notify(t.permAutoNote);
1364
+ };
1248
1365
  left.append(attachBtn, webBtn, ...hostActions, hint);
1249
1366
  bar.append(left, acts);
1250
1367
  box.append(cmds, files, ta, bar, fileInput);
@@ -1297,6 +1414,8 @@ export function renderChat(target, opts) {
1297
1414
  let cmdIndex = 0;
1298
1415
  let cmdFrame = null;
1299
1416
  let unsub = [];
1417
+ /** Run once when the chat is unmounted. */
1418
+ const unmountHooks = [];
1300
1419
  let menu = null;
1301
1420
  let mounted = true;
1302
1421
  // A short chat (a phone held sideways, a small panel) keeps the transcript readable: the composer is compact.
@@ -1352,15 +1471,16 @@ export function renderChat(target, opts) {
1352
1471
  const wake = (id, shown = true) => { const w = waiters.get(id); waiters.delete(id); waiting.delete(id); w?.forEach((f) => f(shown)); };
1353
1472
  /** 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
1473
  const uiFor = (id) => ({
1355
- confirm: async (title, message, o) => ((await whenCurrent(id, o?.signal)) ? ui.confirm(title, message, o) : false),
1474
+ // A permission question gets "Always allow (this app)", which turns auto-run on (a tool's own `always` keeps its place).
1475
+ 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
1476
  select: async (title, options, o) => ((await whenCurrent(id, o?.signal)) ? ui.select(title, options, o) : null),
1357
1477
  input: async (title, o) => ((await whenCurrent(id, o?.signal)) ? ui.input(title, o) : null),
1358
1478
  notify: (m, l) => ui.notify(m, l),
1359
1479
  });
1360
1480
  /** Whether rewinding may restore files: only a directory of the session's own, kept in IndexedDB (not a folder on disk, not shared). */
1361
1481
  const restorable = (a) => !!a.workspace && typeof wsOpt === "function" && !a.workspace.root;
1362
- 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; };
1482
+ const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || (a.queued?.length ?? 0) > 0 || waiting.has(a.id)));
1483
+ 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
1484
  const markBackground = () => histBtn.classList.toggle("ra-bg", background().length > 0);
1365
1485
  /** The Chats count: the conversations, open one included, shown once there is another (redrawn after a run, a switch, a delete). */
1366
1486
  let histTimer = null;
@@ -1418,7 +1538,7 @@ export function renderChat(target, opts) {
1418
1538
  ui.notify(`${titleOfAgent(a)} · ${t.finished}`);
1419
1539
  // `busy` flips after the run's promise settles, a tick after this event.
1420
1540
  setTimeout(() => { if (!mounted)
1421
- return; if (agent !== a && !a.busy && !a.queued.length && !waiting.has(a.id)) {
1541
+ return; if (agent !== a && !a.busy && !a.queued?.length && !waiting.has(a.id)) {
1422
1542
  live.delete(a.id);
1423
1543
  unwatchBackground(a);
1424
1544
  release(a);
@@ -1617,7 +1737,7 @@ export function renderChat(target, opts) {
1617
1737
  back.title = t.rewind;
1618
1738
  back.setAttribute("aria-label", t.rewind);
1619
1739
  back.addEventListener("click", () => void rewindTo(row));
1620
- foot.append(time, copy, back);
1740
+ foot.append(time, copy, ...(replyActions?.rewind === false ? [] : [back]));
1621
1741
  el.addEventListener("mouseenter", () => row.update());
1622
1742
  row.update = () => {
1623
1743
  const ts = tsOf(row.msg);
@@ -1782,13 +1902,13 @@ export function renderChat(target, opts) {
1782
1902
  ui.cancelAll();
1783
1903
  await a.abort();
1784
1904
  }
1785
- await a.remove(turn.start, turn.end);
1905
+ await a.remove?.(turn.start, turn.end);
1786
1906
  }
1787
1907
  catch (err) {
1788
1908
  ui.notify(err.message, "error");
1789
1909
  }
1790
1910
  })());
1791
- foot.append(copy, again, del);
1911
+ foot.append(copy, ...(replyActions?.retry === false ? [] : [again]), ...(replyActions?.delete === false ? [] : [del]));
1792
1912
  const u = last.runUsage;
1793
1913
  if (u && u.calls) {
1794
1914
  const show = (currency) => { cost.textContent = t.replyCost.replace("{cost}", fmtCost(u.total_cost, currency)); };
@@ -1823,7 +1943,8 @@ export function renderChat(target, opts) {
1823
1943
  if (m)
1824
1944
  inline.set(m[1], m[2]);
1825
1945
  }
1826
- const images = parts.flatMap((p) => (p.type === "image_url" && p.image_url.url.startsWith("data:") ? [p.image_url.url] : []));
1946
+ // The pictures the message carried: inline, or at an address (a host that uploads them: `uploadImage`).
1947
+ const images = imagesOf(parts);
1827
1948
  const files = [], paths = [], missing = [];
1828
1949
  for (const line of block.text.split("\n").slice(1)) {
1829
1950
  const a = parseAttachLine(line);
@@ -2098,6 +2219,8 @@ export function renderChat(target, opts) {
2098
2219
  const d = displayOf(name), label = labelOf(name, args);
2099
2220
  const icon = h("span", "ra-ticon");
2100
2221
  icon.innerHTML = d?.icon ?? (TOOL_ICON[name] ?? I.wrench)();
2222
+ if (d?.tone)
2223
+ icon.dataset.tone = d.tone;
2101
2224
  const end = h("span", "ra-tend");
2102
2225
  end.innerHTML = '<span class="ra-spin"></span>';
2103
2226
  sum.innerHTML = `<span class="ra-chev">${I.chev()}</span>`;
@@ -2238,7 +2361,7 @@ export function renderChat(target, opts) {
2238
2361
  return card;
2239
2362
  };
2240
2363
  /** Pictures a tool returned, shown under its result (a screenshot, a chart). */
2241
- const imagesOf = (content) => Array.isArray(content) ? content.flatMap((p) => (p.type === "image_url" && /^(data:image\/|https?:)/.test(p.image_url.url) ? [p.image_url.url] : [])) : [];
2364
+ const imagesOf = (content) => Array.isArray(content) ? content.flatMap((p) => (p.type === "image_url" && /^(data:image\/|https?:|\/(?!\/))/.test(p.image_url.url) ? [p.image_url.url] : [])) : [];
2242
2365
  /** The file a finished call is about, when it really is one: open it and, unless the app handles files itself, download it. */
2243
2366
  const offerFile = async (card) => {
2244
2367
  const ws = agent?.workspace;
@@ -2380,6 +2503,24 @@ export function renderChat(target, opts) {
2380
2503
  // One row per reply, as live: every turn between two user messages; text-less turns (thinking + tool calls) share a group.
2381
2504
  let last = null;
2382
2505
  let lastUserTs;
2506
+ // An agent that holds only the recent part of its conversation: the rest comes on demand.
2507
+ const src = agent;
2508
+ if (src?.hasOlder && src.loadOlder) {
2509
+ const b = h("button", "ra-btn ghost ra-older");
2510
+ b.type = "button";
2511
+ b.textContent = t.older;
2512
+ b.addEventListener("click", () => {
2513
+ if (src.busy) {
2514
+ ui.notify(t.olderBusy, "warning");
2515
+ return;
2516
+ }
2517
+ b.disabled = true;
2518
+ void src.loadOlder().catch((err) => { b.disabled = false; ui.notify(err.message, "error"); });
2519
+ });
2520
+ const el = h("div", "ra-olderrow");
2521
+ el.append(b);
2522
+ addRow({ render: () => el, el });
2523
+ }
2383
2524
  const flush = (atEnd = false) => {
2384
2525
  if (!last)
2385
2526
  return;
@@ -2519,18 +2660,29 @@ export function renderChat(target, opts) {
2519
2660
  },
2520
2661
  };
2521
2662
  /** Every tool the chat's agents get: the host's, plus the built-in suggestion tool. */
2522
- const chatTools = [...(agentOpts.tools ?? []), ...(nextPrompt ? [nextPromptTool] : [])];
2663
+ // Scheduled tasks: the store, and the agent's tools over it (their cards in the chat's language).
2664
+ const schedCfg = scheduleOpt ? (scheduleOpt === true ? {} : scheduleOpt) : null;
2665
+ const schedStore = schedCfg ? schedCfg.store ?? localSchedules(`__runapps_agent_chat:${project}:schedules`) : null;
2666
+ const schedLabels = { schedule_list: () => t.tSchedList, schedule_add: (a) => t.tSchedAdd.replace("{name}", a.name ?? ""), schedule_update: () => t.tSchedUpdate, schedule_remove: () => t.tSchedRemove };
2667
+ const schedTools = schedStore && schedCfg.tools !== false
2668
+ ? scheduleTools(schedStore, { ...schedCfg, onChange: () => refreshSched() }).map((x) => ({ ...x, display: { ...x.display, icon: I.clock(), label: schedLabels[x.name] } }))
2669
+ : [];
2670
+ const chatTools = [...(agentOpts.tools ?? []), ...(nextPrompt ? [nextPromptTool] : []), ...schedTools];
2671
+ // A host's agent brings its own tools: the ones it hides are read from it as well (when it is attached).
2523
2672
  const hiddenTools = new Set(chatTools.filter((x) => x.display?.hidden).map((x) => x.name));
2673
+ const hideToolsOf = (a) => { for (const x of a.tools ?? [])
2674
+ if (x.display?.hidden)
2675
+ hiddenTools.add(x.name); };
2524
2676
  /** 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
2677
  const syncSend = () => {
2526
2678
  const busy = root.dataset.busy === "1", any = !!(ta.value.trim() || pendingFiles.length || pendingContext.length);
2527
2679
  sendBtn.style.display = !busy && any ? "" : "none";
2528
- steerBtn.style.display = fuBtn.style.display = busy && any ? "" : "none";
2680
+ steerBtn.style.display = fuBtn.style.display = canQueue && busy && any ? "" : "none";
2529
2681
  };
2530
2682
  const setBusy = (busy) => {
2531
2683
  root.dataset.busy = busy ? "1" : "";
2532
- ta.placeholder = busy ? fill(t.placeholderBusy) : (nextSuggestion ?? placeholder ?? t.placeholder);
2533
- hint.textContent = fill(busy ? t.hintBusy : nextSuggestion ? t.hintNext : t.hintIdle);
2684
+ ta.placeholder = busy && canQueue ? fill(t.placeholderBusy) : (nextSuggestion ?? placeholder ?? t.placeholder);
2685
+ hint.textContent = fill(busy && canQueue ? t.hintBusy : nextSuggestion ? t.hintNext : t.hintIdle);
2534
2686
  syncSend();
2535
2687
  stopBtn.style.display = busy ? "" : "none";
2536
2688
  renderQueue();
@@ -2552,16 +2704,16 @@ export function renderChat(target, opts) {
2552
2704
  const box = h("span", "ra-qa");
2553
2705
  // Send now: a queued follow-up becomes a steer, inserted at the next step of the running task.
2554
2706
  if (item.kind !== "steer")
2555
- box.append(btn(I.enter(), t.sendNow, () => { if (a.dequeue(item.message))
2556
- a.steer(item.message.content); renderQueue(); }));
2707
+ box.append(btn(I.enter(), t.sendNow, () => { if (a.dequeue?.(item.message))
2708
+ a.steer?.(item.message.content); renderQueue(); }));
2557
2709
  box.append(btn(I.pen(), t.editQueued, () => {
2558
- if (!a.dequeue(item.message))
2710
+ if (!a.dequeue?.(item.message))
2559
2711
  return;
2560
2712
  ta.value = ta.value.trim() ? `${textOf(item.message)}\n${ta.value}` : textOf(item.message);
2561
2713
  ta.focus();
2562
2714
  renderQueue();
2563
2715
  }));
2564
- box.append(btn(I.x(14), t.remove, () => { a.dequeue(item.message); renderQueue(); }));
2716
+ box.append(btn(I.x(14), t.remove, () => { a.dequeue?.(item.message); renderQueue(); }));
2565
2717
  return box;
2566
2718
  };
2567
2719
  const kindTag = (item) => (item.kind === "steer" ? h("span", "ra-qk", t.steer) : null);
@@ -2722,7 +2874,7 @@ export function renderChat(target, opts) {
2722
2874
  renderFiles();
2723
2875
  ta.focus();
2724
2876
  };
2725
- attachBtn.addEventListener("click", () => fileInput.click());
2877
+ attachBtn.addEventListener("click", () => chooseFiles(fileInput, (picked) => void addFiles(picked)));
2726
2878
  fileInput.addEventListener("change", () => { void addFiles(fileInput.files); fileInput.value = ""; });
2727
2879
  ta.addEventListener("paste", (e) => {
2728
2880
  const items = Array.from(e.clipboardData?.files ?? []);
@@ -2794,6 +2946,16 @@ export function renderChat(target, opts) {
2794
2946
  parts.push({ type: "video_url", video_url: { url: b64 } });
2795
2947
  }
2796
2948
  if (a.image && !blind && a.file.size <= MAX_IMAGE_PART) {
2949
+ if (uploadImage) {
2950
+ // The host puts the picture where its server reads it: the message carries the address.
2951
+ try {
2952
+ parts.push({ type: "image_url", image_url: { url: await uploadImage(a.file) } });
2953
+ }
2954
+ catch (err) {
2955
+ ui.notify(`${a.name}: ${err?.message || String(err)}`, "error");
2956
+ }
2957
+ continue;
2958
+ }
2797
2959
  const b64 = await new Promise((res) => { const r = new FileReader(); r.onload = () => res(String(r.result)); r.readAsDataURL(a.file); });
2798
2960
  parts.push({ type: "image_url", image_url: { url: b64 } });
2799
2961
  }
@@ -2815,6 +2977,9 @@ export function renderChat(target, opts) {
2815
2977
  clearNext();
2816
2978
  if (runBuiltin(text))
2817
2979
  return;
2980
+ // Without a queue nothing is sent while a run (or a compaction) is going: the text waits in the composer.
2981
+ if (!canQueue && (agent.busy || compacting))
2982
+ return;
2818
2983
  // While compacting, a message waits for it and then runs (Enter, Steer and Follow-up alike).
2819
2984
  if (compacting)
2820
2985
  mode = "followUp";
@@ -2872,9 +3037,9 @@ export function renderChat(target, opts) {
2872
3037
  return;
2873
3038
  }
2874
3039
  if (mode === "steer")
2875
- a.steer(content);
3040
+ a.steer?.(content);
2876
3041
  else
2877
- void a.followUp(content).catch(() => undefined);
3042
+ void a.followUp?.(content).catch(() => undefined);
2878
3043
  renderQueue();
2879
3044
  }
2880
3045
  catch (err) {
@@ -2999,7 +3164,6 @@ export function renderChat(target, opts) {
2999
3164
  }
3000
3165
  catch { /* private mode */ } };
3001
3166
  let userSettings = givenAgent ? {} : readSettings();
3002
- let permChoice = null; // not persisted: allowing everything is a per-page decision
3003
3167
  const hasSettings = opts.settings ?? !givenAgent;
3004
3168
  let settingsTab = 0;
3005
3169
  if (!hasSettings)
@@ -3252,7 +3416,7 @@ export function renderChat(target, opts) {
3252
3416
  }
3253
3417
  userSettings = {};
3254
3418
  writeSettings({});
3255
- permChoice = null;
3419
+ setPerm(null, true);
3256
3420
  for (const ag of live.values())
3257
3421
  applyTo(ag, {}, null);
3258
3422
  closeMenu();
@@ -3274,8 +3438,8 @@ export function renderChat(target, opts) {
3274
3438
  }
3275
3439
  if (effortSel.value && !effortSel.disabled)
3276
3440
  next.reasoningEffort = effortSel.value;
3277
- if (perm.value === "ask" || perm.value === "auto")
3278
- permChoice = perm.value;
3441
+ if ((perm.value === "ask" || perm.value === "auto") && perm.value !== (permAuto() ? "auto" : "ask"))
3442
+ setPerm(perm.value);
3279
3443
  const summarize = sumSel.value === "summary";
3280
3444
  if (summarize !== hostCompaction.summarize)
3281
3445
  next.summarize = summarize;
@@ -3328,7 +3492,7 @@ export function renderChat(target, opts) {
3328
3492
  const b = h("button");
3329
3493
  b.type = "button";
3330
3494
  const bg = s ? live.get(s.id) : undefined;
3331
- const state = s && bg && bg !== cur ? (waiting.has(s.id) ? ` · ${t.waitingAnswer}` : bg.busy || bg.queued.length ? ` · ${t.running}` : "") : "";
3495
+ const state = s && bg && bg !== cur ? (waiting.has(s.id) ? ` · ${t.waitingAnswer}` : bg.busy || bg.queued?.length ? ` · ${t.running}` : "") : "";
3332
3496
  // The title line: the title shortens, the "Current" tag (and a spinner for a running session) always shows.
3333
3497
  const name = h("span", "ra-mt");
3334
3498
  if (state && !waiting.has(s.id))
@@ -3396,7 +3560,7 @@ export function renderChat(target, opts) {
3396
3560
  });
3397
3561
  document.addEventListener("click", onDocClick, true);
3398
3562
  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))
3563
+ 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
3564
  closeMenu(); }
3401
3565
  /* --- skills menu --- */
3402
3566
  const skillInput = h("input");
@@ -3457,7 +3621,7 @@ export function renderChat(target, opts) {
3457
3621
  const up = h("button", "ra-btn xs solid");
3458
3622
  up.type = "button";
3459
3623
  up.innerHTML = I.upload(13) + `<span>${escapeHTML(t.uploadZip)}</span>`;
3460
- up.addEventListener("click", () => skillInput.click());
3624
+ up.addEventListener("click", () => chooseFiles(skillInput, (picked) => void installZips(picked)));
3461
3625
  if (!ws.userSkillsDir)
3462
3626
  up.style.display = "none";
3463
3627
  head.append(h("span", "", skills.length ? `${t.skills} · ${skills.length}` : t.skills), up);
@@ -3519,6 +3683,291 @@ export function renderChat(target, opts) {
3519
3683
  mine.addEventListener("drop", (e) => { e.preventDefault(); e.stopPropagation(); mine.classList.remove("drop"); void installZips(e.dataTransfer?.files); });
3520
3684
  };
3521
3685
  skillsBtn.addEventListener("click", () => void openSkills());
3686
+ /* --- scheduled tasks --- */
3687
+ if (!schedStore)
3688
+ schedBtn.style.display = "none";
3689
+ const schedLimits = { minMinutes: schedCfg?.minMinutes, maxTasks: schedCfg?.maxTasks };
3690
+ const dayNames = t.schedDayNames.split(",");
3691
+ const zhWords = /[\u4e00-\u9fff]/.test(t.sched);
3692
+ const fmtShort = (ms) => { const s = formatLocalTime(ms); return s.slice(0, 4) === String(new Date().getFullYear()) ? s.slice(5) : s; };
3693
+ /** Runs one task: in its own conversation (made on its first run), or the one conversation when the chat keeps only one. */
3694
+ const runScheduled = async (task) => {
3695
+ await ready;
3696
+ const text = `${t.schedRunHead.replace("{name}", task.name).replace("{time}", formatLocalTime(Date.now()))}\n\n${task.prompt}`;
3697
+ let a;
3698
+ if (givenAgent || oneChat)
3699
+ a = agent ?? givenAgent;
3700
+ else {
3701
+ const sid = task.session ?? `sched_${task.id}`;
3702
+ if (!task.session) {
3703
+ const cur = await schedStore.get(task.id);
3704
+ if (cur)
3705
+ await schedStore.put({ ...cur, session: sid });
3706
+ }
3707
+ a = agent?.id === sid ? agent : live.get(sid) ?? await makeAgent(sid);
3708
+ if (a !== agent) {
3709
+ await a.ready();
3710
+ live.set(sid, a);
3711
+ watchBackground(a);
3712
+ }
3713
+ }
3714
+ // Its own conversation is named after it (the first message would be the run's header).
3715
+ if (!givenAgent && !oneChat)
3716
+ a.setTitle?.(`⏰ ${task.name}`);
3717
+ ui.notify(t.schedStarted.replace("{name}", task.name));
3718
+ const r = a === agent ? await promptFromHost(text) : await a.prompt(text);
3719
+ refreshHistCount();
3720
+ if (r.reason === "error" || r.reason === "max_turns")
3721
+ ui.notify(t.schedFailed.replace("{name}", task.name).replace("{error}", r.error?.message ?? r.reason), "warning");
3722
+ 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 } : {}) };
3723
+ };
3724
+ /** Idle: nothing running in any conversation, no question open, not switching, the user not typing. */
3725
+ const schedIdle = () => mounted && !switching && !!agent && asked === 0 && waiting.size === 0
3726
+ && ![...live.values()].some((a) => a.busy || (a.queued?.length ?? 0) > 0)
3727
+ && !(document.activeElement === ta && ta.value.trim());
3728
+ const scheduler = schedStore ? new Scheduler({ store: schedStore, run: runScheduled, idle: schedIdle, lockPrefix: `__runapps_agent_chat:${project}:schedules`, onChange: () => refreshSched() }) : null;
3729
+ if (scheduler) {
3730
+ // Each run that ends is a moment the chat may have become idle: look again.
3731
+ const again = () => setTimeout(() => void scheduler.tick(), 1500);
3732
+ let lastBusy = false;
3733
+ const poll = setInterval(() => { const b = !schedIdle(); if (lastBusy && !b)
3734
+ again(); lastBusy = b; }, 3000);
3735
+ unmountHooks.push(() => { clearInterval(poll); scheduler.stop(); });
3736
+ }
3737
+ let schedView = "list";
3738
+ const refreshSched = () => {
3739
+ if (!schedStore)
3740
+ return;
3741
+ void schedStore.list().then((all) => {
3742
+ setSchedCount(all.filter((x) => x.enabled).length);
3743
+ if (menu?.classList.contains("ra-schm") && schedView === "list")
3744
+ drawSchedList(menu);
3745
+ }).catch(() => undefined);
3746
+ };
3747
+ const openSched = () => {
3748
+ if (menu) {
3749
+ const was = menu.classList.contains("ra-schm");
3750
+ closeMenu();
3751
+ if (was)
3752
+ return;
3753
+ }
3754
+ if (!schedStore)
3755
+ return;
3756
+ const mine = h("div", "ra-menu ra-skm ra-schm");
3757
+ menu = mine;
3758
+ placeMenu(mine);
3759
+ void drawSchedList(mine);
3760
+ };
3761
+ const drawSchedList = async (mine) => {
3762
+ schedView = "list";
3763
+ let all = [];
3764
+ try {
3765
+ all = await schedStore.list();
3766
+ }
3767
+ catch (err) {
3768
+ ui.notify(err.message, "error");
3769
+ }
3770
+ if (menu !== mine)
3771
+ return;
3772
+ all.sort((a, b) => (a.enabled === b.enabled ? (a.next ?? Infinity) - (b.next ?? Infinity) : a.enabled ? -1 : 1));
3773
+ mine.replaceChildren();
3774
+ const head = h("div", "ra-skh");
3775
+ const add = h("button", "ra-btn xs solid");
3776
+ add.type = "button";
3777
+ add.innerHTML = I.plus(13) + `<span>${escapeHTML(t.schedNew)}</span>`;
3778
+ add.addEventListener("click", () => drawSchedForm(mine, null));
3779
+ head.append(h("span", "", all.length ? `${t.sched} · ${all.length}` : t.sched), add);
3780
+ mine.append(head);
3781
+ if (!all.length)
3782
+ mine.append(h("div", "ra-none", t.schedNone));
3783
+ const statusWord = { ok: t.schedOk, error: t.schedErr, stopped: t.schedStopped };
3784
+ for (const task of all) {
3785
+ const row = h("div", "ra-mi" + (task.enabled ? "" : " ra-off"));
3786
+ const b = h("button");
3787
+ b.type = "button";
3788
+ b.title = t.schedEdit;
3789
+ const name = h("span", "ra-mt");
3790
+ const running = scheduler?.running.has(task.id);
3791
+ if (running)
3792
+ name.append(h("span", "ra-spin"));
3793
+ name.append(h("span", "ra-mtt", task.name));
3794
+ if (running)
3795
+ name.append(h("span", "ra-skb on", t.schedRunning));
3796
+ else if (!task.enabled)
3797
+ name.append(h("span", "ra-skb", t.schedPaused));
3798
+ if (task.by === "agent")
3799
+ name.append(h("span", "ra-skb", t.schedByAI));
3800
+ 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}`;
3801
+ b.append(name, h("small", "", when));
3802
+ if (task.last)
3803
+ 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})` : ""))));
3804
+ b.addEventListener("click", () => drawSchedForm(mine, task));
3805
+ 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; };
3806
+ const runB = act(I.play(), t.schedRunNow, () => {
3807
+ void scheduler.runNow(task.id).then((ok) => { if (!ok)
3808
+ ui.notify(t.schedBusy, "warning"); });
3809
+ setTimeout(refreshSched, 100);
3810
+ });
3811
+ const pauseB = act(task.enabled ? I.pause() : I.clock(13), task.enabled ? t.schedPause : t.schedResume, async () => {
3812
+ try {
3813
+ const cur = await schedStore.get(task.id);
3814
+ if (cur)
3815
+ await schedStore.put(changeTask(cur, { enabled: !cur.enabled }, schedLimits));
3816
+ }
3817
+ catch (err) {
3818
+ ui.notify(err.message, "error");
3819
+ }
3820
+ refreshSched();
3821
+ });
3822
+ const openB = act(I.message(), t.schedOpen, () => { closeMenu(); if (task.session)
3823
+ void resume(task.session).catch((err) => ui.notify(err.message, "error")); });
3824
+ if (!task.session || givenAgent || oneChat)
3825
+ openB.style.display = "none";
3826
+ const del = act(I.trash(), t.schedDel, async () => {
3827
+ closeMenu();
3828
+ if (!(await modalConfirm(root, t.schedDel, t.schedDelMsg.replace("{name}", task.name), { danger: true, ok: t.delete, cancel: t.cancel })))
3829
+ return;
3830
+ try {
3831
+ await schedStore.delete(task.id);
3832
+ }
3833
+ catch (err) {
3834
+ ui.notify(err.message, "error");
3835
+ }
3836
+ refreshSched();
3837
+ }, "ra-x");
3838
+ row.append(b, runB, pauseB, openB, del);
3839
+ mine.append(row);
3840
+ }
3841
+ mine.append(h("div", "ra-skf", t.schedHint));
3842
+ };
3843
+ /** The add / edit form, in the same menu. */
3844
+ const drawSchedForm = (mine, task) => {
3845
+ schedView = "form";
3846
+ for (const b of menuSelects.splice(0))
3847
+ b.close();
3848
+ mine.replaceChildren();
3849
+ const form = h("div", "ra-schf");
3850
+ const field = (label, ...els) => { const l = h("div", "ra-fld"); l.append(h("span", "", label), ...els); return l; };
3851
+ const nameIn = h("input");
3852
+ nameIn.type = "text";
3853
+ nameIn.placeholder = t.schedNamePh;
3854
+ nameIn.value = task?.name ?? "";
3855
+ const promptIn = h("textarea");
3856
+ promptIn.placeholder = t.schedPromptPh;
3857
+ promptIn.value = task?.prompt ?? "";
3858
+ const s0 = task?.schedule ?? { type: "daily", time: "09:00" };
3859
+ 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 });
3860
+ menuSelects.push(typeSel);
3861
+ // once
3862
+ const atIn = h("input");
3863
+ atIn.type = "datetime-local";
3864
+ const at0 = s0.type === "once" ? parseLocalTime(s0.at) : Date.now() + 3600_000;
3865
+ atIn.value = formatLocalTime(Number.isFinite(at0) ? at0 : Date.now() + 3600_000).replace(" ", "T");
3866
+ // every
3867
+ const everyN = h("input");
3868
+ everyN.type = "number";
3869
+ everyN.min = "1";
3870
+ everyN.step = "1";
3871
+ const m0 = s0.type === "every" ? s0.minutes : 60;
3872
+ const unit0 = m0 % 1440 === 0 ? "1440" : m0 % 60 === 0 ? "60" : "1";
3873
+ everyN.value = String(m0 / Number(unit0));
3874
+ const unitSel = selectBox(root, { options: [{ value: "1", label: t.schedMin }, { value: "60", label: t.schedHour }, { value: "1440", label: t.schedDay }], value: unit0 });
3875
+ menuSelects.push(unitSel);
3876
+ const everyRow = h("div", "ra-row");
3877
+ everyRow.append(everyN, unitSel.el);
3878
+ // daily
3879
+ const timeIn = h("input");
3880
+ timeIn.type = "time";
3881
+ timeIn.value = s0.type === "daily" ? s0.time : "09:00";
3882
+ const days = new Set(s0.type === "daily" && s0.days?.length ? s0.days : [0, 1, 2, 3, 4, 5, 6]);
3883
+ const dayRow = h("div", "ra-days");
3884
+ // Monday first.
3885
+ for (const d of [1, 2, 3, 4, 5, 6, 0]) {
3886
+ const db = h("button", days.has(d) ? "on" : "", dayNames[d]);
3887
+ db.type = "button";
3888
+ db.addEventListener("click", () => { if (days.has(d)) {
3889
+ if (days.size > 1)
3890
+ days.delete(d);
3891
+ }
3892
+ else
3893
+ days.add(d); db.classList.toggle("on", days.has(d)); preview(); });
3894
+ dayRow.append(db);
3895
+ }
3896
+ const dailyBox = h("div", "ra-row ra-col2");
3897
+ dailyBox.append(timeIn, dayRow);
3898
+ // cron
3899
+ const cronIn = h("input");
3900
+ cronIn.type = "text";
3901
+ cronIn.placeholder = "0 9 * * 1-5";
3902
+ cronIn.value = s0.type === "cron" ? s0.cron : "";
3903
+ const cronBox = h("div", "ra-fld");
3904
+ cronBox.append(cronIn, h("span", "ra-note", t.schedCronHint));
3905
+ const whenBox = h("div", "ra-fld");
3906
+ const note = h("div", "ra-note");
3907
+ const build = () => {
3908
+ switch (typeSel.value) {
3909
+ case "once": return { type: "once", at: atIn.value.replace("T", " ") };
3910
+ case "every": return { type: "every", minutes: Math.round(Number(everyN.value) * Number(unitSel.value)) };
3911
+ case "cron": return { type: "cron", cron: cronIn.value.trim() };
3912
+ default: return { type: "daily", time: timeIn.value, ...(days.size < 7 ? { days: [...days].sort((a, b) => a - b) } : {}) };
3913
+ }
3914
+ };
3915
+ const preview = () => {
3916
+ const sc = build();
3917
+ const problem = checkSchedule(sc, schedLimits.minMinutes ?? 5);
3918
+ const nx = problem ? null : nextRun(sc, Date.now());
3919
+ note.textContent = problem ?? (nx ? t.schedNext.replace("{time}", formatLocalTime(nx)) : t.schedNoNext);
3920
+ note.classList.toggle("err", !!problem || !nx);
3921
+ save.disabled = !!problem || !nx || !nameIn.value.trim() || !promptIn.value.trim();
3922
+ };
3923
+ const showType = () => {
3924
+ const v = typeSel.value;
3925
+ whenBox.replaceChildren(typeSel.el, ...(v === "once" ? [atIn] : v === "every" ? [everyRow] : v === "cron" ? [cronBox] : [dailyBox]));
3926
+ preview();
3927
+ };
3928
+ typeSel.el.addEventListener("change", showType);
3929
+ unitSel.el.addEventListener("change", preview);
3930
+ for (const el of [nameIn, promptIn, atIn, everyN, timeIn, cronIn])
3931
+ el.addEventListener("input", preview);
3932
+ const btns = h("div", "ra-btns");
3933
+ const cancel = h("button", "ra-btn xs ghost", t.cancel);
3934
+ cancel.type = "button";
3935
+ const save = h("button", "ra-btn xs solid", t.schedSave);
3936
+ save.type = "button";
3937
+ cancel.addEventListener("click", () => { for (const b of menuSelects.splice(0))
3938
+ b.close(); void drawSchedList(mine); });
3939
+ save.addEventListener("click", async () => {
3940
+ try {
3941
+ const fields = { name: nameIn.value, prompt: promptIn.value, schedule: build() };
3942
+ if (task) {
3943
+ const cur = await schedStore.get(task.id);
3944
+ if (!cur)
3945
+ throw new Error("gone");
3946
+ await schedStore.put(changeTask(cur, { ...fields, enabled: true }, schedLimits));
3947
+ }
3948
+ else {
3949
+ if ((await schedStore.list()).length >= (schedLimits.maxTasks ?? 20))
3950
+ throw new Error(`${schedLimits.maxTasks ?? 20} tasks at most`);
3951
+ await schedStore.put(makeTask({ ...fields, by: "user" }, schedLimits));
3952
+ }
3953
+ for (const b of menuSelects.splice(0))
3954
+ b.close();
3955
+ await drawSchedList(mine);
3956
+ refreshSched();
3957
+ }
3958
+ catch (err) {
3959
+ note.textContent = err.message;
3960
+ note.classList.add("err");
3961
+ }
3962
+ });
3963
+ btns.append(cancel, save);
3964
+ 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);
3965
+ mine.append(form);
3966
+ showType();
3967
+ queueMicrotask(() => (task ? promptIn : nameIn).focus());
3968
+ };
3969
+ schedBtn.addEventListener("click", () => openSched());
3970
+ refreshSched();
3522
3971
  const fail = (err) => ui.notify(err.message, "error");
3523
3972
  let compacting = false;
3524
3973
  /** The conversation as Markdown: what was said, and the tools each turn called. */
@@ -3643,7 +4092,7 @@ export function renderChat(target, opts) {
3643
4092
  compacting = true;
3644
4093
  let summary = null;
3645
4094
  try {
3646
- summary = await a.summarize(asked?.msg);
4095
+ summary = (await a.summarize?.(asked?.msg)) ?? null;
3647
4096
  }
3648
4097
  finally {
3649
4098
  compacting = false;
@@ -3653,7 +4102,7 @@ export function renderChat(target, opts) {
3653
4102
  await (oneChat ? clearConversation() : newSession().then(() => undefined));
3654
4103
  const b = agent;
3655
4104
  if (summary) {
3656
- await b.seed(summary);
4105
+ await b.seed?.(summary);
3657
4106
  renderHistory(b.messages);
3658
4107
  showUsage_(b);
3659
4108
  }
@@ -3847,7 +4296,7 @@ export function renderChat(target, opts) {
3847
4296
  ];
3848
4297
  /** The built-ins this chat offers now (the files, settings and debug ones only where their button shows). */
3849
4298
  const builtinCommands = () => builtins
3850
- .filter((b) => (b.name !== "files" || (!!agent?.workspace && filesOpt !== false)) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || (!givenAgent && !!agent?.workspace && !oneChat)))
4299
+ .filter((b) => (!commandsOpt || commandsOpt.includes(b.name)) && (b.name !== "files" || (!!agent?.workspace && filesOpt !== false)) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || (!givenAgent && !!agent?.workspace && !oneChat)))
3851
4300
  .map((b) => ({ name: b.name, description: b.name === "new" && oneChat ? t.confirmClear.split(/[??]/)[0] : t.cmd[b.name] ?? "", kind: t.command, args: b.args, builtin: true }));
3852
4301
  /** `/name [arg]` naming a built-in: run it here (nothing goes to the model). */
3853
4302
  const runBuiltin = (text) => {
@@ -3908,7 +4357,7 @@ export function renderChat(target, opts) {
3908
4357
  };
3909
4358
  const cap = (x) => x.charAt(0).toUpperCase() + x.slice(1);
3910
4359
  /** "Auto-compaction: when less than 16k tokens are left" (or Auto-trim), as the agent will do it now. */
3911
- const compactLine = (a, window) => { const c = a.compactionFor(window); return `${c.summarize ? t.autoCompact : t.autoTrim}: ${t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens))}`; };
4360
+ const compactLine = (a, window) => { const c = a.compactionFor(window); return `${c.summarize ? t.autoCompact : t.autoTrim}: ${c.reserveTokens > 0 ? t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens)) : t.autoCompactFull}`; };
3912
4361
  const pctOf = (used, window) => { const p = used / window; return used && p < 0.01 ? "<1%" : `${Math.round(Math.min(1, p) * 100)}%`; };
3913
4362
  /** The usage panel: how full the context is, what the conversation has cost, and Compact now. */
3914
4363
  const fillUsage = (panel, a, c) => {
@@ -3982,6 +4431,7 @@ export function renderChat(target, opts) {
3982
4431
  for (const u of unsub)
3983
4432
  u();
3984
4433
  unsub = [];
4434
+ hideToolsOf(a);
3985
4435
  // Skills added or removed anywhere (the menu, the agent, another tab): the count and the / list follow.
3986
4436
  if (a.workspace) {
3987
4437
  const ws = a.workspace;
@@ -4073,6 +4523,22 @@ export function renderChat(target, opts) {
4073
4523
  renderHistory(a.messages);
4074
4524
  showUsage_(a);
4075
4525
  } });
4526
+ on("history", (ev) => {
4527
+ if (agent !== a)
4528
+ return;
4529
+ const before = list.length, hadOlder = before > 0 && list.rows[0]?.el?.classList.contains("ra-olderrow") === true;
4530
+ const following = list.follow, top = log.scrollTop;
4531
+ renderHistory(a.messages);
4532
+ // The row that was first is now further down by what came in before it.
4533
+ if (ev.reason === "older")
4534
+ list.scrollToIndex(Math.max(0, list.length - (before - (hadOlder ? 1 : 0))));
4535
+ else if (ev.reason === "newer" && !following) {
4536
+ list.follow = false;
4537
+ log.scrollTop = top;
4538
+ list.layout();
4539
+ }
4540
+ showUsage_(a);
4541
+ });
4076
4542
  on("text_delta", (ev) => {
4077
4543
  const act = ensureActive();
4078
4544
  clearPending(act);
@@ -4179,7 +4645,7 @@ export function renderChat(target, opts) {
4179
4645
  if (!ev.summary)
4180
4646
  trimNoted = ev.runId ?? null;
4181
4647
  const first = a.messages[0];
4182
- const s = first && typeof first.content === "string" ? summaryOf(first) : null;
4648
+ const s = ev.summaryText ?? (first && typeof first.content === "string" ? summaryOf(first) : null);
4183
4649
  addNote(ev.summary ? t.compacted : t.trimmed, ev.summary && s ? s : undefined);
4184
4650
  });
4185
4651
  on("run_end", (r) => {
@@ -4258,7 +4724,7 @@ export function renderChat(target, opts) {
4258
4724
  return agent;
4259
4725
  const prev = agent;
4260
4726
  if (prev) {
4261
- if (prev.busy || prev.queued.length > 0) {
4727
+ if (prev.busy || (prev.queued?.length ?? 0) > 0) {
4262
4728
  if (background().length >= MAX_BACKGROUND) {
4263
4729
  ui.notify(t.bgLimit.replace("{n}", String(background().length)), "warning");
4264
4730
  return prev;
@@ -4284,7 +4750,7 @@ export function renderChat(target, opts) {
4284
4750
  await ready;
4285
4751
  const a = agent ?? givenAgent;
4286
4752
  ui.cancelAll();
4287
- await a.clear();
4753
+ await a.clear?.();
4288
4754
  if (agent === a || givenAgent === a) {
4289
4755
  renderHistory(a.messages);
4290
4756
  showUsage_(a);
@@ -4331,6 +4797,10 @@ export function renderChat(target, opts) {
4331
4797
  const firstId = agentOpts.id ?? (typeof resumeOpt === "string" ? resumeOpt : resumeOpt === false ? undefined : readLast(project) ?? undefined);
4332
4798
  const starting = givenAgent ? Promise.resolve(givenAgent) : makeAgent(firstId);
4333
4799
  const ready = starting.then((a) => attach(a));
4800
+ // Scheduled tasks start once the first conversation is open.
4801
+ if (scheduler)
4802
+ void ready.then(() => { if (mounted)
4803
+ scheduler.start(); }).catch(() => undefined);
4334
4804
  ready.catch((err) => {
4335
4805
  // No session could be opened (the workspace factory or the agent threw): say so instead of a dead chat.
4336
4806
  addError(`${err.message}`);
@@ -4365,6 +4835,7 @@ export function renderChat(target, opts) {
4365
4835
  clear: clearConversation,
4366
4836
  addContext,
4367
4837
  setDebug(on) { debugOn = on; applyDebug(); },
4838
+ setTitle(text) { titleEl.textContent = text; },
4368
4839
  updateComposerAction(id, patch) { const e = actionBtns.get(id); if (!e)
4369
4840
  return; Object.assign(e.a, patch); drawAction(e.btn, e.a); },
4370
4841
  setAppearance(o) {
@@ -4385,6 +4856,12 @@ export function renderChat(target, opts) {
4385
4856
  clearTimeout(histTimer);
4386
4857
  for (const u of unsub)
4387
4858
  u();
4859
+ for (const u of unmountHooks.splice(0)) {
4860
+ try {
4861
+ u();
4862
+ }
4863
+ catch { /* keep going */ }
4864
+ }
4388
4865
  ui.cancelAll(true);
4389
4866
  closeMenu();
4390
4867
  document.removeEventListener("click", onDocClick, true);