Skip to content

feat(platform)!: chat = ask/retrieve — the Chat·Task·Automation boundary model - #2877

Merged
larryro merged 9 commits into
mainfrom
feat/chat-boundary-model
Jul 30, 2026
Merged

larryro merged 9 commits into
mainfrom
feat/chat-boundary-model

Conversation

@larryro

@larryro larryro commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Implements the Chat·Task·Automation boundary model for the chat surface (per the plan document): chat asks and retrieves; deliverables live on tasks; fixed processes live in automations.

What changed

Chat backend — a bounded three-tool loop (breaking)

  • The built-in assistant (hardcoded, deliverables-go-to-tasks rule) runs a round-based tool loop (max 8 rounds, final round withholds tools) over exactly rag_search / rag_fetch / web_fetch — all read-only, per-dispatch RLS-checked, audited, never-throwing.
  • Wire carries tools + structured tool messages on both dialects; tool-free bodies stay byte-identical (prompt cache). Parts settle before execution (crash-safe); usage sums across rounds.
  • Cancel channel: requestCancelGeneration → loop aborts the model fetch and settles with what streamed. Stop works for direct turns.
  • BREAKING: chat turns (REST included) no longer accept agentSlug; equipped skills no longer reach the direct chat lane. listComposerModels keeps externalAgents for the task lane.

Chat frontend — the 0.3 page restored, chat-only

  • Model+effort picker only; no agent/skill/connector pickers, slash commands, canvas, or sandbox chrome.
  • Restored 0.3 pieces: welcome view with starters, flat thought timeline, source cards (derived only from what the turn actually loaded), thread title in the top bar.
  • Product bugs found driving it end to end: arena model-B lost its provider binding (could resolve to a credential-less provider), arena send gated on a deliberately-skipped read, header ⋯ shared its accessible name with sidebar rows (now Conversation actions, en/de/fr).

Provider schema — private-http endpoints behind the host policy ⚠️ security-relevant, review this commit first

  • providerBaseUrlSchema now admits http:// for private/loopback-shaped hosts only (the relaxation the schema comment reserved for a reviewed change). The schema stays pure; reachability is enforced at request boundaries: checkProviderHostPolicy (metadata hosts always refused; private hosts require TALE_ALLOW_PRIVATE_PROVIDER_HOSTS=1) on the chat direct call and the models-endpoint catalog fetch, which also threads the host into safeFetch's allowlist. isPrivateIp lifted to lib/shared/net/ (single recognizer). TTS/embeddings audited: they fail closed through safeFetch.

Mock provider seam rebuilt (the #2876 casualty)

  • New-format providers/e2e-mock.yml fixtures; the docs seed writes the org copy and connects the env credential through the settings UI. Mock /v1/models serves a normalize-compatible catalog; title-generation calls get their own scenario (scripted replies were becoming thread titles). Capture pipeline de-flaked (toast interception, picker-label races, seed staleness from the refactor(platform)!: retire "integration" and rebuild the credential catalogs #2876-era UI).
  • Note: e2e worker orgs still don't get the provider automatically (the interim scaffolder seeds no providers domain) — a chat e2e rebuild should reuse the seed's two moves.

Docs — en/de/fr rewritten with fresh screenshots

  • Deleted agents-in-chat / attachments / canvas-pane / deep-research / video-links (+redirects, nav). Overview/basics/member-tutorial/shared-chats rewritten; ~15 pages swept for stale chat claims. All five chat screenshots recaptured on the restored UI; de/fr are native mirrors.

Verification

  • Full bun run check green (44/44): format, lint, typecheck, all unit tests (~760 platform incl. 74+ new; docs suite 194).
  • Live-verified with a real model (deepseek): web_fetch round-trips real pages, rag_search degrades honestly per source, the deliverable→task rule fires on a 2000-word-essay ask.
  • All five docs screenshots eyeballed; capture pipeline reruns idempotently against the hermetic stack.

Known follow-ups (documented in the tree)

  • RAG ingest is still offline → rag_search's documents/web legs return honest empty notes until the ingest epic lands.
  • Attachments deferred until extraction returns; chat e2e specs to be rebuilt on the new mock seam; agents-docs area rewrite + video re-records.

larryro added 7 commits July 30, 2026 20:26
A provider definition may now name an http:// baseUrl when the host is
private/loopback-shaped — the self-hosted-model-server case the schema
comment reserved for a reviewed change, and the seam the e2e/docs mock
gateway needs post-#2876 (the retired secretsEnv provider files were the
only mock wiring, and org_providers reads *.yml only).

The schema stays pure (no env reads): it admits the SHAPE, and
reachability is decided at request boundaries — checkProviderHostPolicy
(cloud-metadata hosts always refused; private hosts refused unless the
operator set TALE_ALLOW_PRIVATE_PROVIDER_HOSTS=1) now also guards the
models-endpoint catalog fetch, which additionally threads the private
host into safeFetch's allowlist so its own private-IP gate agrees with
the policy that just passed. The chat direct-call boundary gains the
same check in the chat-tools commit that follows. isPrivateIp moves to
lib/shared/net/ so the schema and the SSRF layers share one recognizer;
safe_fetch re-exports it for its existing consumers. TTS/embedding
provider calls keep failing closed through safeFetch (audited; no
raw-fetch path sees provider URLs).
Chat is the ask/retrieve surface of the Chat·Task·Automation boundary
model: the built-in assistant (hardcoded lib/chat/assistant.ts, adapted
from the 0.3 assistant config, deliverables-go-to-tasks rule included)
now runs a round-based tool loop (MAX_TOOL_ROUNDS=8, final round
withholds tools) over exactly three read-only tools — rag_search,
rag_fetch, web_fetch — and nothing else.

- lib/chat/tools.ts: the fixed tool table (wire schemas + docs);
  convex/chat/assistant_tools.ts: the executor — per-dispatch workspace
  RLS check, audit trail, usage lane; never throws (tool failures return
  honest error results the model can read).
- rag_search fans over knowledge sources with per-source degradation
  notes; rag_fetch reads whole documents/pages in 20k windows
  (convex/knowledge/fetch.ts) and wraps web/video-sourced content in the
  untrusted envelope; web_fetch is https-only, private-IP-refusing,
  size/time-capped, with a dependency-free HTML-to-text extractor
  (jsdom cannot ride the Convex bundle).
- Wire: both dialects carry tools + structured tool messages; tool-free
  bodies stay byte-identical so prompt caches survive. One parts-
  carrying assistant message explodes into dialect alternation
  (wire-parts.ts); readEvent decodes streamed tool deltas for both.
- Turn store settles parts BEFORE execution (crash-safe), resets the
  stream tail before parts land (no double render), sums usage across
  rounds; finalize merges parts instead of overwriting them.
- Cancel: generations.cancelRequested + requestCancelGeneration; the
  loop reads the flag on its next progress write and aborts the fetch.
  The direct-call boundary also runs checkProviderHostPolicy.

BREAKING CHANGE: chat turns no longer accept an agentSlug (REST
included) and equipped skills no longer reach the direct chat lane —
the chat page runs the built-in assistant only; agents do their work on
tasks. listComposerModels keeps serving externalAgents for the task
lane's project-agents roster.
The chat page is the 0.3 experience rebuilt on the new backend, with
every non-chat element removed: no agent/skill/connector pickers, no
slash commands, no canvas pane, no sandbox plumbing — the composer
offers the model and its reasoning effort, and send/stop drives the
direct turn (stop now works for direct turns via
requestCancelGeneration).

Restored 0.3 pieces: the welcome view with four starters; the flat
thought timeline (reasoning + one step row per search/fetch, 0.3's own
row language and humanized titles) replacing ThinkingSection; source
cards under the answer, derived only from tool results the turn
actually loaded; the thread title in the top bar. thread-view-core
merges settled parts with the live tail (stale-live prefix guard).

Also fixes surfaced by driving the restored page end to end:
- the arena model-B fallback sent a bare model id, so the backend
  re-resolved the provider and could land on one the org has no
  credential for (CREDENTIAL_NONE_CONFIGURED); the full option —
  provider slug included — now travels with the pick;
- arena send was gated on the surface's deliberately-skipped thread
  view and stayed dead on pair threads;
- the conversation header's overflow button shared its accessible name
  with every sidebar row ('More actions'); it is now 'Conversation
  actions' (chat.aria.threadActions, en/de/fr).

Locales: starters/thinking/sources keys restored in all three catalogs;
orphaned agent/canvas/slash/skill keys removed; the picker aria label
no longer mentions agents. Skills hooks drop their unused
organizationId params (the chat-side skill surface is gone).
The credentials rewrite (#2876) retired the secretsEnv provider files
both hermetic fixture trees still shipped, leaving every browser
pipeline that needs a chatting org — the docs captures today, a chat
e2e rebuild tomorrow — with an empty model picker. Rebuilt end to end:

- fixtures: retired-format e2e-mock.json/openrouter.json replaced by a
  new-format org-custom provider (providers/e2e-mock.yml, private-http
  baseUrl at the mock gateway, env + api-key auth). The interim org
  scaffolder still does not seed the providers domain, so the docs seed
  gains an ensureMockProvider stage: copy the template into the org's
  config dir (slug via Better Auth; config root pinned to the fixtures
  tree — bun loads .env, whose TALE_CONFIG_DIR points at the DEV
  stack's config) and connect the TALE_PROVIDER_KEY_E2E_MOCK env
  credential through the settings UI.
- mock gateway: /v1/models now serves a normalize-compatible, believable
  catalog (context_length, tool/vision signals; the two Claude entries
  the arena docs shot scripts per-model variants for). Thread-title
  generation gets its own scenario — its user turn IS the chat's first
  message, so the docs scan was answering scripted REPLIES as titles,
  which also broke the seed's re-identify-by-prompt idempotency.
- capture: toast viewport hidden in shot contexts (the dev stack's
  update banner intercepted header clicks); clipboard permissions for
  the shared-view shot; picker-label gates so no shot freezes the
  'No models available' loading placeholder.
- seed staleness repairs across the #2876-era UI: members route,
  connector/curation/installation stages skip tolerantly, env-save
  waits for the header Save-button flash (the toast moved), ensureChats
  waits for the history list instead of instant-polling it (the race
  duplicated every seeded chat).
- shots: chat-share-dialog (a dialog that no longer exists) replaced by
  chat-shared-view — share is one gesture now and the recipient's
  read-only snapshot is the surface worth photographing.
Chat's documentation now teaches what the surface actually is — ask and
retrieve with three visible tools — and draws the Chat·Task·Automation
line explicitly, in all three locales.

- Deleted (en/de/fr + redirects): agents-in-chat, attachments,
  canvas-pane, deep-research, video-links — surfaces the chat page no
  longer has. nav.json's chat group shrinks accordingly.
- Rewritten: chat overview (boundary table, the parts of the screen,
  starters), chat basics (send-to-reply path, the three retrieval
  tools, thought timeline, sources, deliverable handoff), the member
  tutorial (five habits), shared chats (the one-gesture snapshot link,
  the read-only view, stop sharing — the dialog/fork flow is gone).
- Swept for stale chat claims: get-started pages, agents/knowledge,
  project-agents, environment-reference, video-ingestion, voice-mode,
  the video-tutorial chapter pages, and the editor tutorial (including
  its intro contradicting its own step 4 about where agents work).
- Screenshots recaptured on the restored UI via the hermetic capture
  stack: thread-reply, arena-split, shared-view (new), composer (new),
  starters-empty (new); mention-picker/code-reply/share-dialog webps
  retired with their pages/flows. Image manifest + search index
  regenerated.

German and French pages are native mirrors (per write-translations),
not literal translations.
The direct lane's usage blob now carries what the message-info panel
renders: costEstimateCents (one estimateCostCents formula shared with
the org ledger, so the two figures can never drift), cachedInputTokens
and reasoningTokens (decoded from both the OpenAI-style details objects
and Anthropic's cache_read_input_tokens), stepLimitHit when the tool
loop spends its round budget, and the TTFT breakdown anchors — setupMs
(turn start to first model dispatch) and timeToFirstReasoningMs — all
turn-anchored, all inside the v.any() usage blob (no migration).

The governance model-access policy now holds at BOTH chat boundaries:
listComposerModels filters the catalog server-side, and executeTurn
re-checks through the new identity-free checkModelAccessInternal before
resolving the model, so a crafted call or a stale saved selection is
refused with the policy's own wording.

Sharing gains getThreadShareStatus — an owner-only READ of the link
state (token, sharedAt snapshot boundary, shareability), so the manage
dialog opens without publishing anything.

transcribeDictation returns from its post-rewrite 'disabled' stub:
the transcription model resolves through the same connector walk the
composer catalog uses (openai-format, transcription-tagged, direct
credentials only — the wire is the /audio/transcriptions shape), and
listComposerModels reports voice.transcriptionAvailable from the same
conditions so the mic's availability signal cannot disagree.
The message-info dialog carries the 0.3 panel again — relative-time
line, model badge with inline provider, cached share percent, cost,
per-tool-call cards with input/output previews, the voice-usage
section (its query had survived unused), and a TTFT drill-in view
(setup before model / first reasoning / first token, Back returns).

Composer correctness: the CJK IME guard (isComposing + ref mirror +
keyCode 229), per-conversation draft persistence with failed-send
restore, paste/copy whitespace normalization on both paths, the
budget send-gate with its stated reason, classified refusal toasts
(PII / policy / budget / model access), starters fill the composer
instead of firing, the data-processing notice sits under the field
again, and the voice toggle is back beside the mic as a one-click
button with failure toasts.

States an owner can hit: an archived conversation swaps the composer
for the banner + Unarchive and withholds edit/regenerate/fork; a dead
or foreign thread URL shows the explicit not-found screen instead of
a live-looking empty chat; a scoped error boundary keeps the composer
(and the draft) alive through a transcript crash.

The thought timeline settles into a quiet "Thought for Ns" that stays
put (counts live in the info dialog), ticks send-anchored from first
paint, keeps a stable verb, and is mutually exclusive with the
pre-first-byte gap shell — never two indicators on one reply. Step
rows drill into full tool input/output; source cards collapse past
three and open document previews. The queued/streaming status region
is screen-reader-only now.

Chrome: the conversation header menu mirrors the sidebar row menu
one-for-one through shared handlers (pin, move to project, archive,
delete, hold-aware), Share opens the manage dialog (status, copy,
republish-newer-messages, revoke), sidebar rows carry the shared and
legal-hold indicators, and below md a compact header + thread-list
drawer replace the desktop-only panel. Select-to-quote stages a chip
the next send prepends as a blockquote. Dictation falls back to
MediaRecorder + server transcription where Web Speech is missing,
with the transcribing state, retry pill, and a disabled explain-why
mic when no transcription model is configured.

Locales: en, de and fr move together throughout; the 0.3 strings are
ported from the old catalogs, the rewritten composer placeholder
tracks the boundary model's actual reach.
@larryro
larryro force-pushed the feat/chat-boundary-model branch from 35a7830 to 1def56c Compare July 30, 2026 12:29
larryro added 2 commits July 30, 2026 20:47
CI lints with --type-aware, which the local pass skipped: drop a
boolean === true on the non-optional archived flag, and replace the
EventTarget-to-Element assertion in the mobile drawer's click-capture
with an instanceof narrowing.
Stop had no feedback while the provider was between bytes — exactly
when a user reaches for it. The cancel flag was only read on progress
writes, and progress writes only happen on streamed chunks, so during
the first-byte wait, thinking stalls, and tool round-trips the click
sat unanswered until the stream resumed.

The stream loop now races each chunk read against a 750ms cancel poll
(the progress channel doubles as the read; the store throttle answers
from its last verdict between real writes), checks the round-boundary
flush's verdict before starting a round's tools, and polls between
tool calls — a Stop lands within about a second whatever the provider
is doing, without re-issuing or dropping a pending read (the chunk
pull stays in lockstep with the body, as for-await had it). A provider
that ignores the abort can no longer hold the settle hostage.

The button itself acknowledges the click instantly: disabled with a
spinner and a localized Stopping… label until the generation row
clears reactively.
@larryro
larryro merged commit 97d15a7 into main Jul 30, 2026
35 of 36 checks passed
@larryro
larryro deleted the feat/chat-boundary-model branch July 30, 2026 13:18
larryro added a commit that referenced this pull request Aug 4, 2026
A task-agent run that lost the session-slot reserve rotted silently at
queued: the QUOTA_EXCEEDED throw happened before the turn's op row
existed, so the settle's finalize claim lost and returned without
recording anything, and four minutes later the watchdog manufactured an
op row and failed the run with a wrong reason (observed live). The run
now PARKS instead — waitingForCapacityAt on the run row, the card says
it waits for a sandbox slot — and every session-status transition out
of {creating, active} (failed included, previously a wake hole) wakes
the org's oldest parked run through the once-stubbed capacity wake,
with the watchdog retrying parked runs as the lost-edge backstop and
failing them with the real reason past their deadline. Every other
pre-op-row failure now settles with its real error via the automation
lane's burned-claim fallback, and startTaskAgentTurn gained the
idempotency gate that keeps a wake/watchdog double start from minting
two gateway keys and two execs for one turn.

Slots also stop outliving their work: the task lane hibernates the
agent's standing session the moment its run settles (sibling runs keep
it up via the running-op guard), the automation lane does the same when
the RUN goes terminal (finishRun, operator cancel, late turn settles,
orphan reap) — its per-execution session is never reused after — and
both lanes re-admit hibernated sessions through a cap-checked resume,
closing the blind stopped-to-active flip that re-admitted past the cap
and the row-stopped-container-alive turn that no budget counted.

The dead chat-sandbox lanes go with it: chat has been ask/retrieve-only
since #2877, so the per-user external-turn entry points, their recovery
cron, the run_code thread-session lane (including its vision arm), and
the per-user/thread naming, queries, and quota row are removed;
external_turn_shared.ts slims to the harness-turn library the task and
automation lanes actually share, with its drain regressions ported onto
drainHarnessWindow. Sandboxes settings copy drops the personal-sandbox
promise in all three locales.
larryro added a commit that referenced this pull request Aug 5, 2026
The per-thread run_code lane has had no producer since chat became
plain-conversation (#2877); its budget existed only as a key kept for
config compatibility.

sessionBudgetForOwnerType now returns null for the retired lane, so
leftover thread-owned rows count against no live budget (they must not
leak into the project pool, whose cap is 2). The reserve/resume paths
use a require variant that rejects retired lanes with
SESSION_LANE_RETIRED, pinned by a new test.

Dropping maxThreadSessionsPerOrg from the sandbox_quota schema is a
data-safe narrowing per the snapshot ritual — Zod strips the leftover
key from existing org config files at parse time, so no migration is
needed; the refreshed config baseline records the decision. The row-
level readers and cleaners for legacy thread-owned sessions stay.
larryro added a commit that referenced this pull request Aug 5, 2026
The chat boundary model (#2877) removed every chat-side skill surface,
which hollowed both fields out. usage-mode's 'chat' value had no caller
left — a chat-only skill was equippable nowhere and staging refused it
by name — while 'agent' and 'all' behaved identically, so the field is
removed end to end: frontmatter schema (existing keys are ignored and
shed on the next edit), surface gate, wire validators, REST param,
composer option, the settings radio and table column.

private visibility loses its only consumer the same way: a project's
agents never see one member's private bundle, so a private skill was
visible to its owner and usable nowhere — and the create default made
every new skill start in that dead state. New skills and uploads now
land org-wide and saves refuse to mint private (SKILL_PRIVATE_RETIRED);
pre-existing private bundles keep parsing with their owner-only
semantics and can be widened at any time.
larryro added a commit that referenced this pull request Aug 5, 2026
lib/skills/slash.ts and staging.ts have had no importer since the chat
boundary model (#2877) cut the composer's skill surfaces, and the
equipped-skills context seam (renderEquippedSkills, the context block,
TurnRequest.equippedSkills) had no producer — the direct chat lane never
populated it, and its presence contradicted the context contract's own
header, which lists a skills suffix among the blocks deliberately not
assembled.
yannickmonney added a commit that referenced this pull request Aug 6, 2026
chat, settings, automations, connectors, and video-links were authored
against surfaces the AI-backend rewrite (#2857/#2877) and the credential
catalog rebuild (#2876/#2889) deleted or reshaped. Rewritten from the
current routes, i18n catalog, and components, with fresh IDs per the
TEMPLATE rewrite policy. SETUP.md drops the mode-A seeded-automation
claim (fixture packs are in the retired format and seed nothing).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant