@molecule/app-ide-panel-logic

Feature · ide · App (browser) · v1.4.2 · Apache-2.0

Framework-neutral logic of the molecule.dev IDE panels (chat, preview, file explorer, tests), shared by every framework's IDE package

npm install @molecule/app-ide-panel-logic

npm · Source on GitHub

How it works

@molecule/app-ide-panel-logic is a ready-made ide feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { t } from '@molecule/app-i18n'
import { COMMANDS, registerCustomEventCard } from '@molecule/app-ide-panel-logic'

// Read the shared slash-command registry (same array the API prompt reads).
const share = COMMANDS.find((command) => command.id === 'share')

// Register an app-specific chat card once; every framework's IDE package
// sees it because the registry lives in this package.
registerCustomEventCard('build_degraded', () => ({
  text: t('app.buildDegraded', undefined, { defaultValue: 'This build ran on a smaller model.' }),
  tone: 'upgrade',
  action: { label: t('app.upgrade', undefined, { defaultValue: 'Upgrade' }), href: '/pricing' },
}))

Works with: @molecule/app-ai-chat, @molecule/app-ai-models, @molecule/app-code-editor, @molecule/app-i18n, @molecule/app-icons, @molecule/app-ide, @molecule/app-live-preview, @molecule/app-storage

Reference

@molecule/app-ide-panel-logic — the framework-neutral logic of the IDE panels (chat, preview, file explorer, tests): command and settings metadata, the custom-event-card registry, and the pure helper modules behind the @molecule/app-ide-react components. Every framework's IDE package imports (and React's re-exports) this exact set, so the logic exists once.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { t } from '@molecule/app-i18n'
import { COMMANDS, registerCustomEventCard } from '@molecule/app-ide-panel-logic'

// Read the shared slash-command registry (same array the API prompt reads).
const share = COMMANDS.find((command) => command.id === 'share')

// Register an app-specific chat card once; every framework's IDE package
// sees it because the registry lives in this package.
registerCustomEventCard('build_degraded', () => ({
  text: t('app.buildDegraded', undefined, { defaultValue: 'This build ran on a smaller model.' }),
  tone: 'upgrade',
  action: { label: t('app.upgrade', undefined, { defaultValue: 'Upgrade' }), href: '/pricing' },
}))

Type

feature

Installation

npm install @molecule/app-ide-panel-logic @molecule/app-ai-chat @molecule/app-ai-models @molecule/app-code-editor @molecule/app-i18n @molecule/app-icons @molecule/app-ide @molecule/app-live-preview @molecule/app-storage

API

Interfaces

CommandCategory

A command category with its display label.

interface CommandCategory {
  /** Stable category key referenced by `CommandDef.category`. */
  key: CommandCategoryKey
  /** Human-readable category heading (English default; wrapped in `t()` at render). */
  label: string
}

CommandDef

Metadata describing a single slash command.

interface CommandDef {
  /** Command id (the part after the slash, e.g. `'help'`). */
  id: string
  /** Display label including the leading slash (e.g. `'/help'`). */
  label: string
  /**
   * Short description shown in the menu and in `/help` (English default). May
   * contain the `{{agentName}}` interpolation token, filled in by the render
   * sites (command menu, `/help`, `/settings` card) from the host's agent
   * identity (neutral default: "the assistant").
   */
  description: string
  /** Category this command is grouped under. */
  category: CommandCategoryKey
  /**
   * Argument syntax for commands that take options, shown in the `/settings`
   * command reference (English default). `[…]` = optional, `<…>` = required.
   * Omit for commands that take no arguments.
   */
  usage?: string
  /**
   * Alternate short forms (WITHOUT the slash) that also invoke this command —
   * e.g. `['t']` lets `/t <message>` invoke `/teamsay`. Matched by the chat
   * input's command dispatch alongside `id`.
   */
  aliases?: readonly string[]
  /**
   * True for a human-only side-channel command handled by the HOST's server
   * (e.g. a team-chat note the agent never sees): the raw `/command` text is
   * sent to the backend, but NO optimistic user bubble is rendered — the server
   * emits the canonical `message` stream event (see the `ChatStreamEvent`
   * union), which IS the visible message, persisted and fanned out live to
   * every project member.
   */
  sideChannel?: boolean
  /**
   * True for commands a read-only project VIEWER may run — the ones that only
   * read, open a view-only surface, or set a per-user/per-device preference
   * (`/cost`, `/settings`, `/help`, `/mic`, …). Everything else writes shared
   * project state or triggers a Synthase turn (which the server 403s for a
   * viewer), so it is **default-denied** for viewers: omitting this flag means a
   * viewer cannot run the command, which is the safe default for any command
   * added later. Host side-channel commands (`sideChannel`, e.g. `/teamsay`) are
   * team communication, not project mutation — they set this so viewers can talk.
   */
  viewerSafe?: boolean
}

CommandGroup

A category paired with the commands that belong to it.

interface CommandGroup {
  /** The category metadata (key + label). */
  category: CommandCategory
  /** Commands in this category, in registry order. */
  commands: CommandDef[]
}

Activity

A single captured activity. Mirrors the SSE activity.activity payload; the REST list endpoint additionally returns payload and result for the expanded detail view.

interface Activity {
  id: string
  type: ActivityType
  status: ActivityStatus
  recipient?: string
  summary?: string
  /** ISO 8601 timestamp. */
  timestamp: string
  /** Full captured payload — only present on the REST detail response (dev only). */
  payload?: unknown
  /** Provider result / synthetic success record — only present on the REST detail response. */
  result?: unknown
}

AutoCommitState

The countdown's state.

intervalSeconds is the configured cadence (0 = disabled). remaining is the live count: a positive number while counting down, 0 at the instant a commit is due, and null while disabled or paused (after a commit, awaiting the next file change to re-arm).

interface AutoCommitState {
  /** Configured countdown length in seconds; `0` when auto-commit is off. */
  intervalSeconds: number
  /** Seconds left until the next auto-commit; `null` when disabled or paused. */
  remaining: number | null
}

ChatCardStyle

A chat info card's container chrome, as React's style takes it (a unitless borderRadius is pixels).

interface ChatCardStyle {
  /** Inner padding. */
  padding: string
  /** Corner radius in pixels. */
  borderRadius: number
  /** The 1px tinted frame on all sides. */
  border: string
  /** The tinted background. */
  background: string
}

ReportFormState

The report modal's form state.

interface ReportFormState {
  /** Short summary / issue title. */
  title: string
  /** Detailed description of the problem or request. */
  description: string
  /** Optional reproduction steps (free text). */
  steps: string
  /** Whether to attach the recent conversation to the report. */
  includeChat: boolean
}

ClientInfo

Client-side diagnostics attached to a report so triage can see the running environment without asking the user. Every field is optional — only what could be read in the current environment is present (see collectClientInfo).

interface ClientInfo {
  /** The running build version. */
  appVersion?: string
  /** `navigator.userAgent` (browser + OS). */
  userAgent?: string
  /** `navigator.platform`. */
  platform?: string
  /** `navigator.language`. */
  language?: string
  /** Inner viewport size, `${innerWidth}×${innerHeight}`. */
  viewport?: string
  /** Physical screen size, `${screen.width}×${screen.height}`. */
  screen?: string
  /** Active theme — `'light'` or `'dark'`. */
  theme?: string
  /** The current page URL (`window.location.href`). */
  url?: string
}

ReportPayload

The POST /projects/:id/report request body.

interface ReportPayload {
  /** Short summary / issue title. */
  title: string
  /** Detailed description. */
  description: string
  /** Reproduction steps — omitted entirely when blank. */
  steps?: string
  /** Whether the backend should attach the recent conversation. */
  includeChat: boolean
  /** Client diagnostics — omitted entirely when none could be collected. */
  clientInfo?: ClientInfo
}

ReportResult

The POST /projects/:id/report response.

interface ReportResult {
  /** Whether the report was recorded. */
  ok: boolean
  /** Link to the created issue, when one was filed. */
  url?: string
  /** The persisted DB row id. */
  id?: string
}

SharePayload

The POST /projects/:projectId/shares request body.

interface SharePayload {
  /** Role granted to anyone who opens the link. */
  role: ShareRole
}

ShareLinkResult

The POST /projects/:projectId/shares response — the created public link. Mirrors the relevant fields of the @molecule/api-resource-share ShareLink.

interface ShareLinkResult {
  /** The link's unique id (used by the revoke route). */
  id?: string
  /** Opaque slug embedded in the public URL. */
  slug: string
  /** The role this link grants. */
  role: ShareRole
  /**
   * A fully-qualified share URL, when the backend supplies one. Preferred over
   * client-side construction so the canonical origin (e.g. a custom domain)
   * wins over the current page origin.
   */
  url?: string
  /** When the link expires, if ever (ISO 8601); absent/`null` = no expiry. */
  expiresAt?: string | null
  /** When the link was revoked (ISO 8601); absent/`null` = still active. */
  revokedAt?: string | null
  /** When the link was created (ISO 8601). */
  createdAt?: string
}

ChatTimestampSlot

A timeline item that can carry a timestamp, in render order.

interface ChatTimestampSlot {
  /** The timeline item's id. */
  id: string
  /** Epoch milliseconds of the item. */
  timestamp: number
  /**
   * Shown even with timestamps turned off — the user's own message headers (the
   * time already fits in the header row) and critical events (a failure, a
   * blocked connection, a limit that stopped work).
   */
  alwaysShown: boolean
}

ChatCardCodeStyle

Inline monospace code style for command/identifier spans in chat cards.

interface ChatCardCodeStyle {
  /** Monospace font stack. */
  fontFamily: string
  /** Slightly smaller than the card body text. */
  fontSize: string
  /** Tight padding around the code span. */
  padding: string
  /** Corner radius in pixels. */
  borderRadius: number
  /** Subtle gray chip background. */
  background: string
  /** The 1px chip frame. */
  border: string
  /** Commands never wrap inside a chat card line. */
  whiteSpace: string
}

ChatCardLinkStyle

Inline link style for action segments in chat cards.

interface ChatCardLinkStyle {
  /** The theme primary, so a link reads clickable in any theme. */
  color: string
  /** Underline — the affordance that says "clickable". */
  textDecoration: string
  /** Pointer cursor. */
  cursor: string
}

DeviceDimensions

Per-frame iframe sizing. width/height are the PORTRAIT CSS sizes; a fixed-frame (rotatable) device swaps them in landscape. '100%' width with a null height means "fluid" — fill the available preview area (responsive / desktop have no fixed frame to rotate).

interface DeviceDimensions {
  /** Portrait CSS width (e.g. `'768px'`, or `'100%'` for a fluid frame). */
  readonly width: string
  /** Portrait CSS height in px (e.g. `'1024px'`), or `null` to fill the area. */
  readonly height: string | null
  /** Whether the frame has a fixed size that can be rotated portrait ⇄ landscape. */
  readonly rotatable: boolean
}

TestCaseRef

The one test a file is on right now, named the way its runner names it.

interface TestCaseRef {
  /** The runner's test title. */
  title: string
  /** Its enclosing group (`describe`), when it has one. */
  describe?: string
}

TestCaseProgress

What one FILE is doing while it runs: which test is on screen, and how its own tests have gone so far. Discarded the moment the file reports a result — the row's verdict pill takes over from there.

interface TestCaseProgress {
  /** The test running right now, or `null` between tests. */
  current: TestCaseRef | null
  passed: number
  failed: number
  skipped: number
}

TestGroup

One rendered group of rows: a kind within a project directory.

interface TestGroup {
  kind: TestKind
  workspace: TestWorkspace
  /** The directory's name for the heading; `null` for the workspace root. */
  label: string | null
  items: TestItem[]
}

TestResultEntry

What one test file ended as in the last run.

interface TestResultEntry {
  status: TestStatus
  durationMs?: number
  passed: number
  failed: number
  skipped: number
  /** The runner's output, kept for a FAILURE so the row can keep showing it. */
  output?: string
}

TestsRunState

Everything the card knows about the run it is showing.

interface TestsRunState {
  runId: string | null
  running: boolean
  /** The ids the run on show covers, in run order (its private Skip candidates). */
  queued: string[]
  /** Files owed by ANY live covering run; row spinners use this aggregate, Skip never does. */
  runningIds?: string[]
  /** The id whose output is streaming right now, when the host says which. */
  currentId: string | null
  /** The live output lines, newest last, capped at `MAX_OUTPUT_LINES`. */
  output: string[]
  /** Per-id outcome from this run (and from earlier runs, until re-run). */
  results: Record<string, TestResultEntry>
  /**
   * Per-id LIVE per-test progress, for the files that are running right now.
   * An entry exists only between a file's first `case` event and its `result`.
   */
  cases: Record<string, TestCaseProgress>
  /** A skip was asked for and the run has not answered it yet. */
  skipPending: boolean
  /**
   * Skipping is not on offer: the host wired no `skipCurrent`, or it answered
   * that there was nothing left to skip. The control is dropped — never
   * replaced by an error the person cannot act on.
   */
  skipUnavailable: boolean
  /** How the run ended, once it has. */
  outcome: TestRunOutcome | null
  /** A run-level failure message (timeout, transport error) shown in the card. */
  error: string | null
  startedAt: number | null
  durationMs: number | null
  /**
   * The run on show was NOT started by this panel (the agent, the platform, or
   * another tab): it can be watched but not stopped or skipped from here.
   * Absent on the panel's own runs.
   */
  external?: boolean
  /** Who started the run, when the host said. */
  source?: TestRunSource | null
  /** The command a run this panel did not start is running, when the host said. */
  command?: string | null
}

TestFailure

One failing test and the output that explains it.

interface TestFailure {
  item: TestItem
  output?: string | undefined
}

ChatEventCardAction

A single call-to-action on a chat card: a labelled link (href) and/or click handler. The app supplies any route/copy — the shared package never hardcodes one.

interface ChatEventCardAction {
  /** Button label (already localized by the app). */
  label: string
  /** Link target. App-owned — e.g. the host's own pricing/auth route. */
  href?: string
  /** Click handler (alternative to, or alongside, `href`). */
  onClick?: () => void
  /**
   * Render the action's label as inline monospace code — a command/identifier like
   * `/report` or a skill name — so it stands out from prose while staying clickable.
   */
  code?: boolean
  /**
   * Semantic design-system button color. When set, the card renders this action
   * as a real `cm.button` (the ClassMap's standard tinted button, same as every
   * other button in the app) in this color, so a CTA looks identical wherever it
   * appears — e.g. an app can keep "Sign up" `primary` and "Log in" `success`
   * across its auth page, banners, and chat cards. When omitted, the card's
   * legacy accent-outline treatment applies. The app owns the semantics; the
   * shared package just passes the color through to the ClassMap.
   */
  color?: 'primary' | 'secondary' | 'success' | 'warning' | 'error' | 'info'
}

ChatEventCardCode

A non-interactive inline monospace code span in a card body — a command or identifier the prose refers to (/report, a skill name) that should read as code but isn't clickable. For a clickable command, use ChatEventCardAction with code: true.

interface ChatEventCardCode {
  /** The code text, rendered monospaced/tinted. */
  code: string
}

ChatEventCard

A chat system card: a short message with an optional action (or actions). Mirrors the system-card shape ChatPanel renders for upgrade prompts, guest reminders, etc.

interface ChatEventCard {
  /** The card's text. */
  text: string
  /** An optional action button (or buttons): a link (`href`) and/or a click handler. */
  action?: ChatEventCardAction | ChatEventCardAction[]
  /**
   * Composable inline body for a `tone` (tip) card: an ordered list of segments rendered
   * in sequence — plain strings as text, `ChatEventCardAction`s as inline underlined
   * links — so prose and links interleave freely (e.g. text → an inline link → a trailing
   * period). When set, the renderer uses this INSTEAD of `text` + appended `action`s, so a
   * link can sit mid-sentence rather than only at the end. Segments carry their own spacing
   * (no auto-space is inserted between them). Keep `text` populated with a plain-text
   * equivalent for accessibility / non-toned consumers. Only honored when `tone` is set.
   */
  content?: ChatEventCardSegment[]
  /**
   * When true, ChatPanel renders the card as a stand-out tip box rather than muted inline
   * text. Prefer setting `ChatEventCard.tone` (which implies emphasis AND picks the
   * accent colour + icon); `emphasized` without a `tone` falls back to the neutral `info`
   * tone. The app opts in; the shared package never infers emphasis from a card's copy.
   */
  emphasized?: boolean
  /**
   * The card's tip TONE — picks its accent colour + default icon so every notice card
   * shares ONE consistent box (icon + tinted body + a uniform 1px border + actions),
   * differing only by colour/icon per kind:
   * - `info` — blue, info glyph (neutral notice)
   * - `gold` — amber, lightbulb (an honest tip / onboarding note)
   * - `upgrade` — amber, clock (a plan/limit/budget nudge)
   * - `success` — green, check (a completed action, e.g. a saved script)
   * - `signup` — primary, sign-in (an auth nudge)
   *
   * Setting `tone` implies emphasis. Cards that supply composable `ChatEventCard.content`
   * render their inline links in the box; cards that supply `action`(s) render them as a
   * consistent row of accent buttons. Omit `tone` (and `emphasized`) for a plain muted line.
   */
  tone?: 'info' | 'gold' | 'upgrade' | 'success' | 'signup'
  /**
   * Optional icon-name override (a `@molecule/app-icons` glyph) — defaults to the tone's
   * icon. Use only a name that exists in the bonded set (`getIcon` throws otherwise);
   * sets with extra glyphs register them via `CustomIconNames` augmentation.
   */
  icon?: IconName
  /**
   * The limit this card already explains, named by the same `limitType` the backend puts
   * on its limit errors (e.g. `'ai_cost'`). A limit is hit ONCE but can surface twice —
   * as this persisted card (recorded when the turn was interrupted) and again as the live
   * limit banner when the NEXT send is refused — which reads as two cards saying the same
   * thing. When a live error carries the same `limitType`, ChatPanel hides this card for
   * as long as that banner is up, so exactly one surface states the limit; the card
   * returns as soon as the error clears. The banner is never the one suppressed: it is
   * the only feedback the refused send gets, and its message can be more specific than
   * the card's (a platform-capacity refusal shares `limitType` with a personal-budget
   * one). The app owns the identifier; the shared package only matches it.
   */
  coversLimitType?: string
  /**
   * Marks the card as a critical event — something failed, was blocked, or stopped
   * the work (a refused deploy, a blocked outbound connection). A critical card
   * keeps its timestamp even while the viewer has timestamps turned off. The app
   * decides; the shared package never infers criticality from a card's tone or copy.
   */
  critical?: boolean
}

SettingMeta

Canonical, value-free metadata for a single user-controllable setting.

interface SettingMeta {
  /** Stable id (also the i18n key suffix, e.g. `'effort'`). */
  id: SettingKey
  /** Human-readable label (English default; wrapped in `t()` at render). */
  label: string
  /**
   * One-line explanation of what the setting does (English default). May
   * contain the `{{agentName}}` interpolation token, filled in at render from
   * the host's agent identity (neutral default: "the assistant").
   */
  description: string
  /**
   * The slash command that edits this setting client-side. Drives the inline
   * "Edit" affordance and cross-links the setting to its command. Omitted only
   * for read-only settings.
   */
  editCommand?: CommandId
  /**
   * The exact slash-command input to prefill when editing, for settings whose
   * bare `SettingMeta.editCommand` is not specific enough — e.g. the
   * per-mode model rows both run the `model` command but must scope it to a
   * mode (`/model --plan`, `/model --execute`). Omit when running the bare
   * command suffices.
   */
  editInput?: string
}

IdeClientAction

A non-mutating UI action the AI agent asks the IDE to perform — reload or navigate the live preview, open a file in the editor, or drive the preview's interaction bridge (preview_ui). Delivered via the client_action chat-stream event (and, for preview_ui, also via the host's collab socket so a mid-build tab reload can't orphan it).

interface IdeClientAction {
  action: 'reload_preview' | 'navigate_preview' | 'open_file' | 'preview_ui'
  /** navigate_preview: a URL path (e.g. "/dashboard"). open_file: a file path. */
  path?: string
  /** preview_ui: correlates the command with its ui-result round-trip. */
  requestId?: string
  /** preview_ui: the interaction the preview bridge should perform. */
  command?: 'snapshot' | 'click' | 'fill' | 'select' | 'waitFor'
  /** preview_ui: the `data-mol-id` of the target element (preferred). */
  molId?: string
  /** preview_ui: CSS-selector fallback when no molId is available. */
  selector?: string
  /** preview_ui: visible-label match for apps whose elements carry no molId. */
  text?: string
  /** preview_ui: value to set for fill/select. */
  value?: string
}

ChatUserIdentity

Identity of the user whose avatar or name was clicked in the chat timeline, passed to ChatPanelProps.onProfileClick so the host can open that user's profile.

The identity is always the clicked MESSAGE AUTHOR's — a teammate's click carries their persisted author fields, never the viewer's. An author-less message (the local optimistic echo, legacy solo rows) is the signed-in user's own, so it carries ChatPanelProps.currentUserId + the viewer's avatar. The host compares id against the signed-in user to pick the surface: own → editable profile, someone else → view-only. A missing id means "the signed-in user" (author-less rows in a host that passes no currentUserId).

interface ChatUserIdentity {
  /** The clicked user's stable id (a persisted `author.id`), when known. */
  id?: string
  /** The clicked user's display name (a persisted `author.name`), when known. */
  name?: string
  /** The clicked user's avatar value (data-URI / URL), if any. */
  avatar?: string | null
}

TestItem

One test file the host discovered in the project.

interface TestItem {
  /** Stable id, unique across workspaces — used as the row key and to select by. */
  id: string
  /** Path relative to its workspace, e.g. `e2e/home.spec.ts`. */
  file: string
  kind: TestKind
  workspace: TestWorkspace
  /**
   * The group's project name, ready to render: the same path as `workspace`,
   * or `null` for the workspace root, which has no name of its own. Hosts that
   * omit it get the path itself (and the translated "Project" for the root).
   */
  workspaceLabel?: string | null
  /** Human label for the row; the bar falls back to the file path without one. */
  title?: string
}

TestRunners

Which runner drives each kind in one workspace (null = none installed).

interface TestRunners {
  e2e: string | null
  unit: string | null
}

TestList

What ChatPanelProps.listTests resolves with.

interface TestList {
  tests: TestItem[]
  /**
   * Per project directory (keyed like `TestItem.workspace`), the runners
   * the host found. Only directories that hold a listed test appear.
   */
  runners: Record<string, TestRunners>
}

TestSelection

What the bar asks the host to run.

interface TestSelection {
  /** Specific `TestItem.id`s. Takes precedence over `kind`. */
  ids?: string[]
  /** Everything of this kind when no `ids` are given. */
  kind?: TestKind | 'all'
}

TestRunHandle

Handle to a run in flight, so the bar can stop it.

interface TestRunHandle {
  /** Stop the run — the host aborts its stream, which cancels the work. */
  cancel(): void
  /**
   * Skip the command the run is on right now WITHOUT ending the run: the files
   * that command owned come back as `result`s with `status: 'skipped'`, and the
   * run moves to the next command.
   *
   * Optional, because a host may not serve it. Resolving `false` means there
   * was nothing to skip (the run had already moved on) — a benign race the card
   * answers by dropping the control, never by showing an error.
   */
  skipCurrent?(): void | Promise<boolean | void>
}

EditorPanelProps

Properties for the editor panel component.

interface EditorPanelProps {
  className?: string
  /**
   * Render the editor read-only (Monaco `readOnly`) — for read-only project
   * VIEWERS, whose file writes the server rejects anyway. Typing is blocked at
   * the editor, so a viewer never composes an edit that cannot be saved.
   */
  readOnly?: boolean
  /** Called whenever the active file changes (tab switch, file open, file close). */
  onActiveFileChange?: (path: string | null) => void
  /** Called once after the editor is fully mounted and ready to accept files. */
  onEditorReady?: () => void
  /** Called whenever the open tab list changes (file opened or closed). */
  onTabsChange?: (paths: string[]) => void
  /** Maps file path to git status for coloring tab filenames. */
  fileStatuses?: Record<string, string>
  /** Path of the file currently being formatted, for visual indicator. */
  formattingFile?: string | null
  /** Path of the file with an active save debounce countdown. */
  countdownFile?: string | null
  /** Incremented each keystroke to restart the countdown animation. */
  countdownKey?: number
  /** Estimated format duration in ms (rolling average, default 2000). */
  formatEstimate?: number
  /** Called when the user triggers "Fix with AI" from the editor's lightbulb or context menu. */
  onFixWithAI?: (request: FixWithAIRequest) => void
  /** Override double-click on a tab. Return `true` to skip the default pin behavior. */
  onTabDoubleClick?: (path: string) => boolean
}

PreviewStuckReport

Structured report passed to PreviewPanelProps.onPreviewStuck when the preview gives up. Carries the failure class + the route it happened on so the host can compose an actionable, agent-fixable message instead of a bare "preview is stuck".

interface PreviewStuckReport {
  /** The failure class — what left the preview unable to show the running app. */
  reason: PreviewStuckReason
  /** The preview's current location (route) when the failure was detected, if known. */
  url?: string
}

PreviewUiCommand

A live-preview interaction the host asks the panel to perform inside the iframe, so an AI agent can verify a feature end-to-end by DRIVING the app the user is watching (no headless browser). The panel just relays it to the iframe's interaction bridge — generic, so it carries no host/API specifics.

interface PreviewUiCommand {
  /** Correlates this command with its result; the host round-trips on it. */
  id: string
  /** `snapshot` the interactive UI, or act on an element. */
  action: 'snapshot' | 'click' | 'fill' | 'select' | 'waitFor'
  /** `data-mol-id` of the target element (preferred over selector). */
  molId?: string
  /** CSS-selector fallback when no molId is available. */
  selector?: string
  /** Visible-label match — targets apps whose elements carry no `data-mol-id`. */
  text?: string
  /** Value to set for `fill` / `select`. */
  value?: string
  /**
   * `snapshot` only — the moment the host pointed the preview at a new URL (`Date.now()`).
   * Only a document that loaded at or after it may answer, so a navigation snapshot can never
   * come from the OUTGOING page still sitting in the iframe. Set it ONLY when a new document
   * is genuinely loading (the URL actually changed) — otherwise nothing can satisfy it and the
   * command goes unanswered. Omit for a plain read.
   */
  minLoadedAt?: number
}

PreviewUiResult

The preview interaction bridge's reply to a PreviewUiCommand.

interface PreviewUiResult {
  ok: boolean
  /** Interactive-element list + url/title from the preview (present on a snapshot / success). */
  snapshot?: unknown
  found?: boolean
  error?: string
  /**
   * Failed network requests from the last ~10s (method, url, status, bounded response body),
   * captured in-page — so a click that 4xx'd explains itself in the same result.
   */
  recentNetworkErrors?: string[]
  /**
   * Present when the bridge gave up on a settle budget instead of observing the page settle —
   * it names what was still pending (document parsing, an empty root, an unreached route,
   * in-flight requests). The snapshot may be incomplete, so a race stays distinguishable from
   * a genuinely broken page.
   */
  stillSettling?: string
}

TabBarProps

Properties for tab bar.

interface TabBarProps {
  tabs: EditorTab[]
  activeFile: string | null
  onSelect: (path: string) => void
  onClose: (path: string) => void
  onDoubleClick?: (path: string) => void
  /** Maps file path to git status for coloring tab filenames. */
  fileStatuses?: Record<string, string>
  className?: string
}

FileExplorerProps

Properties for file explorer.

interface FileExplorerProps {
  /**
   * Read-only mode (a project viewer): the context menu omits every mutating
   * entry. Pair with omitting the mutation handlers (onRename/onDelete/…) so
   * keyboard shortcuts and drag-moves no-op too.
   */
  readOnly?: boolean
  files: FileNode[]
  onFileSelect: (path: string) => void
  onFileDoubleClick?: (path: string) => void
  onDirExpand?: (path: string) => void
  /** Called when the user chooses "Rename" from the context menu. */
  onRename?: (path: string) => void
  /** Called when the user chooses "Delete" from the context menu. */
  onDelete?: (path: string) => void
  /** Called when the user deletes multiple selected files/folders via context menu or keyboard. */
  onDeleteMultiple?: (paths: string[]) => void
  /** Called when the user moves files via drag-and-drop or cut+paste. */
  onMoveFiles?: (moves: Array<{ oldPath: string; newPath: string }>) => void
  /** Called when the user chooses "New File" from the context menu. */
  onNewFile?: (dirPath: string) => void
  /** Called when the user chooses "New Folder" from the context menu. */
  onNewFolder?: (dirPath: string) => void
  /** Called when the user chooses "Collapse All" from the context menu. */
  onCollapseAll?: () => void
  className?: string
  /** Storage key for persisting expand/collapse state across reloads (through `@molecule/app-storage`). */
  persistKey?: string
  /** Path of the currently active file — highlighted in the tree. */
  activeFile?: string | null
  /** Maps file path to git status — used to color directory names by highest-priority child status. */
  fileStatuses?: Record<string, string>
}

FileNode

File Node interface.

interface FileNode {
  name: string
  path: string
  type: 'file' | 'directory'
  children?: FileNode[]
  isDimmed?: boolean
  gitStatus?: 'modified' | 'added' | 'deleted' | 'untracked'
  /** If this entry is a symlink, the target it points to. */
  symlinkTarget?: string
}

ResizeHandleProps

Properties for resize handle.

interface ResizeHandleProps {
  onResize: (delta: number) => void
  direction?: 'horizontal' | 'vertical'
  className?: string
}

DeviceFrameSelectorProps

Properties for device frame selector.

interface DeviceFrameSelectorProps {
  current: DeviceFrame
  onChange: (device: DeviceFrame) => void
  className?: string
}

ToolCallCardProps

Properties for tool call card.

interface ToolCallCardProps {
  id: string
  name: string
  input?: unknown
  output?: unknown
  status: 'pending' | 'running' | 'done' | 'error'
  /** Snapshot of original/modified file content captured at tool-call time. */
  fileDiff?: { original: string; modified: string }
  /** Externally controlled undo state — when true, the card displays as undone. */
  isUndone?: boolean
  /** Called when the undo/redo button is toggled on this tool call. */
  onUndoToggle?: (id: string, undone: boolean) => void
  /** Called when a filename in the card is clicked — should open the file as a preview tab. */
  onFileOpen?: (path: string) => void
  /** Called when a filename in the card is double-clicked — should pin the tab. */
  onFileDoubleClick?: (path: string) => void
  /** Called when a file-changing card is clicked — should open the file diff in the editor. */
  onFileDiff?: (path: string, diff?: { original: string; modified: string }) => void
  /** Called to undo/redo a file change — writes the given content to the file path. */
  onFileRevert?: (path: string, content: string) => Promise<void>
  /** Called when the user responds to an `ask_user` tool call (clicks an option or submits free text). */
  onAskUserResponse?: (response: string) => void
  /**
   * Skip this tool call while it is RUNNING, without ending the turn: the call
   * comes back as skipped, the model is told it did not run, and the turn
   * carries on. Omitted by a host that does not serve it — then no control is
   * rendered at all. Resolving `false` means nothing was in flight (the call
   * had already finished), which returns the button to its resting state rather
   * than reporting an error.
   */
  onSkip?: (id: string) => void | Promise<boolean | void>
  /**
   * Why skipping is unavailable to THIS viewer, already translated by the host
   * — `null` when it is available. The control stays visible and disabled with
   * the reason on it, rather than vanishing without explanation.
   */
  skipDisabledReason?: string | null
  className?: string
}

ChatMessageItemProps

Properties for the chat message item component.

interface ChatMessageItemProps {
  message: ChatMessage
  className?: string
}

KeyboardShortcut

A keyboard shortcut definition.

interface KeyboardShortcut {
  /** Key combo string, e.g. `"mod+p"`, `"mod+shift+f"`. `mod` = Cmd (Mac) / Ctrl (others). */
  keys: string
  /** Handler invoked when the shortcut fires. */
  handler: () => void
  /** If true, fires even when an `<input>` / `<textarea>` is focused. */
  allowInInput?: boolean
  /** If true, fires even when the Monaco editor is focused. */
  allowInEditor?: boolean
  /** Human-readable label for display in the command palette. */
  label?: string
}

SearchPanelProps

Properties for the search-in-files panel.

interface SearchPanelProps {
  /** Project ID used for API calls. */
  projectId: string
  /** Called when the user clicks a search result. */
  onResultClick?: (path: string, line: number) => void
  className?: string
  /**
   * The project's excluded directory names (VS Code `search.exclude`
   * semantics). Displayed and editable in the panel; the backend applies the
   * SAME set server-side to every search surface (panel + AI tools), so this
   * prop is display/edit state — searches don't send it per query. When
   * omitted, the panel shows `DEFAULT_SEARCH_EXCLUDED_DIRS`.
   */
  excludedDirs?: string[]
  /** Persist an edited excluded-dir set (the host owns storage). */
  onExcludedDirsChange?: (dirs: string[]) => void
  /**
   * Read-only mode (a project viewer): search stays fully usable, but the
   * Replace toggle/inputs/buttons are hidden (bulk writes are editor work).
   * Pair with omitting onExcludedDirsChange so exclude edits never persist.
   */
  readOnly?: boolean
}

SearchResult

A single file's search results.

interface SearchResult {
  /** Relative file path. */
  file: string
  /** Matching lines within the file. */
  matches: Array<{ line: number; content: string }>
}

SearchResponse

Response from the search API endpoint.

interface SearchResponse {
  /** The search pattern used. */
  pattern: string
  /** Grouped results by file. */
  results: SearchResult[]
  /** Total number of matches across all files. */
  totalCount: number
  /** Whether results were truncated. */
  truncated: boolean
}

QuickOpenProps

Properties for the quick-open file finder.

interface QuickOpenProps {
  /** Project ID used for API calls. */
  projectId: string
  /** Called when the user selects a file. */
  onFileOpen: (path: string) => void
  /** Called when the picker is dismissed. */
  onDismiss: () => void
}

Command

A command available in the command palette.

interface Command {
  /** Unique identifier. */
  id: string
  /** Display label. */
  label: string
  /** Keyboard shortcut hint (e.g. "Cmd+P"). */
  shortcut?: string
  /** Handler invoked when the command is executed. */
  execute: () => void
  /** Category prefix (e.g. "View", "File"). */
  category?: string
}

CommandPaletteProps

Properties for the command palette.

interface CommandPaletteProps {
  /** Available commands. */
  commands: Command[]
  /** Called when the palette is dismissed. */
  onDismiss: () => void
}

ShortcutEntry

A shortcut entry for display in the keyboard shortcuts panel.

interface ShortcutEntry {
  /** Human-readable label describing the action. */
  label: string
  /** Display string for the key combo (e.g. "⌘P", "⌘⇧F"). */
  keys: string
  /** Optional grouping category. */
  category?: string
  /** Handler invoked when the row is clicked. */
  execute?: () => void
}

KeyboardShortcutsPanelProps

Properties for the keyboard shortcuts reference panel.

interface KeyboardShortcutsPanelProps {
  /** List of shortcuts to display. */
  shortcuts: ShortcutEntry[]
  /** Called when the panel is dismissed. */
  onDismiss: () => void
}

Types

CommandCategoryKey

Category keys used to group commands in the menu and in /help.

type CommandCategoryKey = 'context' | 'code' | 'collaborate' | 'model' | 'settings' | 'support'

WrittenCommandId

The literal id of every command in COMMANDS — the union the command label helpers switch over. Unlike CommandId (every CommandDef id, including host-added commands), this is closed over the shared registry: adding a command to COMMANDS extends it, so the label switches below fail to compile until the new command has its label — a command can no longer ship with no translation site.

type WrittenCommandId = (typeof COMMANDS)[number]['id']

CommandId

Union of all command ids (loosely string, since CommandDef.id is a string).

type CommandId = CommandDef['id']

ActivityType

Channel categories a captured activity can belong to.

type ActivityType = 'email' | 'sms' | 'push' | 'webhook' | 'channel'

ActivityStatus

Lifecycle status of a captured activity.

type ActivityStatus = 'captured' | 'sent' | 'delivered' | 'failed'

AutoCommitAction

Actions the countdown reducer accepts.

  • set — apply a /autocommit <seconds> command (seconds <= 0 disables); arms AND starts a fresh countdown (an explicit, just-now user choice).
  • hydrate — restore a cadence persisted on the project (e.g. on reload), enabled but PAUSED (seconds <= 0 disables). Unlike set, it does NOT start counting down — the countdown only re-arms on the next file change — so reopening a project never auto-commits a tree the user hasn't touched.
  • reset — a file changed; restart the full countdown (no-op when disabled).
  • tick — one second elapsed; decrement toward zero (no-op when paused).
  • fired — a commit was just dispatched; pause until the next file change.
type AutoCommitAction =
  | { type: 'set'; seconds: number }
  | { type: 'hydrate'; seconds: number }
  | { type: 'reset' }
  | { type: 'tick' }
  | { type: 'fired' }

ShareRole

A role granted by a share link.

type ShareRole = (typeof SHARE_ROLES)[number]

ShareCommand

The parsed result of a /share command:

  • create — POST a link at a valid role (/share, defaulting to viewer, or /share <role> with a recognized role).
  • invalid — an unrecognized role argument was given (the caller shows usage).
type ShareCommand = { kind: 'create'; role: ShareRole } | { kind: 'invalid'; arg: string }

TimestampsCommand

Parsed /timestamps invocation: toggle, explicit on/off, or an unrecognized argument.

type TimestampsCommand = { action: 'toggle' | 'on' | 'off' } | { action: 'invalid' }

DeviceOrientation

Preview-only iframe orientation. Portrait is the natural orientation of a fixed-frame device; landscape swaps its width/height. This is a visual preview concern that lives in PreviewPanel's local state — it is NOT part of the live-preview core state.

type DeviceOrientation = 'portrait' | 'landscape'

ChatEventCardSegment

One inline segment of a card's composable body: literal text, an inline monospace ChatEventCardCode span, or a labelled link/action (ChatEventCardAction). See ChatEventCard.content.

type ChatEventCardSegment = string | ChatEventCardCode | ChatEventCardAction

ChatEventCardFactory

Turns a custom event's data payload into a chat card, or returns null to render nothing for that event.

type ChatEventCardFactory = (data: Record<string, unknown> | undefined) => ChatEventCard | null

SettingKey

Stable ids for each user-controllable setting (also the i18n key suffix).

type SettingKey =
  | 'model'
  | 'planModel'
  | 'executeModel'
  | 'commitModel'
  | 'compactModel'
  | 'mode'
  | 'effort'
  | 'maxLoops'
  | 'autoFix'
  | 'autoCommit'
  | 'hooks'
  | 'autoApproveCommands'
  | 'sounds'
  | 'timestamps'

TestWorkspace

Which project directory a test file belongs to: the directory that OWNS the file (the nearest ancestor holding the runner's config or a package.json), as a path relative to the workspace root — app, api, my-app/app, packages/web — or . for the workspace root itself. Nothing guarantees app/ or api/ at the root: the executor names its project directory, so the value is a path, not an enum.

type TestWorkspace = 'app' | 'api' | '.' | (string & {})

TestKind

What a test file is: an end-to-end spec driven against the LIVE PREVIEW (the @molecule/app-e2e-preview bond every scaffolded app carries), or a plain unit test run by the project's own runner.

type TestKind = 'e2e' | 'unit'

TestStatus

How one test file ended.

type TestStatus = 'passed' | 'failed' | 'skipped'

TestCaseStatus

How one TEST inside a file is doing: the three verdicts a file can end with, plus running — the state a file never reports, because a file is only ever seen finished.

type TestCaseStatus = TestStatus | 'running'

TestRunOutcome

How a whole run ended. skipped-by-user is a run that otherwise finished but had at least one command skipped from the card — deliberately its OWN outcome rather than completed plus a count, so nothing can read a run with skipped work in it as a clean pass. A real failure still wins: error, timeout and cancelled take precedence over it.

type TestRunOutcome = 'completed' | 'cancelled' | 'timeout' | 'error' | 'skipped-by-user'

TestRunEvent

One event from a run in progress. The host streams these to the bar (over SSE in molecule.dev) in the order the run produces them: one start, then interleaved output/case/result, then exactly one done.

type TestRunEvent = (
  | {
      type: 'start'
      runId: string
      ids: string[]
      startedAt?: string
      /** Who started the run — what the test view says about a run it did not start. */
      source?: TestRunSource
      /**
       * The command a run the test view did not start is running (masked by the
       * host). An agent's own command names no test ids up front, so this is
       * what the view can show while its results arrive.
       */
      command?: string
    }
  | { type: 'output'; id?: string; stream?: 'stdout' | 'stderr'; chunk: string }
  /**
   * One TEST within a file — the runner's own title and group, so the person
   * watching a five-minute spec run sees WHICH test is on screen instead of a
   * spinner. `id` is the same file id `result` uses.
   */
  | {
      type: 'case'
      id: string
      title: string
      describe?: string
      status: TestCaseStatus
      durationMs?: number
    }
  | {
      type: 'result'
      id: string
      status: TestStatus
      durationMs?: number
      passed?: number
      failed?: number
      skipped?: number
      /** The runner's output for a FAILURE, which the bar keeps visible. */
      output?: string
    }
  | {
      type: 'done'
      runId?: string
      outcome: TestRunOutcome
      passed?: number
      failed?: number
      skipped?: number
      durationMs?: number
      error?: string
    }
) & {
  /** Server order on the direct stream too; optional only for older/custom hosts. */
  eventId?: string
}

TestRunSource

Who started a test run: the person (the Run buttons, in this tab or another), the agent (its test tool or its own shell commands), or the platform (its checks of a deploy).

type TestRunSource = 'person' | 'agent' | 'platform'

TestRunFeedEvent

One event of the project's test-run feed: any TestRunEvent, stamped with the run it belongs to, since the feed interleaves every run in the project.

type TestRunFeedEvent = TestRunEvent & { runId: string }

PreviewStuckReason

Why the preview could not show the running app — the failure CLASS the host hands to its AI agent so a fix can be targeted (and so the agent isn't told "it's broken" with no hint of how). Distinct from a JS error (onPreviewError): these are states the iframe itself can't report once it's in them.

type PreviewStuckReason =
  // Heartbeats stopped after a render — the app's main thread is locked (an infinite
  // loop / runaway render). The iframe can post nothing else once frozen, so only the
  // host's heartbeat-silence watchdog can detect it.
  | 'frozen'
  // Repeated reload/remount cycles never produced a confirmed render — the document
  // loads but the app never mounts (e.g. a route that throws on every attempt).
  | 'load-failed'
  // The absolute readiness ceiling elapsed with no confirmed render and no active
  // build — a catch-all backstop so the preview can never spin forever.
  | 'load-timeout'

PreviewRenderState

The preview's live render verdict, derived from the iframe bridges — the one preview fact the server can't observe itself (it has no browser). The host forwards it to the server so the post-loop verification won't pass a build while the app isn't actually rendering ("compiles + serves" ≠ "renders").

  • rendered — the app drew content (molecule:ready).
  • blank — loaded but showed nothing (gave up / #root empty after settling).
  • frozen — rendered then locked up (heartbeats stopped).
  • loading — still loading / not yet determined.
type PreviewRenderState = 'rendered' | 'blank' | 'frozen' | 'loading'

Classes

TestRunProjection

Incremental card state. A server id is applied once, in order; completed runs are compacted while per-file verdicts survive. No raw event history is retained or replayed into a fold.

class TestRunProjection {
  private readonly runs = new Map<string, ProjectedRun>()
  private readonly results: Record<string, TestResultEntry> = {}
  private readonly pending = new Map<string, string>()
  private lastEventId: string | null = null
  private order = 0

  /** Apply one event and return the visible state. Missing ids support older custom hosts only. */
  apply(event: TestRunFeedEvent, activeOwnRunId: string | null = null): TestsRunState {
    if (event.eventId) {
      if (this.lastEventId && compareEventIds(event.eventId, this.lastEventId) <= 0)
        return this.show(activeOwnRunId)
      this.lastEventId = event.eventId
    }
    const order = ++this.order
    const previous = this.runs.get(event.runId) ?? {
      state: { ...EMPTY_RUN_STATE, runId: event.runId, running: event.type !== 'done' },
      covered: new Set<string>(),
      startOrder: order,
      lastOrder: order,
    }
    if (!previous.state.running && event.type === 'done') return this.show(activeOwnRunId)

    const id =
      event.type === 'case' || event.type === 'result' || event.type === 'output'
        ? event.id
        : undefined
    const covered =
      event.type === 'start' ? event.ids : id != null && !previous.covered.has(id) ? [id] : []
    for (const file of covered) {
      previous.covered.add(file)
      delete this.results[file]
      this.pending.set(file, event.runId)
    }

    let next = applyTestRunEvent(previous.state, event)
    if (event.type === 'start' && event.startedAt) {
      const startedAt = Date.parse(event.startedAt)
      if (Number.isFinite(startedAt)) next = { ...next, startedAt }
    }
    if (event.type === 'result') {
      const verdict = next.results[event.id]
      if (verdict) this.results[event.id] = verdict
      // The latest verdict is what counts, even when an older run produced it after a newer start.
      this.pending.delete(event.id)
    }
    if (event.type === 'done') {
      for (const [file, runId] of this.pending) {
        if (runId === event.runId) this.pending.delete(file)
      }
    }
    this.runs.set(event.runId, { ...previous, state: next, lastOrder: order })
    this.compact()
    return this.show(activeOwnRunId)
  }

  /** Keep every live run (including the active own run) and only the latest completed run. */
  private compact(): void {
    const completed = [...this.runs.values()]
      .filter((run) => !run.state.running)
      .sort((a, b) => b.lastOrder - a.lastOrder)
    for (const run of completed.slice(1)) {
      if (run.state.runId) this.runs.delete(run.state.runId)
    }
  }

  /** Render current per-file state, with progress and controls selected independently. */
  show(activeOwnRunId: string | null = null): TestsRunState {
    const activeOwn = activeOwnRunId ? this.runs.get(activeOwnRunId) : undefined
    const running = [...this.runs.values()]
      .filter((run) => run.state.running)
      .sort((a, b) => a.startOrder - b.startOrder || a.lastOrder - b.lastOrder)
    const latest = [...this.runs.values()].sort((a, b) => a.lastOrder - b.lastOrder).at(-1)
    const shown = activeOwn?.state.running
      ? activeOwn
      : (running.at(-1) ?? latest ?? { state: EMPTY_RUN_STATE })
    const runningIds = new Set(
      [...this.pending]
        .filter(([, runId]) => this.runs.get(runId)?.state.running === true)
        .map(([id]) => id),
    )
    const own = shown.state.runId != null && shown.state.runId === activeOwnRunId
    const currentId =
      shown.state.currentId && runningIds.has(shown.state.currentId) ? shown.state.currentId : null
    const cases = Object.fromEntries(
      Object.entries(shown.state.cases).filter(([id]) => runningIds.has(id)),
    )
    return {
      ...shown.state,
      currentId,
      cases,
      runningIds: [...runningIds],
      results: { ...this.results },
      external: shown.state.runId == null ? undefined : !own,
      skipUnavailable: own ? shown.state.skipUnavailable : true,
    }
  }
}

Functions

groupCommandsByCategory(commands, categories)

Groups commands under their categories, preserving category and command order and dropping empty categories. Used by the /settings command reference (and any other view that lists commands by section) so the grouping stays in sync with the registry automatically.

function groupCommandsByCategory(
  commands?: readonly CommandDef[],
  categories?: readonly CommandCategory[],
): CommandGroup[]
  • commands — Command registry to group (defaults to COMMANDS).
  • categories — Ordered categories (defaults to COMMAND_CATEGORIES).

Returns: One CommandGroup per non-empty category, in category order.

matchesSideChannelCommand(defs, text)

True when text invokes a side-channel command (CommandDef.sideChannel) from defs, matched against the leading /token by command id or alias (case-insensitive). Used by the chat input's dispatch AND the auto-send (initialMessage) path so a side-channel send never renders an optimistic "/command …" echo — the server's emitted message stream event is the one visible message.

function matchesSideChannelCommand(defs: readonly CommandDef[] | undefined, text: string): boolean
  • defs — The command registry to consult (e.g. shared ∪ host commands).
  • text — The raw outgoing message text.

Returns: Whether the text invokes a side-channel command.

isRegistryCommandId(id)

Whether id is one of the shared registry's commands (COMMANDS).

Host-provided commands (e.g. molecule.dev's /deploy, /teamsay) are NOT registry commands: they carry their own English description and have no key in the shared locale bond, so callers render CommandDef.description directly for them and route registry commands through commandDescription.

function isRegistryCommandId(id: string): id is WrittenCommandId
  • id — The command id to test.

Returns: True when the id belongs to the shared registry.

commandDescription(t, id, values)

The localized one-line description of a registry command (the ide.chat.cmd.<id>.desc keys), through the CALLER's translate function so a framework port and a live locale switch both get their own text. One literal t() call per registry id, chosen by a switch exhaustive over WrittenCommandId: adding a command to COMMANDS without adding its case here is a compile error, so a command can never ship untranslated. Each defaultValue is the same English the command's description field carries (the text the API system prompt renders), so the English output is identical either way.

function commandDescription(
  t: TranslateFunction,
  id: WrittenCommandId,
  values?: InterpolationValues,
): string
  • t — The caller's translate function (React passes useTranslation()'s t).
  • id — The command id; MUST be a registry id — narrow a possibly host-added id with isRegistryCommandId first.
  • values — Interpolation values; the descriptions interpolate {{agentName}} (and the caller's agent identity fills it in).

Returns: The localized description.

commandCategoryLabel(t, key)

The localized heading of a command category (the ide.chat.help.category.<key> keys), through the CALLER's translate function. One literal t() call per CommandCategoryKey, exhaustive: a new category key fails to compile until it has a heading. Each defaultValue equals the category's label field, so the English output is unchanged.

function commandCategoryLabel(t: TranslateFunction, key: CommandCategoryKey): string
  • t — The caller's translate function.
  • key — The category key.

Returns: The localized category heading.

activityIconName(type)

Returns the bonded-icon-set glyph NAME for an activity type — pass it to <Icon name={…} /> to render the themed SVG. Unknown/future types (which activityFromEvent normalizes to webhook) reuse the link glyph rather than risk a getIcon throw.

function activityIconName(type: ActivityType): IconName
  • type — The activity channel type.

Returns: The icon-set glyph name for the type.

activityTypeLabel(type)

Human-readable, translated label for a channel type (used as filter-tab labels).

function activityTypeLabel(type: ActivityType): string
  • type — The activity channel type.

Returns: The translated channel label.

activityStatusLabel(status)

Human-readable, translated label for a status (shown in the status pill).

function activityStatusLabel(status: ActivityStatus): string
  • status — The activity status.

Returns: The translated status label.

activityStatusColors(status)

Resolves the status-pill colors for a given status. Uses RGBA literals (not ClassMap classes) because these semantic status hues are not part of the surface/text token set — the same approach VerificationBadge takes for its pass/fail coloring.

function activityStatusColors(status: ActivityStatus): { fg: string; bg: string }
  • status — The activity status.

Returns: An object with fg (text) and bg (background) CSS color strings.

activitySummaryLine(activity)

Builds the one-line summary shown on the inline card: the activity's own summary, with the recipient appended after an arrow when present (e.g. Welcome email → user@example.com). Falls back to a translated, type-specific default when no summary was captured.

function activitySummaryLine(activity: Pick<Activity, 'type' | 'recipient' | 'summary'>): string
  • activity — The activity to summarize.

Returns: The single-line summary string.

activityFromEvent(raw)

Maps a raw SSE activity event payload into a normalized Activity. Tolerates missing optional fields and supplies an id/timestamp if absent.

function activityFromEvent(raw: {
  id?: string
  type?: string
  status?: string
  recipient?: string
  summary?: string
  timestamp?: string
}): Activity
  • raw — The activity field from the SSE event.
  • raw.id — Activity id; generated if absent.
  • raw.type — Channel type; defaults to webhook if absent.
  • raw.status — Lifecycle status; defaults to captured if absent.
  • raw.recipient — Optional recipient.
  • raw.summary — Optional short summary.
  • raw.timestamp — ISO timestamp; defaults to now if absent.

Returns: A normalized Activity object.

filterActivitiesByType(activities, type)

Filters a list of activities by channel type. null (the "All" tab) returns every activity unchanged.

function filterActivitiesByType(activities: Activity[], type: ActivityType | null): Activity[]
  • activities — The activities to filter.
  • type — The channel type to keep, or null for all.

Returns: The filtered list (a new array unless type is null).

isAutoCommitCountdownVisible(state)

Whether the countdown is in its visible window — armed and within the final AUTO_COMMIT_COUNTDOWN_VISIBLE_SECONDS seconds — i.e. the commit button should render the live "Auto-commit in Ns" label instead of "Commit".

function isAutoCommitCountdownVisible(state: AutoCommitState): boolean
  • state — The countdown state.

Returns: true when armed with at most the visible-window seconds left.

resolveAutoCommitSeconds(saved)

Resolves the persisted project.settings.autoCommitSeconds value to the effective cadence. A finite number is an explicit user choice: positive values floor to whole seconds, non-positive values mean "the user turned auto-commit off" (0). Anything else — missing, never configured, or invalid — falls back to DEFAULT_AUTO_COMMIT_SECONDS, because auto-commit is on by default.

function resolveAutoCommitSeconds(saved: unknown): number
  • saved — The raw persisted setting value.

Returns: The effective cadence in whole seconds (0 = off).

autoCommitReducer(state, action)

Pure reducer for the auto-commit countdown. Deterministic and side-effect free: the component performs the actual commit when isAutoCommitDue becomes true, then dispatches fired.

function autoCommitReducer(state: AutoCommitState, action: AutoCommitAction): AutoCommitState
  • state — The current countdown state.
  • action — The action to apply.

Returns: The next countdown state.

isAutoCommitEnabled(state)

Whether auto-commit is enabled (a positive cadence is configured), regardless of whether it is currently counting down or paused.

function isAutoCommitEnabled(state: AutoCommitState): boolean
  • state — The countdown state.

Returns: true when intervalSeconds > 0.

isAutoCommitArmed(state)

Whether the countdown is actively armed (counting down), i.e. a 1s tick interval should be running. False when disabled or paused after a commit.

function isAutoCommitArmed(state: AutoCommitState): boolean
  • state — The countdown state.

Returns: true when remaining is a number.

isAutoCommitDue(state)

Whether a commit is due this instant (the countdown has reached zero). The component reacts to this by running /commit and dispatching fired.

function isAutoCommitDue(state: AutoCommitState): boolean
  • state — The countdown state.

Returns: true when remaining === 0.

parseAutoCommitCommand(input)

Parses an /autocommit [seconds] command.

Returns { seconds: null } when /autocommit is typed with no argument (the caller shows usage/current state), { seconds: n } for a non-negative integer argument (0 cancels), or null when the input is not the command.

function parseAutoCommitCommand(input: string): { seconds: number | null } | null
  • input — The raw chat input.

Returns: The parsed command, or null when it is not /autocommit.

formatAutoCommitBadge(state)

Formats the countdown's remaining seconds for the compact badge (e.g. "12s"). Returns '' when there is nothing to show (disabled or paused).

function formatAutoCommitBadge(state: AutoCommitState): string
  • state — The countdown state.

Returns: The badge label, or ''.

chatCardBorder(accent, pct)

Build the tinted border colour for a chat info card from its accent.

function chatCardBorder(accent?: string, pct?: number): string
  • accent — Accent source colour (CSS var or hex). Defaults to the theme primary.
  • pct — Opacity of the accent in the mix (percent). Defaults to the resting 40.

Returns: A color-mix border colour.

chatCardBg(accent, pct)

Build the tinted background colour for a chat info card from its accent.

function chatCardBg(accent?: string, pct?: number): string
  • accent — Accent source colour (CSS var or hex). Defaults to the theme primary.
  • pct — Opacity of the accent in the mix (percent). Defaults to the resting 10.

Returns: A color-mix background colour.

chatCardStyle(accent, borderPct)

The single container chrome shared by every boxed info card in the chat timeline: subtle tint, full 1px border on all sides, one padding, one radius.

Spread it first, then add layout (display/gap/alignItems) and the bottom-margin rhythm at the call site — e.g. style={{ display: 'flex', gap: 10, marginBottom: TIMELINE_ITEM_GAP, ...chatCardStyle(accent) }}.

A card that deepens its frame on hover sets the whole border to chatCardStyle(accent, 70).border, never borderColor alone: the frame is a shorthand holding a CSS variable, and a longhand written over it leaves its other longhands with no readable value (getPropertyValue returns ''), in a browser and in the conformance kit.

function chatCardStyle(accent?: string, borderPct?: number): ChatCardStyle
  • accent — Tint/border source colour. Defaults to the theme primary (neutral cards).
  • borderPct — Opacity of the accent in the border mix (percent). Defaults to the resting 40.

Returns: The container style chrome (border, background, padding, radius).

relativeTime(iso)

Formats an ISO timestamp as a relative time string (e.g. "5m ago", "2h ago").

function relativeTime(iso: string): string
  • iso — The ISO 8601 timestamp string.

Returns: A human-readable relative time string.

allowanceResetCountdown(t, resetAt)

Format an AI-allowance window reset (epoch ms) as a short countdown phrase for the /cost used-up line ("refreshes in about 3 hours"). Under an hour reads "in under an hour"; ≥ 6h out on a later local calendar day reads "tomorrow"; a day or more out reads "in about N days".

The day scale is what makes this usable on a BILLING-PERIOD allowance, which can be weeks out — an hours-only formatter capped at "tomorrow", so a window ending in 18 days told the user it came back in the morning.

function allowanceResetCountdown(t: TranslateFunction, resetAt: number): string
  • t — The translation function from useTranslation().
  • resetAt — Epoch ms of the window end (always in the future from the API).

Returns: A localized human countdown phrase.

fileToBase64(file)

Reads a File as base64 (without data-URL prefix).

function fileToBase64(file: File): Promise<string>
  • file — The file to encode.

Returns: Base64-encoded string.

formatSize(bytes)

Formats a byte count as a human-readable size string.

function formatSize(bytes: number): string
  • bytes — The size in bytes.

Returns: Formatted string (e.g., "1.2MB").

formatThinkingDuration(t, ms)

Format a duration in milliseconds as a human-readable string.

function formatThinkingDuration(t: TranslateFunction, ms: number): string
  • t — The translation function from useTranslation().
  • ms — Duration in milliseconds.

Returns: Formatted string like "Thought for 5 seconds" or "Thought for 2 minutes".

panelOverlayHeading(t, overlay)

The heading of the closeable panel overlay (/skills, /scripts, /settings) above the composer.

function panelOverlayHeading(
  t: TranslateFunction,
  overlay: 'skills' | 'scripts' | 'settings' | 'tests',
): string

streamingActivityLabel(t, msg)

Derive a real current-activity label for the streaming indicator from the in-flight assistant message's latest block, so the user sees what's actually happening (e.g. "Reading App.tsx", "Writing the plan") instead of a generic spinner. Returns undefined when there's nothing specific to show (the indicator then falls back to its rotating generic messages).

function streamingActivityLabel(
  t: TranslateFunction,
  msg: {
    blocks?: ChatMessage['blocks']
    toolCalls?: Array<Pick<NonNullable<ChatMessage['toolCalls']>[number], 'id' | 'name' | 'input'>>
  },
): string | undefined
  • t — The translation function from useTranslation().
  • msg — The streaming assistant message.
  • msg.blocks — The message's ordered blocks (a tool call is a tool_call block naming its id).
  • msg.toolCalls — The message's tool calls, looked up by block id.

Returns: A short activity label, or undefined.

parseReportCommand(input)

Parses a /report [title] or /bug [title] command. Returns the (possibly empty) trimmed title used to seed the modal when the input is one of those commands, else null.

function parseReportCommand(input: string): { title: string } | null
  • input — The raw chat input.

Returns: { title } when it's a /report or /bug command, else null.

collectClientInfo(opts)

Collects client-side diagnostics for a report. Reads navigator (userAgent/platform/language), window (inner viewport size, screen size, location href), plus the caller-supplied app version and theme. Every access is guarded (typeof window/navigator !== 'undefined' and per-property presence) so it is SSR-safe and never throws — it returns only the fields it could actually read, so the result may be partial or (in a headless environment) empty.

function collectClientInfo(opts?: { appVersion?: string; theme?: string }): ClientInfo
  • opts — Caller-supplied context.
  • opts.appVersion — The running build version, if known.
  • opts.theme — The active theme ('light' | 'dark'), if known.

Returns: The populated subset of ClientInfo.

buildReportPayload(form, clientInfo)

Builds the POST /projects/:id/report body from the form state, trimming all text fields and omitting steps entirely when it is blank. When clientInfo is supplied and non-empty, it is attached; an undefined or empty diagnostics object is omitted from the payload.

function buildReportPayload(form: ReportFormState, clientInfo?: ClientInfo): ReportPayload
  • form — The report form state.
  • clientInfo — Optional client diagnostics from collectClientInfo.

Returns: The normalized report payload.

isReportFormValid(form)

Whether the report form has the minimum required fields: a non-empty title and a non-empty description.

function isReportFormValid(form: ReportFormState): boolean
  • form — The report form state.

Returns: true when the form can be submitted.

formatReportConfirmation(result)

Builds the confirmation message shown after a report is submitted. Returns the English defaults; the component passes these through t() at render. The success defaultValue may contain the {{productName}} interpolation token, which the caller fills in from the host's product identity (neutral default: "the IDE"). When the result is not ok, returns the failure message.

function formatReportConfirmation(result: ReportResult): {
  key: string
  defaultValue: string
}
  • result — The POST /projects/:id/report response.

Returns: { key, defaultValue } for the confirmation/failure message.

isShareRole(value)

Type guard for a valid ShareRole (case-insensitive callers should lower-case first).

function isShareRole(value: string): value is ShareRole
  • value — The candidate value.

Returns: true when value is one of the SHARE_ROLES.

parseShareCommand(input)

Parses a /share [role] command. Bare /share creates a link at the default viewer role; /share <role> uses the named role when valid (any case); an unrecognized role is reported as invalid so the caller can show usage. Returns null when the input is not the /share command.

function parseShareCommand(input: string): ShareCommand | null
  • input — The raw chat input.

Returns: The parsed ShareCommand, or null.

buildSharePayload(role)

Builds the POST /projects/:projectId/shares body for a role.

function buildSharePayload(role?: ShareRole): SharePayload
  • role — The role to grant (defaults to DEFAULT_SHARE_ROLE).

Returns: The normalized share payload.

buildShareUrl(result, origin)

Resolves the copyable public URL for a created share link. Prefers the backend-supplied url (canonical origin / custom domain); otherwise builds <origin>/share/<slug> from the given origin, tolerating a trailing slash.

function buildShareUrl(result: ShareLinkResult, origin: string): string
  • result — The created link from the share endpoint.
  • origin — The current page origin (e.g. window.location.origin).

Returns: The absolute, copyable share URL.

shareRoleLabel(t, role)

The localized picker label for a share role (the ide.chat.share.role.<role> keys), through the CALLER's translate function so a framework port and a live locale switch both get their own text. One literal t() call per ShareRole, chosen by a switch exhaustive over the role union: a new role in SHARE_ROLES fails to compile until it has a label. Each defaultValue equals that role's SHARE_ROLE_LABELS entry, so the English output is unchanged.

function shareRoleLabel(t: TranslateFunction, role: ShareRole): string
  • t — The caller's translate function (React passes useTranslation()'s t).
  • role — The share role.

Returns: The localized role label.

shareGrantsText(t, role)

The localized sentence saying what a link of the given role grants (the ide.chat.share.grants.<role> keys), through the CALLER's translate function. One literal t() call per ShareRole, exhaustive (see shareRoleLabel); the role itself interpolates through {{role}}.

function shareGrantsText(t: TranslateFunction, role: ShareRole): string
  • t — The caller's translate function.
  • role — The role the link grants.

Returns: The localized grants sentence.

shareSubheading(t, role)

The localized subheading shown under the share dialog's heading for a host offering a single role (the ide.chat.share.subheading.<role> keys), through the CALLER's translate function. One literal t() call per ShareRole, exhaustive (see shareRoleLabel); the role interpolates through {{role}}. The multi-role variant is the plain ide.chat.share.subheading key the caller uses directly.

function shareSubheading(t: TranslateFunction, role: ShareRole): string
  • t — The caller's translate function.
  • role — The single role the host grants.

Returns: The localized subheading.

parseChatTimestampsVisible(raw)

Parses the stored preference. Only an explicit 'true' shows every timestamp, so a missing or unreadable value keeps the default (off — only the user's own message headers and critical events carry a time; see planChatTimestamps).

function parseChatTimestampsVisible(raw: string | null): boolean
  • raw — The raw localStorage value.

Returns: Whether timestamps are visible on every item.

getChatTimestampsVisible()

Reads this device's preference.

function getChatTimestampsVisible(): boolean

Returns: Whether chat timestamps are visible on every item (default false).

resolveChatLocale(getLocale) (deprecated)

Deprecated: A component that formats with this keeps the old language after a locale switch, because nothing re-renders it. Read the locale through the framework binding instead (useLocale() in React), which re-renders on a switch. getLocale() from @molecule/app-i18n does not throw: with no provider bonded it bonds a default one.

The active i18n locale, or the browser's when reading it throws.

function resolveChatLocale(getLocale: () => string): string
  • getLocale — The i18n accessor.

Returns: A BCP 47 locale.

planChatTimestamps(slots, options)

Decides which timeline items actually render their timestamp. An item is a candidate when timestamps are on, or when its slot is ChatTimestampSlot.alwaysShown. A candidate renders only when its label differs from the last RENDERED label, so a run of items that would all read "3 minutes ago" shows it once, at the top of the run. Re-run on every minute tick: labels move with the clock, so the grouping does too.

function planChatTimestamps(
  slots: readonly (ChatTimestampSlot | null)[],
  options: { visible: boolean; now: number; locale: string },
): Set<string>
  • slots — One entry per rendered timeline item, in order (null = no timestamp).
  • options — The visibility preference, the current time, and the locale.
  • options.visible — Whether timestamps are turned on for every item.
  • options.now — Epoch milliseconds to measure from.
  • options.locale — BCP 47 locale for the labels.

Returns: The ids of the items whose timestamp renders.

setChatTimestampsVisible(visible)

Persists this device's preference and notifies every mounted chat in this tab.

function setChatTimestampsVisible(visible: boolean): void
  • visible — Whether chat timestamps should be shown.

parseTimestampsCommand(input)

Parses /timestamps [on | off]. show/hide are accepted as synonyms.

function parseTimestampsCommand(input: string): TimestampsCommand | null
  • input — The trimmed composer text.

Returns: The parsed command, or null when the text is not /timestamps.

formatChatRelativeTime(ms, now, locale)

Short, localized, MINUTE-precise time for a chat item: "now" and "5 minutes ago" within the hour, then the clock time ("9:25 AM") for earlier today, then the date and time ("Sep 12, 9:25 AM", with the year when it differs).

Minute precision at every age is load-bearing: planChatTimestamps collapses runs of identical labels, so a coarse label ("1 hour ago", "3 days ago") would collapse a whole hour or day of history into one timestamp. Localized by Intl, so it needs no translation keys.

function formatChatRelativeTime(ms: number, now: number, locale: string): string
  • ms — Epoch milliseconds of the item.
  • now — Epoch milliseconds to measure from.
  • locale — BCP 47 locale (e.g. 'en', 'fr').

Returns: The formatted label.

formatChatFullTime(ms, locale)

Exact, localized date and time for a chat item's tooltip and <time dateTime> companion (e.g. "Sep 13, 2026, 2:05 PM").

function formatChatFullTime(ms: number, locale: string): string
  • ms — Epoch milliseconds of the item.
  • locale — BCP 47 locale.

Returns: The formatted date and time.

isDeviceRotatable(device)

Whether a device frame can be rotated (true only for fixed-frame devices — tablet and mobile). Responsive and desktop are full-width with nothing to rotate, so the "Rotate" control is enabled only "where possible".

function isDeviceRotatable(device: DeviceFrame): boolean
  • device — The device frame.

Returns: true if the frame has a fixed size that can be rotated.

resolveDeviceSize(device, orientation)

Resolves the concrete iframe width/height for a device frame at a given orientation. Fluid frames (responsive/desktop) ignore orientation and fill the preview area (width from dims, height: '100%'). Fixed frames render at their pixel size in portrait and at the swapped size in landscape.

function resolveDeviceSize(
  device: DeviceFrame,
  orientation: DeviceOrientation,
): { width: string; height: string }
  • device — The device frame.
  • orientation — The preview orientation.

Returns: The CSS width and height to apply to the preview iframe.

deviceIconName(device)

Returns the icon-set glyph name for a device frame.

function deviceIconName(device: DeviceFrame): string
  • device — The device frame.

Returns: The icon name registered in the bonded icon set.

groupTests(tests)

Group tests for display: by kind (end-to-end first), then by project directory (whatever directories are present — app, my-app/app, packages/web, the root last), with the files sorted inside each group.

function groupTests(tests: readonly TestItem[]): TestGroup[]
  • tests — Every discovered test.

Returns: The groups, in display order. Empty groups are never produced.

countByKind(tests)

How many tests there are of each kind.

function countByKind(tests: readonly TestItem[]): Record<TestKind, number>
  • tests — Every discovered test.

Returns: The per-kind counts.

summarizeResults(tests, results)

The tallies of the last run, over the tests that are still listed. Counted per FILE (one row, one verdict) so the collapsed summary matches the rows.

function summarizeResults(
  tests: readonly TestItem[],
  results: Record<string, TestResultEntry>,
): { passed: number; failed: number; skipped: number; reported: number }
  • tests — The currently listed tests.
  • results — The per-id outcomes.

Returns: Passed/failed/skipped file counts.

applyTestRunEvent(state, event)

Fold one streamed event into the run state.

Deliberately total: an event for an id the card no longer lists is recorded anyway (a re-list may be in flight), a case that arrives out of order (after its file already reported a verdict) is dropped rather than resurrecting a finished row, and an unknown event type leaves the state untouched rather than throwing inside a stream handler.

function applyTestRunEvent(state: TestsRunState, event: TestRunEvent): TestsRunState
  • state — The current state.
  • event — The event just received.

Returns: The next state (a new object whenever anything changed).

requestSkip(state)

Record that the person asked to skip what is running. The state only says a request is OUT — the run's own result for the skipped file is what actually moves the row, so nothing here can make a skipped file read as anything else.

function requestSkip(state: TestsRunState): TestsRunState
  • state — The current state.

Returns: The next state, or the same one when there is nothing to skip.

markSkipUnavailable(state)

Record that skipping is not on offer — either the host wired no skipCurrent or it answered that the run had already moved on. The control is dropped; the person is not shown an error about a race they did not cause.

function markSkipUnavailable(state: TestsRunState): TestsRunState
  • state — The current state.

Returns: The next state.

canSkipRun(state)

Whether the host can be asked to skip right now.

function canSkipRun(state: TestsRunState): boolean
  • state — The run state.

Returns: True when a Skip control belongs on screen.

currentRunRowId(state)

Which row the Skip acts on: the one the stream named as current, or — when it has not named one yet — the single row still awaiting a verdict, because with exactly one candidate there is nothing to be ambiguous about.

function currentRunRowId(state: TestsRunState): string | null
  • state — The run state.

Returns: The row's id, or null when the run is not on an identifiable row.

testCaseLabel(current)

The one-line name of the test a file is on: its group and its title, or just its title when the runner gave it no group.

function testCaseLabel(current: TestCaseRef | null | undefined): string
  • current — The running test, or null.

Returns: The label, or `` when nothing is named.

failRun(state, message)

The state after a run that never produced a done event — the host's stream died, or its request failed before the server could answer.

function failRun(state: TestsRunState, message: string): TestsRunState
  • state — The current state.
  • message — What to show in the card.

Returns: The next state, no longer running.

isRowRunning(state, id)

Whether a row should render as "running": the run is live and either the host named this row as current, or it is in the queue and has no verdict yet.

function isRowRunning(state: TestsRunState, id: string): boolean
  • state — The run state.
  • id — The row's test id.

Returns: True when the row is part of the live run and still undecided.

testRowLabel(item)

The label for a row: the host's title when it gave one, else the file path.

function testRowLabel(item: TestItem): string
  • item — The test.

Returns: The label to render.

filterTests(tests, query)

Filters tests by a free-text query, matching (case-insensitively) against the file path, the row title, and the project directory. A blank query returns every test in input order — the same contract as filterScripts.

function filterTests(tests: readonly TestItem[], query: string): TestItem[]
  • tests — The tests to filter.
  • query — The search query.

Returns: The matching tests, in input order.

parseTestCommand(input)

Parses a /test [query | all] command (/tests is the registered alias).

all is the one argument that ACTS: it runs everything immediately. Every other argument only filters the list, exactly the way /scripts <query> seeds the scripts browser — running ONE test by name is what the per-row Run button is for, and giving the argument a second meaning would make /test <thing> sometimes list and sometimes execute.

function parseTestCommand(input: string): { query: string; runAll: boolean } | null
  • input — The raw chat input.

Returns: { query, runAll } when it is a /test command, else null.

buildTestFixMessage(failures)

Compose the ONE user message the card's “Fix with Synthase” action sends.

It is a real turn the executor answers, so it reads like something a person would type: which test failed, where it lives, what the runner said, and to re-run it. This is a PROMPT, not UI copy — it is not translated, exactly like the auto-fix loop’s own Fix these issues: message.

function buildTestFixMessage(failures: readonly TestFailure[]): string
  • failures — The failing tests, in the order the card lists them.

Returns: The message, or `` when there is nothing to fix.

failedTests(tests, results)

Every listed test whose last verdict was a failure, with its output — what the card's fix actions send.

function failedTests(
  tests: readonly TestItem[],
  results: Record<string, TestResultEntry>,
): TestFailure[]
  • tests — The currently listed (and filtered) tests.
  • results — The per-id outcomes.

Returns: The failures, in list order.

resolveUserAvatar(avatar)

Resolve a stored avatar value to a safe <img> src, or null to fall back to the generic icon.

function resolveUserAvatar(avatar?: string | null): string | null
  • avatar — The avatar value from user metadata (data-URI, URL, or absent).

Returns: A safe image src string, or null when there is no renderable avatar.

hasRenderableAvatar(avatar)

Whether a stored avatar value is renderable (vs. needing the icon fallback).

function hasRenderableAvatar(avatar?: string | null): boolean
  • avatar — The avatar value from user metadata.

Returns: true when resolveUserAvatar would return a src.

clampPanelSize(currentSize, deltaPx, containerWidth, min, max)

Clamp a panel's new size after a pixel drag delta.

function clampPanelSize(
  currentSize: number,
  deltaPx: number,
  containerWidth: number,
  min?: number,
  max?: number,
): number
  • currentSize — The panel's current size as a percentage.
  • deltaPx — The drag delta in pixels (positive = grow the left panel).
  • containerWidth — The layout container width in pixels.
  • min — Minimum allowed percentage. Defaults to MIN_PANEL_PERCENT.
  • max — Maximum allowed percentage. Defaults to MAX_PANEL_PERCENT.

Returns: The new size as a percentage, clamped to [min, max].

livePanelSize(layout, panelConfigs, index)

The live size (percentage) of the visible panel at index, read from layout.sizes keyed by the panel's position group (where resizePanel writes), falling back to the panel's defaultSize, then to an equal split.

function livePanelSize(layout: WorkspaceLayout, panelConfigs: PanelConfig[], index: number): number
  • layout — The current workspace layout.
  • panelConfigs — The visible panel configs, in render order.
  • index — The index of the panel within panelConfigs.

Returns: The panel size as a percentage.

registerCustomEventCard(name, factory)

Register a renderer for a custom chat-stream event. Consuming apps call this at startup so their own { type: 'custom', name } events surface as chat cards — keeping app-specific events out of the core ai-chat union and this package's ChatPanel. Re-registering the same name overwrites the previous factory.

function registerCustomEventCard(name: string, factory: ChatEventCardFactory): void
  • name — The custom event name to handle (matches the emitted event's name).
  • factory — Builds the card from the event's data (or returns null to skip).

getCustomEventCardFactory(name)

Resolve the registered card factory for a custom event name, if any.

function getCustomEventCardFactory(name: string): ChatEventCardFactory | undefined
  • name — The custom event name.

Returns: The registered factory, or undefined if none is registered.

serializeEvent(e, isMac)

Serialize a KeyboardEvent into a normalized combo string. Format: modifier keys in order mod+ctrl+alt+shift+key (lowercase). mod maps to Meta on Mac, Control elsewhere.

function serializeEvent(e: KeyboardEvent, isMac?: boolean): string
  • e — The keyboard event.
  • isMac — Override platform detection (for testing).

Returns: Serialized combo string.

normalizeKeys(keys)

Normalize a shortcut definition string into the same format produced by serializeEvent. Accepts mod+shift+f style strings (case-insensitive).

function normalizeKeys(keys: string): string
  • keys — Raw shortcut string.

Returns: Normalized lowercase combo string.

isInputFocused(e)

Returns true when the event target is an interactive input element where shortcuts should be suppressed by default.

function isInputFocused(e: KeyboardEvent): boolean
  • e — The keyboard event.

Returns: Whether an input-like element is focused.

isMonacoFocused(e)

Returns true when focus is inside a Monaco editor instance.

function isMonacoFocused(e: KeyboardEvent): boolean
  • e — The keyboard event.

Returns: Whether the target is inside .monaco-editor.

isShortcutBlockedByFocus(shortcut, e)

Whether where the key was pressed rules a shortcut out. Inside the Monaco editor only allowInEditor decides: Monaco takes keys through its own hidden <textarea>, which is the editor, not a text field, so allowInInput neither blocks nor allows it there. Elsewhere a text field (<input>, <textarea>, <select>, an editable element) rules it out unless allowInInput is set.

function isShortcutBlockedByFocus(
  shortcut: Pick<KeyboardShortcut, 'allowInInput' | 'allowInEditor'>,
  e: KeyboardEvent,
): boolean
  • shortcut — The shortcut's focus flags.
  • e — The keyboard event.

Returns: true when the shortcut must not fire for this event.

findKeyboardShortcut(shortcuts, e, isMac)

The shortcut a keydown triggers: the first whose keys match the event's combo and whose focus flags allow where it was pressed (isShortcutBlockedByFocus). A matching shortcut the focus rules out lets a later one with the same keys fire.

function findKeyboardShortcut<S extends KeyboardShortcut>(
  shortcuts: readonly S[],
  e: KeyboardEvent,
  isMac?: boolean,
): S | undefined
  • shortcuts — The registered shortcuts, in priority order.
  • e — The keyboard event.
  • isMac — Override platform detection (for testing).

Returns: The shortcut to run, or undefined when the key is not one.

settingLabel(t, id)

The localized label of a user-controllable setting (the ide.chat.settings.<id>.label keys), through the CALLER's translate function so a framework port and a live locale switch both get their own text. One literal t() call per SettingKey, chosen by a switch exhaustive over the union: adding a setting to SETTINGS without adding its case here is a compile error, so a setting can never ship with no translation site. Each defaultValue equals that setting's label field, so the English output is identical either way.

function settingLabel(t: TranslateFunction, id: SettingKey): string
  • t — The caller's translate function (React passes useTranslation()'s t).
  • id — The setting id.

Returns: The localized label.

settingDescription(t, id, values)

The localized one-line explanation of a user-controllable setting (the ide.chat.settings.<id>.desc keys), through the CALLER's translate function. One literal t() call per SettingKey, exhaustive over the union (see settingLabel). Each defaultValue equals that setting's description field, so the English output is identical either way; the descriptions interpolate {{agentName}}, filled from the caller's agent identity.

function settingDescription(
  t: TranslateFunction,
  id: SettingKey,
  values?: InterpolationValues,
): string
  • t — The caller's translate function.
  • id — The setting id.
  • values — Interpolation values (the descriptions interpolate {{agentName}}).

Returns: The localized description.

Constants

COMMAND_CATEGORIES

Ordered list of command categories used as section headings.

const COMMAND_CATEGORIES: readonly CommandCategory[]

COMMANDS

Every available slash command, grouped by category order. This is the authoritative list — the menu, key handling, /help, AND the system prompt's "Available Commands" section all read from it.

const COMMANDS: readonly [
  {
    readonly id: 'clear'
    readonly label: '/clear'
    readonly description: 'Clear conversation'
    readonly category: 'context'
  },
  {
    readonly id: 'compact'
    readonly label: '/compact'
    readonly description: 'Compress context to free space'
    readonly category: 'context'
  },
  {
    readonly id: 'cost'
    readonly label: '/cost'
    readonly description: "Show token usage & share of the project's AI allowance"
    readonly category: 'context'
    readonly viewerSafe: true
  },
  {
    readonly id: 'skills'
    readonly label: '/skills'
    readonly description: 'Browse & load project skills'
    readonly category: 'context'
    readonly usage: '/skills [query]'
  },
  {
    readonly id: 'commit'
    readonly label: '/commit'
    readonly description: 'Commit current changes'
    readonly category: 'code'
  },
  {
    readonly id: 'explain'
    readonly label: '/explain'
    readonly description: 'Explain code (e.g. /explain @file)'
    readonly category: 'code'
    readonly usage: '/explain [@file | topic]'
  },
  {
    readonly id: 'lint'
    readonly label: '/lint'
    readonly description: 'Run linter and fix issues'
    readonly category: 'code'
    readonly usage: '/lint [path]'
  },
  {
    readonly id: 'test'
    readonly label: '/test'
    readonly description: "List and run the project's tests"
    readonly category: 'code'
    readonly usage: '/test [query | all]'
    readonly aliases: readonly ['tests']
    readonly viewerSafe: true
  },
  {
    readonly id: 'undo'
    readonly label: '/undo'
    readonly description: "Revert last AI turn's file changes"
    readonly category: 'code'
  },
  {
    readonly id: 'scripts'
    readonly label: '/scripts'
    readonly description: 'Browse & run saved scripts and built-in actions'
    readonly category: 'code'
    readonly usage: '/scripts [query]'
  },
  {
    readonly id: 'run'
    readonly label: '/run'
    readonly description: 'Run a saved script or built-in by name'
    readonly category: 'code'
    readonly usage: '/run <name> [--option value]'
  },
  {
    readonly id: 'autocommit'
    readonly label: '/autocommit'
    readonly description: 'Auto-commit N seconds after the last file change (0 cancels)'
    readonly category: 'code'
    readonly usage: '/autocommit <seconds>'
  },
  {
    readonly id: 'autofix'
    readonly label: '/autofix'
    readonly description: 'Toggle auto-fix after AI file changes'
    readonly category: 'code'
  },
  {
    readonly id: 'autoapprove'
    readonly label: '/autoapprove'
    readonly description: 'Toggle auto-approving destructive commands (skip the Proceed confirm)'
    readonly category: 'code'
  },
  {
    readonly id: 'share'
    readonly label: '/share'
    readonly description: 'Create a public share link for this project'
    readonly category: 'collaborate'
    readonly usage: '/share [viewer | commenter | editor | owner]'
  },
  {
    readonly id: 'model'
    readonly label: '/model'
    readonly description: 'Switch the model for any mode (plan, execute, commit messages, compaction)'
    readonly category: 'model'
    readonly usage: '/model [name | --plan | --execute | --commit | --compact]'
  },
  {
    readonly id: 'plan'
    readonly label: '/plan'
    readonly description: 'Toggle plan/execute mode'
    readonly category: 'model'
  },
  {
    readonly id: 'maxloops'
    readonly label: '/maxloops'
    readonly description: 'Set max tool iterations'
    readonly category: 'model'
    readonly usage: '/maxloops <n>'
  },
  {
    readonly id: 'effort'
    readonly label: '/effort'
    readonly description: "Pick reasoning effort per mode from the model's own levels"
    readonly category: 'model'
    readonly usage: '/effort [--plan|--execute] [level]'
  },
  {
    readonly id: 'settings'
    readonly label: '/settings'
    readonly description: "View & change {{agentName}}'s settings"
    readonly category: 'settings'
    readonly viewerSafe: true
  },
  {
    readonly id: 'sounds'
    readonly label: '/sounds'
    readonly description: 'Notification sounds'
    readonly category: 'settings'
    readonly viewerSafe: true
  },
  {
    readonly id: 'timestamps'
    readonly label: '/timestamps'
    readonly description: 'Show or hide the time on chat messages and events'
    readonly category: 'settings'
    readonly usage: '/timestamps [on | off]'
    readonly viewerSafe: true
  },
  {
    readonly id: 'mic'
    readonly label: '/mic'
    readonly description: 'Choose the dictation engine (on-device / browser native)'
    readonly category: 'settings'
    readonly viewerSafe: true
  },
  {
    readonly id: 'dictate'
    readonly label: '/dictate'
    readonly description: 'Choose the dictation engine (alias for /mic)'
    readonly category: 'settings'
    readonly viewerSafe: true
  },
  {
    readonly id: 'help'
    readonly label: '/help'
    readonly description: 'Workflow guide & tips'
    readonly category: 'support'
    readonly viewerSafe: true
  },
  {
    readonly id: 'report'
    readonly label: '/report'
    readonly description: 'Report a bug or send feedback'
    readonly category: 'support'
    readonly usage: '/report [title]'
    readonly viewerSafe: true
  },
  {
    readonly id: 'bug'
    readonly label: '/bug'
    readonly description: 'Report a bug (alias for /report)'
    readonly category: 'support'
    readonly usage: '/bug [title]'
    readonly viewerSafe: true
  },
  {
    readonly id: 'version'
    readonly label: '/version'
    readonly description: 'Show the app version'
    readonly category: 'support'
    readonly viewerSafe: true
  },
]

ACTIVITY_TYPES

All channel types, in the order their filter tabs should appear.

const ACTIVITY_TYPES: ActivityType[]

AUTO_COMMIT_DISABLED

The disabled (off) countdown state — the reducer's initial value.

const AUTO_COMMIT_DISABLED: AutoCommitState

DEFAULT_AUTO_COMMIT_SECONDS

The default auto-commit cadence in seconds — auto-commit is ON by default. Projects that have never persisted autoCommitSeconds hydrate to this cadence (paused, arming on the first file change); only an explicit 0 (the user cancelled) keeps auto-commit off.

The value is the TOTAL debounce after the last file change (once the agent's turn has finished): a short quiet period, then the final AUTO_COMMIT_COUNTDOWN_VISIBLE_SECONDS seconds render as a live countdown on the commit button. 5s = 2s quiet + 3s visible countdown.

const DEFAULT_AUTO_COMMIT_SECONDS: 5

AUTO_COMMIT_COUNTDOWN_VISIBLE_SECONDS

How many final seconds of the countdown are DISPLAYED as a live countdown. Until the countdown drops to this threshold, the commit-bar button stays a plain green "Commit" (a bare "12s" pill told users nothing); the countdown label only takes over for these last seconds, right before the auto-commit fires. Cadences at or below the threshold show the countdown the whole time.

const AUTO_COMMIT_COUNTDOWN_VISIBLE_SECONDS: 3

CHAT_CARD_NEUTRAL_ACCENT

Neutral accent for non-semantic info cards: the theme's primary colour, so a card that has no status meaning is still subtly tinted (never a flat gray surface) and recolors with the brand.

const CHAT_CARD_NEUTRAL_ACCENT: 'var(--mol-color-primary, #6366f1)'

CHAT_CARD_ICON_SIZE

Uniform leading-icon size (px) for every chat-timeline info card.

const CHAT_CARD_ICON_SIZE: 18

EMPTY_REPORT_FORM

An empty report form (the modal's initial state).

const EMPTY_REPORT_FORM: ReportFormState

SHARE_ROLES

Share roles, ordered least- to most-privileged. Mirrors the @molecule/api-resource-share SHARE_ROLES contract; duplicated here (rather than imported) because an app-* package may not import an api-* package across the stack boundary.

const SHARE_ROLES: readonly ['viewer', 'commenter', 'editor', 'owner']

DEFAULT_SHARE_ROLE

The default (and safest) role when /share is run with no argument.

const DEFAULT_SHARE_ROLE: ShareRole

SHARE_ROLE_LABELS

Short English labels per role (the component wraps these in t() at render).

const SHARE_ROLE_LABELS: Record<ShareRole, string>

CHAT_TIMESTAMPS_STORAGE_KEY

localStorage key holding 'true' / 'false'. Absent = the default (hidden).

const CHAT_TIMESTAMPS_STORAGE_KEY: 'mol_chat_show_timestamps'

CHAT_TIMESTAMPS_EVENT

Window event dispatched (same tab) whenever the preference changes.

const CHAT_TIMESTAMPS_EVENT: 'mol:chat-timestamps-changed'

CHAT_CARD_CODE_STYLE

Subtle inline monospace code style for command/identifier spans in chat cards.

const CHAT_CARD_CODE_STYLE: ChatCardCodeStyle

Inline link style for action segments in chat cards (theme primary, underlined).

const CHAT_CARD_LINK_STYLE: ChatCardLinkStyle

USER_ACCENT_STYLE

User-message accent stripe. The left edge of a real user message draws a vertical, multi-tone BLUE gradient swept gently up and down (the same smooth single-gradient technique as the composer ring, but vertical + blue) — NOT a repeating barber-pole, which read busy + janky. The host supplies the curated blues via --mol-chat-accent-gradient; the fallback is a lightened primary so it stays blue + never dark in any theme (the theme's primary-light/-dark tokens are actually a medium

  • a dark blue with no light tone). It's a full-box gradient (so the sweep has room to travel) clipped to a 3px LEFT band that follows the row's rounded corners. A ::before + its keyframe can't be expressed inline (and inline animation can't be media-queried), so — like AutoCommitBadge — it is injected once and gated on the existing data-mol-id; the auto-sent row keeps its solid success accent.
const USER_ACCENT_STYLE: '\n[data-mol-id="chat-user-message"] { position: relative; }\n[data-mol-id="chat-user-message"]::before {\n  content: \'\';\n  position: absolute;\n  inset: 0;\n  border-radius: inherit;\n  background: var(--mol-chat-accent-gradient, linear-gradient(to bottom, color-mix(in srgb, var(--mol-color-primary, #3060c0) 85%, #fff), color-mix(in srgb, var(--mol-color-primary, #3060c0) 50%, #fff) 50%, color-mix(in srgb, var(--mol-color-primary, #3060c0) 85%, #fff)));\n  background-size: 100% 300%;\n  animation: mol-chat-accent-flow 6s ease-in-out infinite;\n  -webkit-mask: linear-gradient(to right, #000 3px, transparent 3px);\n  mask: linear-gradient(to right, #000 3px, transparent 3px);\n  pointer-events: none;\n}\n@keyframes mol-chat-accent-flow {\n  0%, 100% { background-position: 50% 0%; }\n  50% { background-position: 50% 100%; }\n}\n@media (prefers-reduced-motion: reduce) {\n  [data-mol-id="chat-user-message"]::before { animation: none; }\n}'

MAX_ATTACHMENT_SIZE

Maximum file size for attachments (20 MB).

const MAX_ATTACHMENT_SIZE: number

ACCEPTED_FILE_TYPES

MIME types accepted by the file input for AI provider attachments.

const ACCEPTED_FILE_TYPES: 'image/jpeg,image/png,image/gif,image/webp,image/svg+xml,application/pdf,audio/mpeg,audio/wav,audio/ogg,audio/flac,audio/webm,video/mp4,video/webm'

USER_MSG_COLLAPSE_HEIGHT

Height threshold (px) above which user messages get collapsed.

const USER_MSG_COLLAPSE_HEIGHT: 150

LOAD_EARLIER_THRESHOLD_PX

Distance from the top (px) at which scrolling up pages in older timeline items. Same idea as the 80px bottom threshold of the stick-to-bottom detector: a margin, so the trigger fires while the user is still moving, not only pinned exactly at scrollTop 0.

const LOAD_EARLIER_THRESHOLD_PX: 120

APP_VERSION

The version this IDE reports — read by the /version command output AND the /version entry's description in the slash-command menu, so the menu shows the real number, not a stale literal.

const APP_VERSION: '0.1.0'

TIMELINE_ITEM_GAP

Standard bottom margin (px) every chat-timeline item owns. 8px-grid rhythm unit.

const TIMELINE_ITEM_GAP: 16

TIMELINE_ITEM_GAP_DISCOVERY

Roomier bottom margin (px) for discovery-phase message cards (intentionally looser).

const TIMELINE_ITEM_GAP_DISCOVERY: 24

AUTO_SENT_ACCENT

Accent (success green) for an auto-sent message card — drives its tint, 1px border and sync icon via chatCardStyle, so an agent-sent message is unmistakably green while sharing the exact card shape of the user message and info cards.

const AUTO_SENT_ACCENT: 'var(--mol-color-success, #16a34a)'

NOTICE_TONE

The accent + default icon per notice tone, keyed by tone id.

const NOTICE_TONE: Record<
  'info' | 'gold' | 'upgrade' | 'success' | 'signup',
  { accent: string; icon: IconName }
>

NOTICE_TONE_BUTTON_COLOR

The SEMANTIC button colour each notice tone falls back to when the host gives an action no explicit color. Every notice-card action is a design-system button; this is only about which semantic it takes when the caller did not say. Without it a coloured action and a colourless one rendered side by side in the SAME card with two different box models (13px/3px vs a hand-rolled 12px/6px) — the exact mismatch this treatment exists to prevent.

const NOTICE_TONE_BUTTON_COLOR: Record<
  'info' | 'gold' | 'upgrade' | 'success' | 'signup',
  NonNullable<ChatEventCardAction['color']>
>

DEVICE_FRAMES

The device frames the selector dropdown lists, in display order. none = responsive (no fixed frame, full width).

const DEVICE_FRAMES: readonly DeviceFrame[]

DEVICE_META

Per-frame display metadata: the icon-set glyph name and the i18n label (key + English default) shown in the dropdown trigger + menu items.

const DEVICE_META: Record<
  DeviceFrame,
  { readonly icon: IconName; readonly labelKey: string; readonly label: string }
>

DEVICE_DIMENSIONS

The fixed pixel frame each device renders the preview iframe at. none (responsive) and desktop are fluid — full width, full height, nothing to rotate. tablet (768×1024) and mobile (375×667) are fixed frames that can be rotated to landscape (swapping width/height).

const DEVICE_DIMENSIONS: Record<DeviceFrame, DeviceDimensions>

DEFAULT_SEARCH_EXCLUDED_DIRS

Default search-excluded directory names shown when the host supplies none — VS Code's search.exclude/files.exclude defaults plus the platform's vendored/build dirs. MUST stay in sync with the API-side list in @molecule/api-ai-tools (utilities.ts) — the cross-stack import boundary forces the duplication; molecule/scripts/__tests__/search-excluded-dirs-sync.test.mjs fails when the two differ.

const DEFAULT_SEARCH_EXCLUDED_DIRS: readonly [
  'node_modules',
  'bower_components',
  '.git',
  '.svn',
  '.hg',
  'CVS',
  'dist',
  '.next',
  '.vite',
  'molecule',
]

MAX_OUTPUT_LINES

Live output lines retained — enough to read, bounded so a chatty run cannot grow forever.

const MAX_OUTPUT_LINES: 400

EMPTY_RUN_STATE

A run that has not started.

const EMPTY_RUN_STATE: TestsRunState

MAX_FIX_OUTPUT_CHARS

Output kept per failure when several are batched into one fix message.

const MAX_FIX_OUTPUT_CHARS: 2000

MAX_FIX_MESSAGE_OUTPUT_CHARS

Total output kept across a batched fix message, so one click cannot send a novel.

const MAX_FIX_MESSAGE_OUTPUT_CHARS: 12000

MAX_AVATAR_SRC_LENGTH

Maximum avatar source length we will render inline (~256 KB data-URI).

const MAX_AVATAR_SRC_LENGTH: 262144

MIN_PANEL_PERCENT

Smallest a panel may shrink to, as a percentage of the container.

const MIN_PANEL_PERCENT: 10

MAX_PANEL_PERCENT

Largest a panel may grow to, as a percentage of the container.

const MAX_PANEL_PERCENT: 80

IS_MAC

Whether the platform is macOS or iOS, where mod means Cmd instead of Ctrl.

const IS_MAC: boolean

SETTINGS

Every user-controllable setting, in display order. The authoritative list — the /settings view (via buildSettingsList) and the system prompt both read from it, so they cannot drift. The default model and the per-mode planModel / executeModel rows are kept distinct (rather than collapsed into one "Model" row); effort, autoCommit, and hooks are each listed alongside (or in hooks' case, instead of) the command the panel references — so a user's actual configuration is never understated and the panel never shows a command for a setting it hides.

const SETTINGS: readonly SettingMeta[]

NARROW_VIEWPORT_QUERY

The phone-width media query — matches viewports below 768px, mirroring the host workspace's single-pane mobile breakpoint.

const NARROW_VIEWPORT_QUERY: '(max-width: 767px)'

COARSE_POINTER_QUERY

The touch-first media query — matches when the PRIMARY pointer is coarse (finger), i.e. phones/tablets, regardless of viewport width.

const COARSE_POINTER_QUERY: '(pointer: coarse)'

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-ai-chat ^1.8.0
  • @molecule/app-ai-models ^1.4.0
  • @molecule/app-code-editor ^1.0.1
  • @molecule/app-i18n ^1.2.0
  • @molecule/app-icons ^1.0.1
  • @molecule/app-ide ^1.0.1
  • @molecule/app-live-preview ^1.0.1
  • @molecule/app-storage ^1.1.1

Runtime Dependencies

  • @molecule/app-ai-chat

  • @molecule/app-ai-models

  • @molecule/app-code-editor

  • @molecule/app-i18n

  • @molecule/app-icons

  • @molecule/app-ide

  • @molecule/app-live-preview

  • @molecule/app-storage

  • The ./panels entry holds the further helper modules the panel views use directly; it is not re-exported by the framework packages.

  • registerCustomEventCard() holds module state: every importer reaches THIS package's one copy of the registry, never a second one.