deer-flow/frontend/AGENTS.md
Totoro 35cdcab1c5
feat(scheduled-tasks): signals, honest notices and fair queueing for server-started runs (RFC #6340, 2/2) (#6393)
* feat(scheduler): lifecycle rules, goal/limit parity and coded errors for scheduled tasks

- Migration 0031: nullable scheduled_tasks.unmet_streak_after_seq (internal
  streak boundary) and stop_condition (the user's stop rule, own column).
- Stop rule is normalized (stop_rule.py) and appended only at launch; the
  stored prompt never contains it. Wording adapts when scheduler.tool_enabled
  is off.
- Willem 1: page-created tasks get goal evaluation, <standing_notes>, the
  previous-run reference and own-schedule stop; request_stop and the
  scheduled capability no longer require an origin conversation.
- Repository: single reactivation choke point raising
  ScheduledTaskLimitsExhausted; streak boundary moves on goal/prompt/stop
  condition/note changes (not on resume); goal-check failures neither count
  nor reset the streak; pause of a finished task returns "finished"; trials
  on a paused task keep the host pause marker.
- New repository reads: automatic_runs_used_for, active_run_status_for,
  list_manageable_from_thread, thread_relation/thread_run on thread tasks,
  task_ids_for_thread, run_number, and run_number/total_tokens/summary on
  run history rows.
- REST: goal/max_runs/end_at/stop_condition on create and PATCH (null
  clears, naive end_at = task timezone), resume recomputes from now with an
  optional renewal body, once_time_passed, task_finished, limits_exhausted,
  scheduler_not_running on create, trigger returns outcome/existing/thread_id,
  task responses add automatic_runs_used and active_run_status.
- Coded errors {code, message, params} for routes, shared validation and the
  chat capability (scheduled_task_errors.py), pinned by
  contracts/scheduled_task_errors_contract.json; goal notes contract v2 with
  check_failure_codes, scheduled_origin_key and host_run_errors (host_notes.py).
- /api/features adds scheduled_tasks {available, running, tool_enabled,
  min_interval_seconds}; ScheduledTaskService.is_running.
- Docs: six README scheduler sections, API.md scheduled tasks section
  (breaking error shape), CONFIGURATION.md, AGENTS notes, CHANGELOGs.
- Tests: migration 0031, stop rule, error contract, run listing, lifecycle
  over HTTP, repository, service and capability cases; updated tests for the
  new error shape, finished-task pause and head revision.

* feat(scheduler): conversation update/resume, run-conversation authority and readable launches

- schedule_task: update and resume actions, stop_condition and clear_fields
  parameters, plain parameter types (value rules come back as coded results),
  rewritten docstrings for schedule_task and stop_scheduled_task.
- Capability: update/resume share the REST validation and error codes;
  interactive turns in a task's run conversation may manage that task;
  scheduled runs keep only own-stop; grants require a running scheduler.
- Results: compact JSON-safe task views with local times, display card/text,
  last run in list, timezone_source/browser_timezone, now_local; no ISO, user,
  lease or origin fields; stop_instructions removed.
- Timezone: explicit > browser (context.client_timezone, validated in
  start_run and never forwarded to the run config) > not needed for intervals
  and offset run_at > timezone_required.
- Trial gate accepts natural direct requests after acknowledgements and
  particles; trial results report thread_id and existing.
- Scheduled launches: stable message id scheduled-<task_run_id>, server-owned
  deerflow_scheduled_origin metadata with the user-language parts, run thread
  title for fresh-thread tasks.
- Worker records goal continuations in the verdict; lead prompt language rule
  covers stored task text and scheduled runs.
- Docs: six READMEs, CONFIGURATION, API, runtime/tools AGENTS, CHANGELOGs.

* feat(frontend): scheduled-task core types, formatting, errors and glossary

- throwGatewayApiError now throws GatewayApiError (status, code, params,
  rawMessage); message stays the string detail or detail.message
- scheduled-task types gain stop_condition, automatic_runs_used,
  active_run_status, origin/notes, run_number/total_tokens/summary, thread
  relation, trigger result, renewal and scheduled origin; isTaskBusy and
  hasActiveRun helpers
- api: fetchScheduledTask, resume with optional renewal body, typed trigger
  result and update payload with null clears
- hooks: polling at 3 s while a run is active (list, thread list, run
  history), useScheduledTask with live gating and final 404, useInView,
  localized error toasts; run history refreshes tasks when a run finishes
- new pure modules: errors.ts (contract code to localized copy), format.ts
  (relative task times, viewer time, display zone), status.ts, actions.ts,
  run-error.ts; describeTaskSchedule in cron.ts; goal-outcome adds unchecked
  goal checks, describeTaskOutcome and parseStopRunId
- features: scheduled_tasks block with defaults when missing
- buildRunContext sends client_timezone
- titleOfThread takes a localized untitled label; breadcrumb names scheduled
  tasks and agents; reference chips use the localized untitled label
- schedule input: shared browserTimeZone, labelled selects, aria-pressed
  type toggles, interval minimum from the hint template
- i18n: all PR1 scheduled-task keys in en-US and zh-CN, glossary fixes,
  recipe instructions moved into i18n
- e2e mocks follow the new task, trigger, resume, thread-task and features
  shapes; expectNoRawIdentifiers helpers for e2e and DOM tests
- tests for errors, format, cron, status, actions, goal outcome, run errors,
  hooks, run context, thread titles and features; scheduled e2e copy updated

* feat(frontend): list-first scheduled tasks page with outcomes and editable goals

- page.tsx is now a thin composition of components/workspace/scheduled-tasks:
  status tabs (All/Active/Paused/Finished) and search over the task list,
  ?task_id= deep link with router.replace on selection, ?thread_id= chip
  with Show all, empty state, scheduler-off notice and unavailable state
- task list rows show the schedule in words and one status line (next run,
  running now, paused by agent, auto-paused, finished by its cap)
- task detail: status badge, actions from availableActions with reasons,
  More actions menu (Duplicate, Copy task ID, Delete), outcome notice,
  Runs / Stops when / Each run's goal / Does / Notes from chat / History,
  origin chat link; success toasts for every action
- run rows: run number or Trial run, summary, goal and assumption badges,
  continuations, tokens, Open chat link; raw errors and the evaluator
  reason only behind Details
- create/edit/duplicate dialog with goal, stop condition, safety caps and
  advanced agent/context options; PATCH sends only changed fields, null
  clears a cap
- renew dialog raises or removes caps and resumes in one request; a
  limits_exhausted Resume opens it
- removed i18n keys the old page used; added feedback.resumedNoTime
- recorded en-3 and zh-1 page fixtures; scheduled e2e specs rewritten for
  the new page; DOM tests for the detail and the form dialog
- CHANGELOG entries and the frontend AGENTS.md scheduled-task note

* feat(frontend): live schedule card, run conversation provenance and header entry

- schedule_task results (create, update, pause, resume, trial, delete) become
  an assistant:scheduled-task message group rendered as a live card: schedule,
  next run, stop condition with the safety cap, goal, where results go, Run
  once now, Pause/Resume and Open task; the card polls the task only while it
  is on screen and shows deleted, scheduler-off and limits-exhausted states
- one card per task per assistant turn; the card group is not a turn boundary
  for usage, branching, editing, outline or skill attribution
- a human message with deerflow_scheduled_origin stays a human group with
  scheduledOrigin and renders as a "Scheduled run / Trial run" block with the
  task instructions, stop condition and notes collapsed; the launched text is
  never shown and the message is not editable
- readable step labels for schedule_task actions and stop_scheduled_task
- ThreadScheduledTasksButton replaces the header link: hidden without tasks,
  shows the count, links to the task (or the chat filter), and a run's chat
  links to its task
- recorded en-3 / zh-1 chat and run-thread fixtures; chat-card and run-thread
  e2e specs; unit and DOM tests for parsing, grouping, turn boundaries, card,
  run block, header button, step labels and reconnect hydration
- i18n: header.countLabelOne added, unused card.next removed; CHANGELOG and
  frontend AGENTS.md notes

* fix(scheduler): address verification findings

Move the scheduled-task lifecycle guidance from backend/AGENTS.md into the persistence guide and leave a one-line pointer, so the effective AGENTS.md chains for agents/middlewares, sandbox and subagents stay under the 98304-byte hard limit enforced by scripts/check_agent_guidance.py in lint-check.

* fix(scheduler): address review findings

* fix(gateway): no-transform on SSE responses

All four text/event-stream responses (thread run create stream, join,
existing-run GET/POST stream, stateless create stream) now take their
headers from app/gateway/sse_headers.py and send
Cache-Control: no-cache, no-transform, so compressing proxies such as
Next's rewrite proxy stop buffering streams. Content-Location and
X-Accel-Buffering are unchanged; scheduled and MCP-notification runs keep
stream_mode=None.

Tests pin the headers on every SSE route and fail on a literal no-cache
header left in routers. Docs: API.md SSE headers note, CHANGELOGs.

* feat(scheduler): per-owner run cap and fair queue selection

New scheduler.max_concurrent_runs_per_user (default 2, 0 = off, effective
min(cap, max_concurrent_runs)) caps launching/running scheduled runs per task
owner. claim_queued_run checks it right after the global count under the same
budget lock, so it is atomic across workers and Pods. list_queued_runs ranks
same-thread FIFO heads per owner with ROW_NUMBER() OVER (PARTITION BY owner)
and orders the batch by that rank, so the drain is owner-fair even with the
cap off; owners at their cap drop out before the batch limit. Orphan rows
(task deleted while queued) are never held back by the cap.

Gateway lifespan passes the startup value; the service constructor default
stays 0. Docs: config.example.yaml (config_version 54), CONFIGURATION.md,
the six READMEs, backend AGENTS.md, CHANGELOGs (behavior change flagged).
The live-task quota is untouched.

* feat(scheduler): durable lifecycle events for the originating chat

When a chat-created schedule is paused by the agent, auto-paused or finishes,
finalization now reports task_stopped / task_paused / task_finished, only on a
live -> paused/finished transition. The new finish_task_at_end_condition
replaces the three inline "mark completed" blocks (admission rejected as ended,
claim-time skip, complete_if_ended), so every site emits exactly once.

The scheduler's finalization observer is always installed. It writes
scheduled_task_events rows for the originating chat in the same transaction as
the state change, deduplicated on (task_id, anchor, event), with a title
snapshot, stop condition, run number, last run outcome and the chat's newest
run as placement anchor. Lookups fall back on bad stored data; only database
errors propagate. Manual trials drop only run_* events. The IM step keeps
PR1's selection until B4.

New GET /api/threads/{thread_id}/scheduled-task-events (owner check, caller's
rows, oldest first); rows survive task deletion and go with the chat.
Migration 0032_activity_and_task_events adds the events table plus the
run-origin column/index and read-state tables used later, each object guarded
on its own. Contract scheduled_goal_notes v3 pins the lifecycle vocabulary.
Docs: API.md, migrations chain, backend AGENTS.md, six READMEs, CHANGELOGs.

* feat(scheduler): honest, localized and self-contained IM notices

Every scheduled-task IM notice is now enqueued by the finalization observer
in the transaction that records the outcome, one message per occurrence
(task_stopped > task_paused > task_finished > run_failed > run_unmet >
run_completed; a once task sends only its run event). The merged auto-pause
replaces the separate unmet + pause messages, agent stops and finishes now
notify, and recovery-finalized runs notify exactly once. Idle finishes use a
deterministic idle: key derived from the lifecycle anchor. The old
non-transactional enqueue in handle_run_completion is removed.

New app/channels/capabilities.py holds CHANNEL_CAPABILITIES with a
proactive_notifications flag (adds the missing qq entry); only push-capable
providers (WeCom) get rows, /api/channels/providers returns the flag, and the
worker ends legacy rows for other providers as terminal failed.

New app/scheduler/notification_text.py renders en-US/zh-CN text: title, what
happened (plus the last run's outcome), the tasks page's one-line run summary
(redacted) when the agent replied, and a closing line. No IDs, no links, no
public_base_url. Locale is the owner's new `locale` preference, else the new
channel_connections.notification_locale (default en-US).

Docs: config.example.yaml (config_version 55), CONFIGURATION.md, API.md,
channels AGENTS.md, six READMEs, CHANGELOGs (behavior change flagged).

* feat(gateway): thread origin, activity feed and read markers for server-created threads

Runs started by the server for a user (scheduler, IM channels, GitHub
agents, extension handles, MCP notifications) now carry a server-owned
metadata.deerflow_origin {kind, provider?, namespace?} (new harness module
deerflow.runtime.run_origin, pinned by contracts/thread_origin_contract.json).
It is stamped only from request.state.run_origin or by the internal channel
caller; run admission drops client copies from both metadata and
config.metadata, and thread create/patch strip it. RunRepository derives
runs.origin_kind on put and on create_thread_operation_atomic (agent runs
only), and gains latest_change().

New ThreadReadRepository keeps a per-user, never-decreasing read position
(thread_read_markers) and a per-user read clock (thread_read_versions).
POST /api/threads/{id}/read marks a thread read, thread search items carry
unread, and thread delete removes the markers. GET /api/thread-activity pages
the caller's run changes over the run-change clock, returns only threads
changed by server-originated runs plus read_version, and 503s without SQL;
/api/features reports thread_activity.available.

Docs: API.md, gateway AGENTS.md (condensed to stay under its budget),
CHANGELOGs.

* fix(scheduler): adapt PR2 to PR1 follow-ups

PR1 moved the scheduled-task lifecycle rules out of backend/AGENTS.md into
the persistence guide and grew the sandbox AGENTS.md chain to within 267
bytes of its hard limit. The per-owner queue-fairness detail now lives in
the persistence guide next to the lifecycle rules (backend/AGENTS.md keeps
the cap and a link), so check_agent_guidance passes again.

PR1's goal-outcome unit test pinned scheduled_goal_notes_contract version 2;
PR2 bumps it to 3 (lifecycle vocabulary only, the v2 keys are unchanged).

* fix(scheduled-tasks): polish from live acceptance

- zh schedule wording: an interval of one unit reads 每分钟 / 每小时 / 每秒,
  and a saved interval of whole days reads 每天 / 每 2 天 (Every day / Every 2
  days) instead of 每 1 分钟 or 每 24 小时; several units keep the number
- zh spacing: 已于{time} 满足 and 在{time} 的运行中 now leave a space between
  the interpolated time and the Chinese after it; a copy test guards every
  scheduled-task zh string against a placeholder glued to Chinese
- run summary: when the first line of the final reply only leads in to a list
  (ends with ":" or ":"), the list items follow it as plain text (bullets,
  numbering, checkboxes, bold, code and links stripped), joined with ";" for
  CJK text and "; " otherwise, within the 160-character cap
- a schedule_task result (create, update, pause, resume, trial, delete) that
  arrives in a chat invalidates that chat's task list, the tasks list and the
  named task, so the header button and cards update without waiting for the
  idle poll; results already in the loaded history do not refetch
- e2e and unit fixtures are now the live acceptance recordings (DeepSeek
  Flash, demo data, fictional names): live-weekday.json (create, trial, edit,
  pause, resume in one zh chat) and live-minute.json (per-minute chat, run 1
  and run 2, paused by the agent), fetched with GET from the demo Gateway and
  trimmed; the hand-shaped en-3 / zh-1 fixtures are removed and the chat-card,
  run-thread and tasks-page specs run in both locales over the recorded data

* docs(changelog): reference #6378 for the scheduled-tasks entries

* docs(agents): shorten the scheduled-task pointer to stay under the guidance limit

* test(scheduled-tasks): pin the live takes to their recorded time zone

The live fixtures were recorded in Asia/Shanghai, and an interval task
reads in the viewer's zone, so the 16:48 assertions failed on UTC CI
runners. Pin the browser zone in the two live-take e2e specs and the
zh live-take unit test.

* feat(frontend): thread origin, activity polling, read markers and task events core

Frontend core for server-created threads and schedule lifecycle events
(PR2 F1); the sidebar markers (F2) and the chat event line (F3) build on it.

- core/threads/origin.ts: threadOriginOf reads metadata.deerflow_origin,
  then channel_source (github -> GitHub origin), then a legacy
  scheduled_task_id; key and kinds pinned to
  contracts/thread_origin_contract.json. labelOfThreadOrigin and the now
  exported labelOfChannelProvider(provider, t) use the new localized
  threads.origin.providers names (飞书, 企业微信, ...), with the English map
  (gaining GitHub) only as the fallback.
- core/threads/activity.ts: useThreadActivity polls /api/thread-activity
  every 15 s (focus refetch, never in the background, off unless
  features.thread_activity.available). The first response only seeds the
  cursor; server-origin threads, a truncated page or a higher read_version
  invalidate the thread lists, a scheduled thread also ["scheduled-tasks"];
  an invalid cursor re-seeds. useMarkThreadRead debounces POST /read by 1 s,
  skips a thread whose cached unread is false, patches the search and
  infinite caches optimistically and stores the returned read_version so a
  tab's own read does not refetch its lists. AgentThread gains unread.
- core/scheduled-tasks/events.ts: ScheduledTaskEvent, the events query
  (["scheduled-tasks","thread-events",id], one fetch per saved chat, not
  gated on the task list so a deleted task's lines stay, refetched when a
  task of the chat changes status or finishes a run), describeTaskEvent
  (en/zh copy, title and condition as segments, last-run suffix, See that
  run / Open task) and placeTaskEvents (end of the after_run_id turn, else
  the tail, ordered by created_at); lifecycle names pinned to contract v3.
- features: thread_activity (default unavailable); channels:
  proactive_notifications on providers.
- Locale sync: the I18nProvider reports the UI language and a signed-in
  preference session saves it as the new `locale` preference when the
  account's differs (and on every switch), so IM notices follow the UI
  language; nothing is written with auth disabled.
- i18n: threads.* (unread, origin labels, provider names),
  scheduledTasks.events.*, history.waitingForSlot (now shown for queued run
  rows), channels.scheduledUpdates.*.
- e2e mocks: thread activity feed and controller, POST /read, the events
  route, providers with proactive_notifications, search unread, features
  thread_activity (off by default). Preference e2e mocks return the UI
  locale so they keep asserting only their own edits.
- Docs: frontend AGENTS.md, CHANGELOGs.

* fix(scheduled-tasks): keep untouched end times and drop a chat filter the new task is not in

- The edit, duplicate and renew dialogs keep a stored end time's instant
  while its field still shows it. A minute-precision wall value cannot
  keep seconds or name the later 01:30 of a DST fall-back, so a
  title-only edit moved the cap an hour earlier, and raising the run
  limit re-sent the end time without its seconds.
- Creating or duplicating a task from a chat's task view drops the chat
  filter when the new task does not belong to that chat, instead of
  showing "This task isn't one of this chat's tasks".

* feat(frontend): origin markers and unread state in the thread lists

Server-created threads (PR2 F2) now say who created them and whether they
are new, in the sidebar and on the Chats page, and reach an open sidebar
without a reload.

- ThreadOriginIcon (thread-channel-source.tsx): clock for a scheduled run,
  the provider mark for IM threads, the GitHub mark (new in
  ChannelProviderIcon) for GitHub threads, a puzzle piece for extensions;
  the localized "Scheduled run" / "From Feishu" / "From GitHub" / "From an
  extension" label is its accessible name and tooltip. ThreadChannelIcon
  stays exported as a wrapper, and the provider chip tooltip is localized
  (no more "Feishu channel").
- Unread dot after the title (aria-hidden dot plus sr-only "Unread"); the
  row aria-label becomes "{title}, unread" / "{title},未读". Never shown for
  the open thread.
- WorkspaceSidebar mounts useThreadActivity once.
- useMarkOpenThreadRead (components/workspace/chats): the default and
  custom-agent chat pages mark the thread read once its metadata has
  loaded, when its cached unread flips to true while open, when the tab
  becomes visible, and from onFinish (a send or a joined run ended). Each
  trigger goes through useMarkThreadRead, so it is debounced and a no-op
  while the cached unread is false.
- Tests: thread-origin-icon and recent-chat-list DOM tests (en/zh, active
  row, no raw identifiers), use-mark-open-thread-read DOM tests,
  e2e thread-activity.spec.ts (new scheduled run appears unread within one
  fake-clock poll without a reload, opening it posts /read and clears the
  dot, a read on another device clears it, IM and GitHub markers, zh
  labels, the Chats page, no polling when unavailable);
  thread-history.spec.ts now finds the localized origin icon.
- Docs: frontend AGENTS.md, CHANGELOGs.

* feat(frontend): schedule event line in the originating chat and channel notice support

The chat that created a schedule now says when the schedule paused or
ended, and the channel cards say which apps receive scheduled task updates
(PR2 F3).

- ScheduledTaskEventLine (mockup m2, marker 4): a dashed, muted row with
  the describeTaskEvent text (title in <strong>, stop condition clamped to
  one line with the full text in its tooltip, last-run suffix), the time
  via formatTaskTime and a right-aligned "See that run" (run chat) or
  "Open task" link. PauseCircle for paused, CircleCheck for finished and
  once-done, CircleX for once-failed. role="note", aria-label "Scheduled
  task update" / "定时任务通知", data-task-id and data-event-id only.
- MessageList takes scheduledTaskEvents and renders placeTaskEvents output
  through a new VirtualMessageList.renderAfterGroup, so each line sits at
  the end of its after_run_id turn inside the group's measured row (also
  when the list virtualizes); lines with nowhere to go render at the tail.
- Both chat pages load useThreadScheduledTaskEvents (not gated on the task
  list, so the lines stay after a task is deleted). The custom-agent page
  passes its agent so "See that run" opens the run on that agent's route.
- ChannelScheduledUpdates: "Scheduled task updates: sent here" / "... not
  available for this app yet" (定时任务通知:会发送到这里 / 此应用暂不支持)
  on the Settings provider cards and under each sidebar channel row; nothing
  when an older backend does not report proactive_notifications.
- e2e mock controller: setScheduledTasks.
- Tests: scheduled-task-event-line and channel-scheduled-updates DOM tests
  (every kind in en and zh, hrefs, clamp, no raw identifiers, Chinese
  title), MessageList placement DOM tests; e2e
  scheduled-task-chat-events.spec.ts (the line appears with the card's
  "Paused by agent" without a reload, See that run opens the run chat,
  anchored vs tail placement, two events in time order, the line survives
  task deletion and Open task shows the task is gone; en-3 and zh-1) and
  channels.spec.ts (WeCom sent here, Feishu not yet; en and zh).
- Docs: frontend AGENTS.md, CHANGELOGs.

* fix(scheduled-tasks): tie pause notices to the pause they describe

- Paused by agent links and times only the run named in last_error. When
  that run is not loaded, the notice shows no link and the task's own time
  instead of an earlier run that also asked to stop.
- The outcome notice reads the latest history page whichever page is
  shown, so browsing older runs no longer swaps the auto-pause reason and
  "Open latest run" to an earlier miss. It shares that page's request.

* fix(scheduler): address PR2 review findings

- Event lines: hold an event whose anchor run is on an unloaded history
  page instead of placing it at the bottom (hasMoreHistory); tail fallback
  only for fully loaded (branched/pruned) history or no anchor.
- Idle-finish anchor follows its reason: end:<iso> only for an end_at
  finish, seq:<n> otherwise, so a later end-time finish is not deduplicated
  away by an earlier max_runs finish.
- Observer takes FOR SHARE on the originating threads_meta row, so a racing
  thread delete cannot leave an orphan event line.
- One taskPagePath (core), re-exported by the card.
- Notification locales derived from NotificationLocale; /preferences uses it.
- IM notices drop generic reasons (goal_not_met_yet, unknown) instead of
  repeating the sentence.
- Localized provider names on Settings cards, sidebar rows and setup dialog.
- zh event lines: no space after a Chinese title (Latin-aware gap).
- Unread row label keeps the origin marker; chats page keeps the time as a
  description.
- Sidebar shows the scheduled-updates line only for connected apps;
  Settings says "available after you connect" for unconnected push apps.
- Event line keeps a real space before the time.

* fix(scheduled-tasks): three lifecycle gaps found while re-checking review classes

- The edit form compares a cron in the form its schedule input emits, so an
  untouched "0 09 * * 0,6" is not re-sent as "0 9 * * 6,0" and a title-only
  edit no longer re-arms or refuses a finished task.
- Chat resume asks for a timezone, as update does, when a naive end_at would
  land in the UTC placeholder of a zone-free task.
- Re-arming a task clears a host pause marker, as resume does, so a later
  manual pause no longer reads as "Paused by agent".

* test(scheduler): consolidate PR2 backend test setup

- Fold the repeated task, origin-chat and observer setup of the
  lifecycle-event repository tests into one lifecycle_task builder.
- Build the per-owner-cap services through one _capped_service builder
  that keeps every cap explicit at the call site.
- Table the five SSE route header checks into one parametrized test with
  the same routes, bodies and Content-Location expectations.
- Reuse bind_wecom and hoist repeated local imports in the event tests.

Every case and assertion is kept; collected cases are unchanged.

* test(frontend): consolidate PR2 thread activity and origin test setup

Extract shared builders and helpers in the frontend tests PR2 adds, with
every case, input and assertion kept:

- activity.test.ts: seededClient/apply helpers and one LIST_KEYS constant
  replace the per-test seed, spy and apply boilerplate.
- mark-read.dom.test.tsx: newClient() and advance() replace the repeated
  QueryClient wrapper and fake-timer act blocks.
- origin.test.ts: the English and Chinese label checks become tables; the
  no-English-name check now runs on every Chinese row.
- thread-activity.spec.ts: a scheduledRun() builder replaces four inline
  copies of the scheduled run thread.
- channels.spec.ts: the PR2 block uses setLocaleCookie and one card helper.

Collected cases are unchanged (unit 211, e2e 60); no test was removed.

* fix(scheduled-tasks): keep the notice's latest-runs query from refreshing older pages

useLatestScheduledTaskRuns kept React Query's default refetch on mount,
focus and reconnect, so going offline and back while an older history page
was shown fetched the latest page again. Refreshing stays with the history,
which refreshes the latest page only while it is shown.

* fix(scheduler): two gaps found in live acceptance

- A fresh scheduled run thread is named when it launches. The worker
  copied the title to the thread list only when the run ended, so the
  sidebar, which now shows the new run thread at once, listed it as
  untitled while it ran.
- A task capped at one run finishes with "its one run is done" /
  "唯一一次运行已完成" in the chat event line and the IM notice, instead
  of "all 1 runs are done".

* test(scheduled-tasks): let the viewer's time carry its own day label

Between 16:00 and 24:00 UTC, UTC and Asia/Shanghai are on different days,
so the run prompt shows "Tomorrow 01:00 · Today 09:00 your time" and the
fixed "01:00 · 09:00 your time" assertion failed depending on the hour.

* test(scheduler): expect the one-run finish copy in service notices

* fix(gateway): create a scheduled run thread with its title

Pre-setting the name after start_run raced the thread row, which the run
worker creates asynchronously: live, one of two run threads still reached
the sidebar untitled. Run admission now creates a new thread with the title
its run input carries, which the worker would copy only at run end.

* docs(changelog): reference #6393 for the scheduled-task signal entries

* fix(scheduled-tasks): route event-line run links by the agent that ran them

The originating chat's agent was used for "See that run", but a task's
agent can change after the chat created it, so the link could open the run
chat on another agent's route. Lifecycle events now record run_agent_name,
the task's agent when the run finished (edits are refused while a run is
active), and the line routes by it.

* fix(scheduled-tasks): load up to the route's maximum of chat event lines

The chat loads its lifecycle events once, and the route's default of 50
would silently drop the oldest lines of a chat with many schedules. Ask
for the maximum, 200.

* fix(threads): keep activity reads and the first cursor in step with the lists

- Accepting the first activity cursor refreshes the thread lists once. The
  lists load on their own, possibly before a run the seed already counts,
  and later polls start after it, so such a thread never appeared.
- A local read whose returned read clock jumps past that one read also
  covers reads on other devices; the lists are refreshed instead of the
  clock silently skipping those threads' stale unread dots.
- An invalid cursor re-seeds through the same path, so it refreshes once.

* docs(agents): bring the middlewares guidance chain back under the hard limit

#6378 and #6363 each fit the budget, but together the middlewares AGENTS.md
chain on main is 98,425 bytes, 121 over the 98,304 hard limit, so Lint
Check fails on main. Move the scheduled-task recovery, launch-update and
queue-timeout rules from backend/AGENTS.md into the persistence guide's
lifecycle section, which backend/AGENTS.md already points to. The chain is
now 98,067 bytes.

* fix(helm): bump the chart's config_version to 55

config.example.yaml moved to 55 in this PR, so the Helm chart's
validate-chart drift check failed. The chart's embedded config needs no
field changes: the new scheduler and channel keys have defaults.

---------

Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
2026-10-07 10:22:15 +08:00

29 KiB

AGENTS.md

This file provides guidance to AI coding agents (Claude Code, Codex, and others) when working with the DeerFlow frontend. It is the source of truth; the sibling CLAUDE.md imports it via @AGENTS.md.

Project Overview

DeerFlow Frontend is a Next.js 16 web interface for an AI agent system. It communicates with a LangGraph-based backend to provide thread-based AI conversations with streaming responses, artifacts, and a skills/tools system.

Stack: Next.js 16, React 19, TypeScript 5.8, Tailwind CSS 4, pnpm 10.26.2. Requires Node.js 22+ and pnpm 10.26.2+.

Core dependencies

  • LangGraph SDK (@langchain/langgraph-sdk ^1.5.3) — Agent orchestration and streaming
  • LangChain Core (@langchain/core ^1.1.15) — Fundamental AI building blocks
  • TanStack Query (@tanstack/react-query ^5.90.17) — Server state management
  • UI: Shadcn UI, MagicUI, React Bits, and Vercel AI SDK elements (generated from registries — see Code Style)

pnpm-workspace.yaml overrides vulnerable @xmldom/xmldom 0.9.x releases to 0.9.12 for GHSA-965w-775f-mr7g. Nextra pulls it in through MathJax and speech-rule-engine@4.1.2, which pins 0.9.8. Keep the override until the upstream dependency chain resolves a patched version without it; regenerate pnpm-lock.yaml and verify the docs build when changing this constraint.

Commands

Command Purpose
pnpm dev Start the development server with Webpack
pnpm build Production build
pnpm check Lint + type check (run before committing)
pnpm lint ESLint only
pnpm lint:fix ESLint with auto-fix
pnpm format Prettier check (pnpm format:write to apply)
pnpm test Run unit tests with Rstest
pnpm test:e2e Run E2E tests with Playwright (Chromium)
pnpm typecheck TypeScript type check (tsc --noEmit)
pnpm start Start production server

Unit tests live under tests/unit/ and mirror the src/ layout (e.g., tests/unit/core/api/stream-mode.test.ts tests src/core/api/stream-mode.ts). Powered by Rstest; import source modules via the @/ path alias.

Webpack is the default development bundler. Use DEER_FLOW_DEV_BUNDLER=turbo with pnpm dev to opt in to Turbopack when diagnosing a local Next.js bundler issue.

On Windows pnpm dev binds 127.0.0.1 by default because Hyper-V/winnat excluded port ranges can reject Next's default 0.0.0.0 bind with EACCES (#2870). Pass pnpm dev -- --hostname 0.0.0.0 to listen on a LAN interface instead.

Rstest runs them as two projects (rstest.config.ts). *.test.ts / *.test.tsx run in a plain node environment — that is nearly the whole suite, and it is the default for anything that is pure logic. *.dom.test.ts / *.dom.test.tsx run in happy-dom, for tests that need a document: hooks driven through renderHook from @testing-library/react, and components. Keep the split — a DOM environment costs roughly 3x the runtime of the node suite, so tests that do not render should not opt into it. A hook whose behavior only exists under real React (effect ordering, cleanup on unmount, re-render on store change) belongs in a .dom.test.* file rather than a node test that mocks react itself.

E2E tests live under tests/e2e/ and use Playwright with Chromium. They mock all backend APIs via page.route() network interception and test real page interactions (navigation, chat input, streaming responses). Config: playwright.config.ts. The real-backend auth contract in tests/e2e-real-backend/auth-disabled-contract.spec.ts and backend/tests/test_auth_me_permissions.py pin the complete route-permission list; update both when adding registered permissions (including projects:read/write/delete).

The dedicated run-history.ts hook replaces the unpaged runs hook. Show counts only after a successful history read, never during initial loading or errors. Scheduled run history uses task/page query keys and the existing live offset API. Fetch 51 rows to display 50 plus a next-page sentinel; never append pages. Only page zero polls or refreshes on focus/reconnect. Task switches reset to page zero, and consumed AbortSignals cancel obsolete reads. Live offsets are not snapshots; explicit mutations or navigation may observe newly inserted runs. Run status unmet identifies a finished occurrence whose scheduled goal was not satisfied; keep it distinct from execution failure. core/scheduled-tasks/goal-outcome.ts maps goal verdicts and host reason codes for run history; show known codes as localized labels; unknown codes, raw run errors and the evaluator's reason stay behind the run row's Details. Check-failure codes are "unchecked", not a miss. contracts/scheduled_goal_notes_contract.json pins the host strings it and run-error.ts match. Scheduled-task views read state through the pure core/scheduled-tasks helpers (status.ts, actions.ts, format.ts, describeTaskSchedule, errors.ts) so list, detail and chat card agree. "Is a run active?" is status === "running" or active_run_status (a recurring task stays enabled while it runs). Default views show no IDs, ISO times, cron strings or enum names; errors localize by detail.code (contracts/scheduled_task_errors_contract.json) with raw text only behind Details. tests/e2e/utils/readable.ts and tests/unit/helpers/readable.ts assert this. The tasks page (app/workspace/scheduled-tasks/page.tsx) only composes components/workspace/scheduled-tasks/*: list with status tabs, detail (Runs / Stops when / goal / Does / notes / History), outcome notice, create/edit/duplicate dialog (PATCH sends only changed fields, null clears) and the renew dialog that a limits_exhausted Resume opens. ?task_id= selects a task; ?thread_id= scopes the list to one chat. In chat, a schedule_task result becomes an assistant:scheduled-task group (core/scheduled-tasks/tool-result.ts, last card per task per turn; not a turn boundary) rendered by ScheduledTaskCard, which polls the task only while on screen. A human message with additional_kwargs.deerflow_scheduled_origin stays a human group with scheduledOrigin: ScheduledRunPrompt renders the origin's user-language parts, never the launched text, and it is not editable. Server-created threads: core/threads/origin.ts reads metadata.deerflow_origin (contracts/thread_origin_contract.json), then channel_source, then a legacy scheduled_task_id; provider names come from threads.origin.providers. core/threads/activity.ts polls /api/thread-activity (mount useThreadActivity once; unmounting resets its cursor; first poll only seeds; invalidate lists only on server-origin threads, truncation or a higher read_version) and useMarkThreadRead posts reads. core/scheduled-tasks/events.ts loads a chat's lifecycle events, not gated on its task list; placeTaskEvents puts each at the end of its after_run_id turn. The UI language is saved as the locale preference once per session and on each switch, only when the Gateway's preferences include locale. Thread rows (sidebar, /workspace/chats) show ThreadOriginIcon and, if unread === true and not the open thread, ThreadUnreadDot with threads.unreadLabel as row label. WorkspaceSidebar mounts useThreadActivity. Chat pages call useMarkOpenThreadRead once metadata loads (marks read on load, on an unread flip, on tab visible, and via its callback from onFinish). Chat pages pass useThreadScheduledTaskEvents data to MessageList (scheduledTaskEvents; the custom-agent page also passes its agent for the run link), which renders ScheduledTaskEventLine through VirtualMessageList.renderAfterGroup at the placeTaskEvents position, inside the group's measured row. Lines are history: never gated on the task list. Channel provider cards (Settings and the sidebar list) render ChannelScheduledUpdates from proactive_notifications, and nothing when the field is absent.

Architecture

Frontend (Next.js) ──▶ LangGraph SDK ──▶ LangGraph Backend (lead_agent)
                                              ├── Sub-Agents
                                              └── Tools & Skills

The frontend is a stateful chat application. Users create threads (conversations), send messages, set thread-scoped /goal completion conditions, and receive streamed AI responses. The backend orchestrates agents that can produce artifacts (files/code), todos, and goal state updates.

Source Layout (src/)

  • app/ — Next.js App Router. Routes include / (landing), /showcase/[thread_id] (allowlisted public read-only demos), /workspace/chats/[thread_id] (authenticated chat), /workspace/agents/[agent_name] and /workspace/agents/new (custom agents), /artifacts/view (chrome-free window that renders Markdown or CSV/TSV artifacts with the panel's own renderer), /blog/…, the (auth)/{login,setup,auth/callback} flow, /[lang]/docs/…, and /api/… route handlers (e.g. /api/memory).
  • components/ — React components:
    • ui/ — Shadcn UI primitives (auto-generated, ESLint-ignored)
    • ai-elements/ — Vercel AI SDK elements (auto-generated, ESLint-ignored)
    • workspace/ — Chat page components (messages, artifacts, settings)
    • landing/ — Landing page sections
    • docs/ — Docs / MDX rendering components
  • core/ — Business logic, the heart of the app. Domains include threads/ (creation, streaming, state), api/ (LangGraph client singleton), agents/ (custom agents), subagents/ (runtime worker catalog and administrator mutations), auth/ (authentication), artifacts/, channels/ (IM connections), integrations/ (managed third-party integration status/install clients such as Lark CLI), i18n/ (en-US, zh-CN), settings/, memory/, skills/, messages/, mcp/, models/, input-polish/ (pre-send draft rewrite API), voice-input/ (browser speech-recognition helpers), suggestions/, tasks/, todos/, tools/, workspace-changes/ (run-scoped changed-file summaries and diff fetching), config/, notification/, blog/, plus rendering helpers (rehype/, streamdown/) and utils/.
  • hooks/ — Shared React hooks
  • lib/ — Utilities (cn() from clsx + tailwind-merge)
  • content/ — MDX content (blog posts, docs) rendered by the app
  • styles/ — Global CSS with Tailwind v4 @import syntax and CSS variables for theming
  • typings/ — Ambient TypeScript declarations
  • Root files: env.js (env validation), mdx-components.ts (MDX component map)

More specific AGENTS.md files under src/ contain the frontend sections split from this file.

Code Style

core/utils/markdown.ts reads web-fetch titles from the first nonblank line. Match zero to three literal spaces before # without trimming indentation; mixed space/tab code blocks must fall back to the URL. Strip optional closing hashes with a backwards scan so long fetched titles cannot cause quadratic regex backtracking. Closing hashes require a preceding space/tab (or an empty title) and only ASCII spaces/tabs afterward, apart from the terminal CR in CRLF input. Non-ASCII trailing whitespace must not turn literal hashes into closing syntax. Keep this local to title extraction rather than changing the shared streamdown fence parser.

Custom Agent display_name is an optional Unicode UI label, edited in AgentSettingsDialog. Use it with a fallback to name for gallery/chat text; keep name for React identity, URLs, requests, and runtime agent_name. The 100-code-point budget uses [...value.trim()].length, matching Pydantic; do not use HTML maxLength, which counts UTF-16 code units instead.

Custom Agent portability uses the versioned deerflow.custom-agent JSON document through core/agents/api.ts. Keep file parsing client-side only for previewing the proposed local name; the Gateway is authoritative for schema, name, model, and conflict validation. Export downloads must never synthesize runtime state from browser caches.

  • Imports: Enforced ordering (builtin → external → internal → parent → sibling), alphabetized, newlines between groups. Use inline type imports: import { type Foo }.
  • Unused variables: Prefix with _.
  • Class names: Use cn() from @/lib/utils for conditional Tailwind classes.
  • Path alias: @/* maps to src/*.
  • Components: ui/ and ai-elements/ are generated from registries (Shadcn, MagicUI, React Bits, Vercel AI SDK) — don't manually edit these.

Scheduled-task list search filters the current authorized query result by title or prompt, composing with status/type filters and thread scope. Selection must derive from the filtered list so hidden tasks cannot remain actionable. Keep literal matching in core/scheduled-tasks/search.ts; clearing search retains other filters.

Single-run schedule edits retain the mounted task's original run_at while its wall time and timezone match. The parent echoes edits through initial; retain a stable snapshot and reset the parent draft during render before remounting with a task key when switching tasks. Use the resolved timezone consistently for the snapshot and displayed wall time. Component and scheduled-task E2E tests cover DST folds and timestamp precision.

Environment

Scheduled-task interval forms preserve the initial every_seconds on mount, timezone changes, and untouched blur. The backend's configurable interval minimum can be lower than the UI's default 60-second floor. Apply that UI floor only after an explicit amount/unit edit so editing metadata or duplicating a task cannot silently change its cadence. Component regressions live in tests/unit/components/workspace/scheduled-task-schedule-input.dom.test.tsx.

Backend API URLs are optional; an nginx proxy is used by default:

NEXT_PUBLIC_BACKEND_BASE_URL=http://localhost:8001
NEXT_PUBLIC_LANGGRAPH_BASE_URL=http://localhost:8001/api

Leave these unset for the standard make dev / Docker flow, where nginx serves the public /api/langgraph/* prefix and rewrites it to Gateway's native /api/* routes.

make build-static creates a standalone read-only demo and copies .next/static and public into the output. In static mode, core/api/static-response.ts resolves Gateway REST reads with the bundled capability catalog and safe installation projections from existing same-origin /mock/api fixtures; writes and unknown API routes fail locally. The homepage client counter calls /github-stars, outside the Gateway proxy. That dynamic route reads the server-only GITHUB_OAUTH_TOKEN at runtime, caches GitHub data for one hour, and returns 204 when the count is unavailable. Start the standalone server from frontend/ with node --env-file=.env .next/standalone/server.js to load the current credentials.

To reach a dev server on anything other than localhost — a LAN address, or a proxied hostname — list the host in DEER_FLOW_DEV_ALLOWED_ORIGINS (comma-separated; a full URL is reduced to its host). It feeds Next's allowedDevOrigins, which gates /_next/*, fonts, and HMR. Without it those requests get a 403 and the page renders server-side but never hydrates, so nothing on it — including the login form — responds. Development only; production builds ignore it.

One-time schedule input uses validZonedLocalToUtcIso to reject wall times that do not round-trip in the selected timezone. Invalid input emits an empty spec and localized inline feedback; both create and edit must block submission. Keep this UI validation separate from the API payload. Preserve the original instant when wall time and timezone match the mounted snapshot; validate changed inputs, and restore the exact original timestamp when those edits are reverted.

Resources

Contributing

When adding features:

  1. Follow the established src/ structure
  2. Add TypeScript types and proper error handling
  3. Write unit tests under tests/unit/ (pnpm test) and E2E tests under tests/e2e/ (pnpm test:e2e)
  4. Run pnpm check before committing
  5. Update this AGENTS.md when architecture, commands, or conventions change

Route asset budgets are enforced with pnpm perf:check. The command measures /login from a normal production build, then builds in static-demo mode for the fixture-backed workspace routes. It starts the production server on temporary local ports, measures the unique JavaScript and CSS files referenced by representative routes, writes the detailed result to .next/performance-results.json, and compares totals with performance-budgets.json. Fix route ownership or split points when a budget fails; do not raise a ceiling without documenting and reviewing the measured regression.

Chat archive is a thread metadata flag (deerflow_archived === true), independent of run status. Sidebar and Chats explicitly request the Gateway's optional archived filter through searchThreadsByArchive; the SDK drops this extension, so use the authenticated REST fetcher. Static demos retain SDK fixture queries. core/threads/archive.ts waits for the write, cancels stale reads, merges only the owned flag into metadata snapshots, then restarts metadata reads and resets list pagination. Keep both default and Custom Agent header restore controls in sync. Pin/archive responses must not merge unrelated metadata flags: out-of-order organization requests can otherwise roll back each other's confirmed state. Run-created optimistic snapshots have no archive flag: refresh archive-filtered lists from the server instead of inserting those snapshots into either view.

Delimited artifact preview

CSV/TSV previews share artifact-table-preview.tsx between the panel and standalone viewer. Papa Parse runs only inside delimited-preview.worker.ts; use-delimited-preview.ts bounds input before transfer, cancels stale work, and enforces a five-second timeout. The parser detects the first record separator outside quoted fields and passes it explicitly to Papa Parse, so embedded newlines in an incomplete quoted field cannot corrupt newline detection. It retains at most 202 logical records and 50 columns, discarding an incomplete final record from truncated input. UI pagination displays at most 200 data rows in pages of 50. Keep the table mounted but inactive when switching to source so header/pagination state survives; changing file identity resets it. Pending write_file content stays in source mode until success.

For a truncated sample whose first separator is LF or CRLF, strip a terminal CR before parsing so a split CRLF separator cannot make a quoted final field invalidate the whole preview, including LF-first files with later CRLF records. The terminal record remains incomplete and is discarded; complete CR-only files and malformed quotes retain their existing behavior.

Custom skill export is admin-only and disabled in static demos. The lazy skill-export-dialog.tsx must abort requests and ignore stale callbacks on close or user/skill changes. core/skills/export.ts owns the revision-bound Blob download; HTTP 409 requires explicit preview refresh. Keep file lists paginated and diagnostics localized. Browser handoff does not prove the file was saved to disk.

Sidebar rows request deletion through ThreadDeleteDialogProvider, hosted in WorkspaceSidebar outside the virtualized flat/project lists. Keep the selected thread snapshot and retry UI alive when a partial deletion removes its row. Focus Cancel on open and after a failed deletion has re-enabled the actions; block dismissal while deletion is pending. Show the error message when available, with a localized fallback, and log the rejection for debugging. The shared delete helper accepts remote 404 (not 403) before retrying local cleanup, and onDeleted runs only after both deletion steps succeed.

Capability Center

/workspace/capabilities owns Plugins and Skills navigation. Plugins composes the MCP manager and a lazily loaded Lark configuration dialog; installation, OAuth, mutation permissions, and cache ownership remain in the existing hooks. Skill display names/summaries are presentation metadata; runtime names and full descriptions remain unchanged. Public, custom, integration, and legacy sources must stay distinct. Community currently offers archive import, not a remote marketplace. Screenshot E2E fixtures are demo data. backend/packages/harness/deerflow/capabilities/builtin.json owns localized catalog manifests. Refresh the generated demo snapshot with pnpm catalog:sync after changing the catalog; unit tests enforce equality with the source. Demo business projections derive provider IDs from the catalog adapter metadata. The sync script uses decoded filesystem paths for formatter configuration lookup. plugin-catalog.ts only resolves localized text and explicit installation metadata; never infer provider identity from server display names. plugin-directory.tsx groups rows and applies search/category/installed filters. core/capabilities consumes catalog and safe status projections; MCP secrets and raw settings remain in the administrator-only editor. plugin-adapters.tsx registers integration-specific settings flows once, independent of catalog size. The business form uses manifest credential fields without asking for an MCP URL; its backend adapter generates bundled DingTalk/WeCom notification or HubSpot CRM connections. These also appear in MCP discovery, so deduplicate projections by installation ID. Keep their labels as configuration, not package installation. Keep installation, enabled state, configured credentials, and verified authorization distinct. Agent mcp_plugins uses stable installation IDs; null means all, [] means none. The settings dialog submits only selections changed from its opening snapshot, preserving concurrent updates on unrelated saves and treating restored selections as unchanged. It is runtime selection, not a replacement authorization policy. See docs/capability-center.md for the complete contract and extension example. PluginIcon is shared by recommendations, configured entries, and the editor; brand assets and their provenance live in public/images/plugins/. Brand icons require explicit catalog metadata; a custom server name never selects a brand. Ambiguous installation IDs remain visible but cannot be selected for an Agent. The icon picker accepts local PNG/JPEG/WebP up to 2 MiB, checks the signature, decodes and contains the image in a 128px PNG, and stages changes until the existing targeted MCP save. presentation.icon is a bounded PNG data URL carried by the API's existing extra metadata support; it must never enter transport parameters. Preserve sibling presentation fields and masked credentials; cancel/reset/unmount must fence stale image-decoding results. Uploaded remote URLs and SVG are never rendered. Existing shared-MCP administrator checks remain authoritative; this adds no personal scope.

This is NOT the Next.js you know

This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in node_modules/next/dist/docs/ (resolved from this file's directory; in monorepos the next package may not be visible from the repo root) before writing any code. Heed deprecation notices.

This block is written and re-added by next dev — verify at node_modules/next/dist/server/lib/generate-agent-files.js. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.

Shared model settings

Settings → Models (?settings=models) offers administrator-only catalog management through /api/managed-models. YAML entries are read-only. core/models/management.ts whitelists editable fields so source metadata and has_api_key never get posted. Draft credentials stay in editor state, never query cache or browser storage; blank keeps the saved key, explicit removal sends an empty key. Saving invalidates both the admin catalog and MODELS_QUERY_KEY. Editor unmount aborts probes and fences late callbacks. Static demos and non-admin users must not query the management API.

Model reasoning capabilities

/api/models projects a per-model reasoning contract (issue #5073) beside the deprecated supports_thinking / supports_reasoning_effort booleans. core/models/reasoning.ts is the only place that interprets it: it falls back to the booleans for older Gateways, clamps the chat mode (getResolvedMode never yields flash for a required-thinking model), lists the effort options the composer and the sidecar render, and maps mode presets and remembered values through the contract's aliases/default (resolveReasoningEffort). Effort values are open strings (ReasoningEffortValue), so provider-specific tokens such as max flow through local settings and account preferences unchanged; the custom agent dialog offers only the intersection with the per-agent low/medium/high schema and hides "off" for required-thinking models. Do not read the booleans in components directly. On a legacy model, resolveReasoningEffort keeps only its advertised generic values; this drops a remembered provider-specific token after a model switch without changing the backend's direct legacy-request behavior.

Full-stack plugin UI

core/extensions/ loads authenticated deployment-installed ES modules from /api/plugins. Inline modules use authenticated fetch plus a released Blob URL. Manifest assets use native credentialed module scripts, preserving relative imports and resource URLs. Both honor the backend base and prefixes; transport and cache semantics are documented in docs/full-stack-plugins.md. Host copy belongs in the typed locale dictionaries. Conversation action factories, shapes and availability callbacks are guarded per plugin; only validated value snapshots reach the toolbar/sidebar render paths. PluginNavigation and the dynamic workspace extension route consume page declarations; Capability Center defaults to the repository examples in core/extensions/catalog.ts, merged by explicit namespace with runtime descriptors. Catalog-only entries are discovery metadata, never module-loader inputs or proof of installation. Backend-only examples may have no plugin descriptor; keep their runtime status unasserted. Details link to package installation instructions. Keep the catalog aligned with examples/deerflow-extension-*. Agent teams uses community.agent-teams; merge its installed descriptor into the localized catalog entry without asserting runtime status for a catalog-only row. Conversation action slots augment normal/custom-agent toolbars and sidebar menus without replacing native export or notification. Plugin views use mount/dispose and abort signals; Shadow DOM is CSS isolation, not a sandbox. Descriptors are user-keyed page snapshots, refreshed manually. Backend calls bind the plugin's namespace, action allowlist and expected viewer identity. See docs/full-stack-plugins.md.

Plugin page openConversation(threadId) resolves authenticated thread metadata with pathOfThread; do not let plugins hardcode default-agent routes. The page's abort signal fences late navigation after unmount/account changes. Synchronous conversation-action callbacks reject Promise returns while consuming rejections.

Composer references

components/workspace/mentions/ owns cursor-local @ detection, the picker, and atomic references. Render labels as DOM text, never HTML; canonical tokens preserve draft positions. Submission expands tokens to @label and sends up to 16 unique skill IDs in additional_kwargs.skill_references; the backend checks each against the user registry and agent allowlist. The web slash picker lists only /goal and /compact; skill selection uses @. Legacy typed slash text continues through normal message submission for backend and channel compatibility. Project files require confirmed additional_kwargs.files. Conversation context is reconciled from tokens against the current capability and limit. Only successful discovery may flatten references; pending/errors preserve IDs and block reference sends, with retry on failure. Polish restores whole labels longest-first in one pass. Confirmed thread creation seeds metadata before migration; references stay locked during attachment. Deleting an object removes its context; undo restores references already attached to the draft. Labels grant no read authority. IME, caret, thread changes and attachment fences apply to editor and picker. The @ and attachment buttons share the picker.