From 6297403a41c862b25d8c7baffce928bbbd4d8e82 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:32:43 -0500 Subject: [PATCH] docs: document the OpenCode client migration surfaces (OM-179) Adds JSDoc comments to the functions this branch adds or changes, so the touched-code docstring coverage clears the review threshold. Comments only; no code, formatting or import changes. --- backend/src/routes/opencode-config.ts | 15 +++ backend/src/routes/opencode-proxy.ts | 11 +++ backend/src/routes/opencode-server-proxy.ts | 5 + backend/src/routes/repos.ts | 5 + backend/src/services/assistant-mode.ts | 51 ++++++++++ backend/src/services/opencode-config-apply.ts | 10 ++ .../src/services/opencode-config-effective.ts | 5 + backend/src/services/opencode-config-file.ts | 71 ++++++++++++++ .../src/services/opencode-config-redact.ts | 8 ++ .../services/opencode-config-references.ts | 23 +++++ .../src/services/opencode-event-routing.ts | 5 + .../services/opencode-event-subscription.ts | 12 +++ .../src/services/opencode-single-server.ts | 4 + backend/src/services/opencode/client.ts | 4 + backend/src/services/remote-server-events.ts | 52 ++++++++++ backend/src/services/sse-aggregator.ts | 97 +++++++++++++++++++ frontend/src/api/opencode.ts | 8 ++ frontend/src/api/providers.ts | 4 + .../session/PermissionRequestDialog.tsx | 10 ++ .../src/components/settings/AgentDialog.tsx | 31 ++++++ .../src/components/settings/AgentsEditor.tsx | 4 + .../src/components/settings/CommandDialog.tsx | 15 +++ .../components/settings/CommandsEditor.tsx | 4 + .../src/components/settings/McpManager.tsx | 4 + .../settings/OpenCodeConfigEditor.tsx | 17 ++++ .../settings/OpenCodeConfigManager.tsx | 28 ++++++ .../settings/OpenCodeModelDialog.tsx | 61 ++++++++++++ .../settings/OpenCodeModelsEditor.tsx | 18 ++++ frontend/src/contexts/EventContext.tsx | 15 +++ frontend/src/hooks/useFileSearch.ts | 5 + frontend/src/hooks/useOpenCode.ts | 5 + frontend/src/hooks/useSSE.ts | 13 +++ frontend/src/hooks/useSessionAgent.ts | 8 ++ frontend/src/hooks/useSessionTranscript.ts | 10 ++ frontend/src/lib/modelSections.ts | 5 + .../openCodeEventStream.ts | 23 +++++ frontend/src/pages/SessionDetail.tsx | 5 + frontend/src/stores/sessionStatusStore.ts | 4 + ocm-cli/src/link.ts | 4 + shared/src/opencode/config-validation.ts | 8 ++ shared/src/opencode/mcp.ts | 4 + 41 files changed, 691 insertions(+) diff --git a/backend/src/routes/opencode-config.ts b/backend/src/routes/opencode-config.ts index a35564b4..0ad8be13 100644 --- a/backend/src/routes/opencode-config.ts +++ b/backend/src/routes/opencode-config.ts @@ -57,6 +57,10 @@ function mergeMcpServerStatus(views: McpServerView[], status: McpStatusMap) { }) } +/** + * Maps a config read failure to a JSON error response: 503 when the OpenCode server is unreachable, + * 502 for other client errors, and 500 otherwise, using `message` as the client-facing text. + */ function toClientReadErrorResponse(c: Context, error: unknown, message: string) { if (error instanceof ClientError) { if (error.reason === 'Transport') { @@ -67,6 +71,12 @@ function toClientReadErrorResponse(c: Context, error: unknown, message: string) return c.json({ error: message }, 500) } +/** + * Serves the OpenCode config read routes (`/`, `/effective`, `/managed`, `/mcp`) and the `PUT` and + * `PATCH` write routes. Reads and writes take the shared config file lock, `redactSecrets` masks + * secret values in every response, and a `PATCH` that names config entities is rejected with 409 + * while OpenCode has not yet loaded the saved configuration. + */ export function createOpenCodeConfigRoutes( settingsService: SettingsService, openCodeClient: OpenCodeClient, @@ -195,6 +205,11 @@ export function createOpenCodeConfigRoutes( return app } +/** + * Applies a validated config update and maps the outcome to a JSON response, redacting secrets when + * `redactSecrets` is set and translating conflict, invalid-source, shadowed-removal, redacted-value + * and schema-validation failures into their matching status codes. + */ async function applyUpdate( c: Context, input: Parameters[0], diff --git a/backend/src/routes/opencode-proxy.ts b/backend/src/routes/opencode-proxy.ts index 02dd2c00..747cff52 100644 --- a/backend/src/routes/opencode-proxy.ts +++ b/backend/src/routes/opencode-proxy.ts @@ -113,6 +113,12 @@ function rewriteRepoLocationBody(bodyText: string, resolveDirectory: RepoDirecto return JSON.stringify(parsed) } +/** + * Serves `/repos/:repoId/*` and `/*` by forwarding to the managed OpenCode server, rewriting repo + * directory references in the path, query and JSON body. Every request needs the internal token + * except a ticketed persistent PTY WebSocket connect, which is origin-checked and bridged to the + * upstream socket. + */ export function createOpenCodeProxyRoutes(db: Database, settingsService: SettingsService, upgradeWebSocket: UpgradeWebSocket) { const app = new Hono() const requireInternalToken = createInternalTokenMiddleware(db) @@ -145,6 +151,11 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting return (await upgrade(c, async () => {})) ?? c.body(null) } + /** + * Forwards the current request to the managed OpenCode server with basic auth and a default + * directory, letting the optional rewrites adjust path, query and JSON body first. Returns 503 + * before lifecycle initialization, 501 for non-PTY upgrades and 502 when the upstream call fails. + */ async function forwardToOpenCode( c: Context, pathSuffix: string, diff --git a/backend/src/routes/opencode-server-proxy.ts b/backend/src/routes/opencode-server-proxy.ts index 67a9d124..e920bbba 100644 --- a/backend/src/routes/opencode-server-proxy.ts +++ b/backend/src/routes/opencode-server-proxy.ts @@ -80,6 +80,11 @@ function isWithinUpstreamApiPath(basePath: string, pathname: string): boolean { return pathname.startsWith(`${basePath}/api/`) } +/** + * Serves `/:serverId/*` behind `requireAuth`, proxying each request to the registry-resolved remote + * OpenCode server while keeping the normalized upstream pathname inside that connection's own `/api/` + * space. Maps an upstream header timeout to 504 and an unreachable server to 502. + */ export function createOpenCodeServerProxyRoutes( registry: OpenCodeServerRegistry, requireAuth: MiddlewareHandler, diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 1399aeac..5bab0b03 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -41,6 +41,11 @@ function withRepoSettings(database: Database, repo: Repo): Repo { } } +/** + * Mounts the repo git, terminal, project-config, schedule and secret/variable sub-routers, and serves + * repo CRUD with discovery, ordering, access, credential, identity, workspace, pull/branch, download + * and assistant-mode routes. Handler failures are mapped to their status codes with a JSON message. + */ export function createRepoRoutes( database: Database, gitAuthService: GitAuthService, diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index e456acb7..03d6bee8 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -1134,6 +1134,11 @@ Fork a session, optionally before a specific message. Omit \`beforeMessageId\` t ` } +/** + * Builds the canonical Assistant `opencode.json` document: the assistant agent as default agent, its + * allowed permissions, and a `primary` agent entry. The result is schema-validated, and an invalid + * result throws rather than returning a config OpenCode would reject. + */ export function buildAssistantOpenCodeConfig(): OpenCodeConfigInfo { const permission = buildAssistantAgentPermission() const config: OpenCodeConfigInfo = { @@ -1158,6 +1163,12 @@ export function buildAssistantOpenCodeConfig(): OpenCodeConfigInfo { return config } +/** + * Creates or repairs the Assistant workspace for `repo`: writes AGENTS.md, the assistant OpenCode + * config, the bundled skills and the default agent file, updating the config under a file lock and + * preserving customized content unless the matching `overwrite*` option is set. Returns the + * resulting status, including warnings for instruction updates it declined to apply. + */ export async function ensureAssistantMode( repo: Repo, options?: AssistantModeInitRequest, @@ -1352,6 +1363,10 @@ export async function ensureAssistantMode( } } +/** + * Parses JSONC config text into a config object, returning `undefined` when the text is malformed or + * its root is not an object. + */ function parseAssistantOpenCodeConfig(rawContent: string): Record | undefined { try { const parsed = parseJsonc(rawContent) @@ -1377,12 +1392,21 @@ function resolveV1EntityPath(v2Path: readonly string[]): string[] { const ASSISTANT_V1_AGENT_PATH = resolveV1EntityPath(['agents']) const ASSISTANT_V1_PERMISSION_PATH = resolveV1EntityPath(['permissions']) +/** + * Reports whether the config still carries v1 keys, which mark a file that has not been converted to + * the v2 shape yet. + */ function hasAssistantV1OpenCodeConfig(config: Record): boolean { if (readConfigValueAtPath(config, ASSISTANT_V1_PERMISSION_PATH) !== undefined) return true const v1Agents = readConfigValueAtPath(config, ASSISTANT_V1_AGENT_PATH) return isRecord(v1Agents) && isRecord(v1Agents[ASSISTANT_DEFAULT_AGENT_NAME]) } +/** + * Reports whether an existing Assistant config lacks what `ensureAssistantMode` requires: the + * assistant as default agent, an enabled agent entry with a valid mode, and no generated persona left + * inline. + */ function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean { if (config.default_agent !== ASSISTANT_DEFAULT_AGENT_NAME) return true const agents = config.agents @@ -1399,6 +1423,7 @@ function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigI return normalizeAssistantAgent(config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]) !== undefined } +/** Returns the agent's `mode` when it is `primary` or `all`, otherwise falling back to `primary`. */ function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' { const mode = (agent as { mode?: unknown } | undefined)?.mode return mode === 'primary' || mode === 'all' ? mode : 'primary' @@ -1412,6 +1437,10 @@ function normalizeAssistantAgent(agent: unknown): OpenCodeAgentConfig | undefine return { mode: resolveValidAssistantMode(agent) } } +/** + * Rewrites the assistant agent entry to a mode-only value, dropping a generated `system` prompt so it + * comes from the agent markdown file rather than opaque config text. + */ function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCodeConfigInfo { const existingAssistantAgent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME] @@ -1426,6 +1455,10 @@ function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCo } } +/** + * Merges an existing Assistant config over a freshly generated one, keeping user settings and extra + * agents while forcing the assistant as default agent and re-enabling its entry. + */ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeConfigInfo { const generated = buildAssistantOpenCodeConfig() const existingAssistantAgent = existing?.agents?.[ASSISTANT_DEFAULT_AGENT_NAME] @@ -1448,6 +1481,11 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo } } +/** + * Lists the v1 paths to delete after a conversion: the assistant agent entry, widened to the whole v1 + * `agents` container when that container held nothing else, plus `permissions` when a v2 counterpart + * has just been written. + */ function buildAssistantV1ConfigRemovalPaths( config: Record, convertedPermissions: unknown, @@ -1466,6 +1504,10 @@ function buildAssistantV1ConfigRemovalPaths( return paths } +/** + * Picks the assistant agent written back to the converted file, preferring OpenCode's converted entry, + * then the agent passed in, then a mode derived from the v1 definition. + */ function resolveConvertedAssistantAgent( agent: OpenCodeAgentConfig | undefined, v1Agent: unknown, @@ -1473,6 +1515,10 @@ function resolveConvertedAssistantAgent( return normalizeAssistantAgent(agent) ?? agent ?? { mode: resolveValidAssistantMode(v1Agent) } } +/** + * Puts the raw `{env:…}` and `{file:…}` references from the original file back into the converted + * assistant agent, returning the agent unchanged when no restored entry can be read. + */ function restoreAssistantAgentReferences( agent: OpenCodeAgentConfig, resolved: OpenCodeConfigInfo, @@ -1503,6 +1549,11 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom } } +/** + * Converts one Assistant `opencode.json` in place when it still holds v1 keys, writing OpenCode's + * converted agent and permissions while preserving comments. Returns `false` without writing when the + * file is absent, already v2, unreadable by OpenCode, or the rewritten text fails validation. + */ async function convertAssistantOpenCodeConfigFile( api: OpenCodeApi, assistantDir: string, diff --git a/backend/src/services/opencode-config-apply.ts b/backend/src/services/opencode-config-apply.ts index c2f479f6..2691e275 100644 --- a/backend/src/services/opencode-config-apply.ts +++ b/backend/src/services/opencode-config-apply.ts @@ -101,6 +101,11 @@ function requiresOpenCodeReload(previous: OpenCodeConfigFile | null, next: OpenC return listChangedTopLevelKeys(previous?.content ?? {}, next.content).length > 0 } +/** + * Replaces substituted values in a merge patch with the `{env:…}` or `{file:…}` references held by + * the raw config, reading the resolved config from the OpenCode server. Returns the patch unchanged + * when it does not name any config entity. + */ async function keepOpenCodeConfigReferences( patch: Record, snapshot: OpenCodeConfigSnapshot, @@ -111,6 +116,11 @@ async function keepOpenCodeConfigReferences( return restoreOpenCodeConfigReferences(patch, resolved as Record, snapshot.content) } +/** + * Applies config content or a merge patch under the shared config file lock, saving the previous + * valid config as last-known-good and restoring it if that save fails. OpenCode is reloaded only when + * top-level keys changed, and a failed reload is reported as `restart_pending`. + */ export async function applyOpenCodeConfigUpdate( input: ApplyOpenCodeConfigOptions, ): Promise { diff --git a/backend/src/services/opencode-config-effective.ts b/backend/src/services/opencode-config-effective.ts index 5b9427cd..161d4479 100644 --- a/backend/src/services/opencode-config-effective.ts +++ b/backend/src/services/opencode-config-effective.ts @@ -30,6 +30,11 @@ export async function readOpenCodeConfigDocuments( return infoByPath } +/** + * Merges the OpenCode config documents the server reports for the workspace, keeping only the given + * managed sources. Documents OpenCode did not load are skipped, so the result reflects only values + * the server actually resolved. + */ export async function readManagedOpenCodeConfig( api: OpenCodeApi, sources: ReadonlyArray, diff --git a/backend/src/services/opencode-config-file.ts b/backend/src/services/opencode-config-file.ts index ec3b3a9a..5bd4482d 100644 --- a/backend/src/services/opencode-config-file.ts +++ b/backend/src/services/opencode-config-file.ts @@ -212,6 +212,11 @@ interface ReadOpenCodeConfigPathOptions { nullAncestorCountsAsFound?: boolean } +/** + * Resolves a JSON path against parsed config content, walking objects by key and arrays by index. + * Returns whether the path exists plus its value; an absent path yields `found: false`, and + * `nullAncestorCountsAsFound` treats a null intermediate value as terminal instead of missing. + */ function readOpenCodeConfigPath( content: Record, jsonPath: JSONPath, @@ -283,6 +288,11 @@ interface MergeOpenCodeConfigValuesOptions { deleteNullValues?: boolean } +/** + * Deep-merges `source` into `target` and returns a new object, recursing into plain-object values. + * With `deleteNullValues`, a null source value removes the key and nested nulls are stripped from + * replaced values. + */ export function mergeOpenCodeConfigValues( target: Record, source: Record, @@ -316,11 +326,19 @@ export function withOpenCodeConfigLock(fn: () => Promise): Promise { return withFileLock(getOpenCodeConfigDirectory(), fn) } +/** + * Validates parsed config content against the OpenCode config schema and throws + * OpenCodeConfigValidationError carrying the reported issues when it fails. + */ function assertValidOpenCodeConfig(value: unknown): void { const result = validateOpenCodeConfig(value) if (!result.success) throw new OpenCodeConfigValidationError(result.issues) } +/** + * Parses JSONC config text and validates it against the OpenCode config schema, returning the parsed + * object (empty when parsing fails) with `isValid` and any validation issues instead of throwing. + */ export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigParseResult { let parsed: unknown try { @@ -418,6 +436,11 @@ export async function readOpenCodeConfigSnapshot(): Promise source.validationIssues ?? []) return { @@ -458,6 +481,11 @@ export async function writeOpenCodeConfigFile( return toOpenCodeConfigFile(await readOpenCodeConfigSnapshot()) } +/** + * Computes the JSON-path operations that turn `current` into `next`, recursing into plain objects on + * both sides. Merge mode treats `null` as a deletion and strips null members from merged values, + * replace mode additionally removes keys absent from `next`. + */ function collectOpenCodeConfigPathOperations( next: Record, current: Record, @@ -495,6 +523,11 @@ function collectOpenCodeConfigPathOperations( return operations } +/** + * Returns the v1 entity paths a v2 merge patch removes, since OpenCode still reads v1 containers. + * Container-wide removals carry no `container`, while named removals record their v1 container so + * it can be pruned once left empty. + */ function collectOpenCodeConfigV1EntityRemovals( patch: Record, ): OpenCodeConfigV1EntityRemoval[] { @@ -515,6 +548,10 @@ function collectOpenCodeConfigV1EntityRemovals( return removals } +/** + * Returns the offset of the first comma in `rawContent` between `start` and `end`, skipping line + * and block comments, or -1 when none exists or a comment runs past `end`. + */ function findOpenCodeConfigSeparatorComma(rawContent: string, start: number, end: number): number { let index = start while (index < end) { @@ -536,6 +573,10 @@ function findOpenCodeConfigSeparatorComma(rawContent: string, start: number, end return -1 } +/** + * Returns the offset just past the line break that follows `offset`, ignoring intervening spaces + * and tabs, or null when the line has more content after them. + */ function findOpenCodeConfigLineEnd(rawContent: string, offset: number): number | null { let index = offset while (index < rawContent.length && (rawContent[index] === ' ' || rawContent[index] === '\t')) { @@ -546,6 +587,12 @@ function findOpenCodeConfigLineEnd(rawContent: string, offset: number): number | return null } +/** + * Builds JSONC text edits that delete the property at `jsonPath` while leaving surrounding comments + * intact. Returns null when the node, its container, or a required separator comma cannot be + * located; a comment between the property and the next member makes the property and the comma be + * removed by separate edits so the comment survives. + */ function buildOpenCodeConfigCommentPreservingRemovalEdits( rawContent: string, jsonPath: JSONPath, @@ -603,6 +650,10 @@ export function removeOpenCodeConfigProperty(rawContent: string, jsonPath: JSONP return applyEdits(rawContent, edits) } +/** + * Returns the distinct containers named by `removals` that remain empty objects in the updated raw + * config text, so they can be pruned. Yields nothing when the parsed root is not an object. + */ function collectEmptyOpenCodeConfigContainers( rawContent: string, removals: OpenCodeConfigV1EntityRemoval[], @@ -642,6 +693,10 @@ export function applyOpenCodeConfigEdits( return text } +/** + * Throws OpenCodeConfigShadowedRemovalError when a planned removal targets a path the target source + * does not define but another config source does, listing the shadowed paths and their sources. + */ function assertNoShadowedOpenCodeConfigRemovals( operations: OpenCodeConfigPathOperation[], targetSource: OpenCodeConfigSourceFile | undefined, @@ -668,6 +723,11 @@ function assertNoShadowedOpenCodeConfigRemovals( } } +/** + * Writes new config text, or applies object content/patch, to the requested source or the preferred + * writable one. Enforces `expectedRevision`, rejects redacted values and invalid sibling sources, + * preserves JSONC comments and formatting, and returns the refreshed config snapshot. + */ export async function updateOpenCodeConfigFile( content: Record | string, options: UpdateOpenCodeConfigOptions = {}, @@ -874,6 +934,12 @@ async function applyOpenCodeConfigSourceFileStates( } } +/** + * Restores the config source files from a serialized snapshot: sources present in the snapshot are + * written, sources absent from it but currently on disk are removed, and the legacy config.json source + * is folded afterwards. All writes roll back together on failure, and the refreshed file view is + * returned, or null when no sources remain. + */ export async function restoreOpenCodeConfigSnapshot(snapshot: string): Promise { const desired = parseOpenCodeConfigSnapshot(snapshot) const current = await readOpenCodeConfigSnapshot() @@ -906,6 +972,11 @@ async function archiveLegacyConfigJsonSource(rawContent: string): Promise { const legacyPath = getOpenCodeConfigSourcePath(LEGACY_OPENCODE_CONFIG_SOURCE_NAME) diff --git a/backend/src/services/opencode-config-redact.ts b/backend/src/services/opencode-config-redact.ts index bc52f569..9f1eae2e 100644 --- a/backend/src/services/opencode-config-redact.ts +++ b/backend/src/services/opencode-config-redact.ts @@ -53,6 +53,10 @@ function isSecretKey(key: string): boolean { return SECRET_KEYS.has(normalizeSecretKey(key)) } +/** + * Reports whether a config path points at a map of user-chosen names (`providers`, `agents`, + * `commands`, `mcp.servers`), so its keys are treated as names rather than secret keys. + */ function keysAreNames(path: string[]): boolean { const [head] = path if (head === 'providers') { @@ -81,6 +85,10 @@ function redactOpaqueValue(value: unknown, path: string[], redactedPaths: string ) } +/** + * Recursively copies a config value with secret-named strings and the contents of `headers` and + * `environment` replaced by the redaction placeholder, appending each redacted path to `redactedPaths`. + */ function redactValue(value: unknown, path: string[], redactedPaths: string[]): unknown { if (Array.isArray(value)) { return value.map((item, index) => redactValue(item, [...path, String(index)], redactedPaths)) diff --git a/backend/src/services/opencode-config-references.ts b/backend/src/services/opencode-config-references.ts index 4efe006f..6b80a8f5 100644 --- a/backend/src/services/opencode-config-references.ts +++ b/backend/src/services/opencode-config-references.ts @@ -44,10 +44,15 @@ export function readConfigValueAtPath(value: unknown, path: readonly string[]): return current } +/** Whether `path` begins with every segment of `prefix`, used to match field-alias prefixes. */ function startsWithPath(path: readonly string[], prefix: readonly string[]): boolean { return prefix.length <= path.length && prefix.every((segment, index) => path[index] === segment) } +/** + * Finds the raw `{env:…}` or `{file:…}` reference stored for `path` in any candidate entity, + * also checking each alias-mapped path. Returns undefined when no candidate holds a reference there. + */ function readRawReference(candidates: readonly RawEntityCandidate[], path: readonly string[]): string | undefined { for (const candidate of candidates) { const paths = [ @@ -64,6 +69,11 @@ function readRawReference(candidates: readonly RawEntityCandidate[], path: reado return undefined } +/** + * Walks a patch value and swaps each string that still equals its resolved counterpart for the raw + * config reference at the same path. Returns a new value; edited strings and strings without a + * stored reference are kept as given. + */ function restoreEntityReferences( next: unknown, path: readonly string[], @@ -85,6 +95,10 @@ function restoreEntityReferences( return next } +/** + * Returns the single entity name the patch removes but the resolved container still contains, or + * undefined when the patch removes zero or several names. + */ function findRenameSource( patchContainer: Record, resolvedContainer: Record, @@ -95,6 +109,11 @@ function findRenameSource( return removed.length === 1 ? removed[0] : undefined } +/** + * Restores references for every named entity in a patch container, resolving the source entity from + * the resolved container or from a single rename within the same patch. Returns the patch container + * unchanged when the resolved container is not an object. + */ function restoreContainerReferences( mapping: OpenCodeConfigV1EntityPath, patchContainer: Record, @@ -126,6 +145,10 @@ function restoreContainerReferences( ) } +/** + * Returns a copy of `target` with `value` written at `path`, creating intermediate plain objects + * where they are missing. An empty path returns `target` itself. + */ function setValueAtPath(target: Record, path: readonly string[], value: unknown): Record { const [head, ...rest] = path if (head === undefined) return target diff --git a/backend/src/services/opencode-event-routing.ts b/backend/src/services/opencode-event-routing.ts index 7ad667e4..a247f5f2 100644 --- a/backend/src/services/opencode-event-routing.ts +++ b/backend/src/services/opencode-event-routing.ts @@ -105,6 +105,11 @@ export function applySessionActivity(busySessions: Set, event: V2Event): } } +/** + * Returns a builder that stamps each replayed permission, form or session-status event with the + * current time and a monotonically increasing `${idPrefix}${count}` id, so replayed events stay + * ordered and distinct from live ones. + */ export function createReplayEventBuilder(idPrefix: string): ReplayEventBuilder { let count = 0 return (...args) => { diff --git a/backend/src/services/opencode-event-subscription.ts b/backend/src/services/opencode-event-subscription.ts index df77d060..76dc73d9 100644 --- a/backend/src/services/opencode-event-subscription.ts +++ b/backend/src/services/opencode-event-subscription.ts @@ -52,6 +52,9 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption let delayTimer: ReturnType | null = null let resolveDelay: (() => void) | null = null + /** + * Clears the watchdog and aborts the in-flight attempt so its stream iterator ends. + */ const stopAttempt = (): void => { const attempt = currentAttempt currentAttempt = null @@ -63,6 +66,10 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption attempt.controller.abort() } + /** + * Cancels a pending reconnect wait and resolves it at once, letting the loop observe that it has + * been closed or superseded. + */ const stopDelay = (): void => { if (delayTimer) { clearTimeout(delayTimer) @@ -82,6 +89,11 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption }, delayMs) }) + /** + * Runs the reconnect loop for one loop token, opening a fresh attempt per iteration, aborting it + * when the stall watchdog fires, and waiting a doubling backoff before retrying. Returns once the + * subscription is closed or `token` is superseded by a newer loop. + */ const run = async (token: number): Promise => { while (!closed && token === loopToken) { const attempt: SubscriptionAttempt = { controller: new AbortController(), watchdog: null } diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index d227dbe7..eb69e81a 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -1037,6 +1037,10 @@ class OpenCodeServerManager { return this.sandboxEnforced } + /** + * Sets the lifecycle gate and, when it transitions from closed to open, notifies the registered + * listeners that the proxy is now serving requests. Listener failures are logged, not propagated. + */ setLifecycleInitialized(initialized: boolean): void { const opened = initialized && !this.lifecycleInitialized this.lifecycleInitialized = initialized diff --git a/backend/src/services/opencode/client.ts b/backend/src/services/opencode/client.ts index 3ff04c47..710dab48 100644 --- a/backend/src/services/opencode/client.ts +++ b/backend/src/services/opencode/client.ts @@ -64,6 +64,10 @@ export class FetchOpenCodeClient implements OpenCodeClient { return this.fetchFn(input, { ...init, headers }) } + /** + * Proxies a raw request to the OpenCode server, dropping the `/api/opencode` prefix and applying the + * directory header and basic auth. Upstream failures become a `502` JSON response instead of a throw. + */ async forwardRaw(request: Request): Promise { const url = new URL(request.url) const path = url.pathname.replace(/^\/api\/opencode/, '') + url.search diff --git a/backend/src/services/remote-server-events.ts b/backend/src/services/remote-server-events.ts index bfc500e5..08bbdbe5 100644 --- a/backend/src/services/remote-server-events.ts +++ b/backend/src/services/remote-server-events.ts @@ -155,6 +155,10 @@ export class RemoteServerEventHub { return false } + /** + * Delivers already-built replay events to one client through the aggregator, which drops them unless + * the client still subscribes to that server and directory. + */ private emitReplayEventsToClient( clientId: string, serverId: string, @@ -181,6 +185,11 @@ export class RemoteServerEventHub { } } + /** + * Replaces the server's event subscription with a fresh one, recording a stream error instead when the + * registry cannot provide a connection. Does nothing until the hub has started, so stale callbacks from + * the prior subscription are ignored rather than applied. + */ private connectServer(serverId: string): void { if (!this.started) return this.closeStream(serverId) @@ -210,6 +219,10 @@ export class RemoteServerEventHub { logger.info(`Remote event stream connecting: ${serverId}`) } + /** + * Marks the server's stream connected, announces it to the aggregator, and starts version probing + * and session status replay. A callback from a superseded subscription is ignored. + */ private handleOpen(serverId: string, subscription: OpenCodeEventSubscription): void { const stream = this.streams.get(serverId) if (!stream || stream.subscription !== subscription) return @@ -223,6 +236,10 @@ export class RemoteServerEventHub { void this.replaySessionStatuses(serverId, subscription) } + /** + * Records a disconnect on the server's stream and clears its connected flag, leaving the + * subscription itself to keep reconnecting. + */ private handleStreamError(serverId: string, error: unknown): void { const stream = this.streams.get(serverId) if (!stream) return @@ -232,6 +249,10 @@ export class RemoteServerEventHub { logger.warn(`Remote event stream error for ${serverId}: ${stream.error}`) } + /** + * Routes one upstream event to the aggregator while maintaining the hub's per-stream bookkeeping: + * busy-session activity, subagent session ids, and the directory the event resolves to. + */ private handleMessage(serverId: string, event: V2Event): void { const stream = this.streams.get(serverId) if (!stream) return @@ -249,6 +270,11 @@ export class RemoteServerEventHub { this.aggregator.deliverRemoteEnvelope(serverId, resolvedDirectory ?? null, event) } + /** + * Keeps streams aligned with the server registry: deleted, unreadable, or disabled servers have their + * stream forgotten, while added and updated servers get their cached version state cleared and are + * reconnected. + */ private handleRegistryChange(change: OpenCodeServerChange): void { if (!this.started) return @@ -280,6 +306,10 @@ export class RemoteServerEventHub { this.connectServer(change.serverId) } + /** + * Reports whether the subscription still owns the server's live stream, so async work started under + * it does not act on a stream that has since been replaced or disconnected. + */ private isStreamCurrent( serverId: string, stream: RemoteServerStream, @@ -288,6 +318,11 @@ export class RemoteServerEventHub { return this.streams.get(serverId) === stream && stream.subscription === subscription && stream.connected } + /** + * Re-emits idle and busy status events for the server's active sessions after a reconnect, so + * clients that missed updates while disconnected resync. Stops quietly at any await once the stream + * is no longer current. + */ private async replaySessionStatuses(serverId: string, subscription: OpenCodeEventSubscription): Promise { const stream = this.streams.get(serverId) if (!stream || !this.isStreamCurrent(serverId, stream, subscription)) return @@ -336,6 +371,11 @@ export class RemoteServerEventHub { } } + /** + * Looks up the working directory of active sessions the stream has not mapped yet, caching each result + * in `sessionDirectories`. Sessions are fetched concurrently and left unresolved when their lookup + * fails, so replay proceeds with whatever directories are known. + */ private async resolveActiveSessionDirectories( api: OpenCodeApi, serverId: string, @@ -356,6 +396,11 @@ export class RemoteServerEventHub { })) } + /** + * Probes the server's OpenCode version, skipping when a probe is already pending or the version is + * known. Results are applied only when the probe token still matches the current stream, and a failed + * probe reopens the request flag so a later reconnect can retry it. + */ private async refreshVersion(serverId: string): Promise { const stream = this.streams.get(serverId) if (!stream || stream.versionRequested) return @@ -382,6 +427,10 @@ export class RemoteServerEventHub { current.versionRequested = false } + /** + * Returns the server's stream bookkeeping record, creating an empty one on first use so callers can + * record state before a subscription exists. + */ private ensureStream(serverId: string): RemoteServerStream { const existing = this.streams.get(serverId) if (existing) return existing @@ -407,6 +456,9 @@ export class RemoteServerEventHub { stream.error = error } + /** + * Closes the stream's subscription and clears the handle, keeping the stream entry itself. + */ private closeSubscription(stream: RemoteServerStream): void { if (!stream.subscription) return stream.subscription.close() diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts index a6630878..d2196471 100644 --- a/backend/src/services/sse-aggregator.ts +++ b/backend/src/services/sse-aggregator.ts @@ -99,12 +99,20 @@ class SSEAggregator { this.broadcastResync() } + /** + * Forces the upstream event subscription to reconnect, used after credentials change. No-op while the + * aggregator is not started. + */ reconnect(): void { if (!this.started) return logger.info('SSE forcing upstream reconnect (auth changed)') this.subscription?.reconnect() } + /** + * Returns the process-wide aggregator, creating it on first call. All events and client registrations + * flow through this single instance. + */ static getInstance(): SSEAggregator { if (!SSEAggregator.instance) { SSEAggregator.instance = new SSEAggregator() @@ -112,6 +120,10 @@ class SSEAggregator { return SSEAggregator.instance } + /** + * Subscribes to local OpenCode events once per process, wiring the open, event, and disconnect handlers. + * Without a registered OpenCode client it logs a warning and stays stopped. + */ start(): void { if (this.started) return const client = this.openCodeClient @@ -253,6 +265,10 @@ class SSEAggregator { } } + /** + * Runs the remote replay handler for one server directory, catching and logging failures so that a + * directory that cannot replay does not reject the caller. + */ private async replayRemoteDirectory( clientId: string, serverId: string, @@ -266,6 +282,10 @@ class SSEAggregator { } } + /** + * Replays pending permission and form events for each of the client's directories, settling every + * directory independently so one failed lookup does not block the rest. + */ private async replayPendingActionsForClient(clientId: string, directories: string[]): Promise { const client = this.openCodeClient if (!client) return @@ -292,6 +312,10 @@ class SSEAggregator { this.emitReplayEventsToClient(clientId, directory, events.forms) } + /** + * Writes replayed events to a client only while it is still registered and subscribed to the directory; + * delivery stops at the first write error, leaving the remaining events unsent. + */ private emitReplayEventsToClient(clientId: string, directory: string, events: V2Event[]): void { if (events.length === 0) return @@ -310,6 +334,11 @@ class SSEAggregator { logger.info(`replay: sent ${events.length} pending action(s) for ${directory} to client ${clientId}`) } + /** + * Re-emits idle and busy status events for sessions the aggregator already tracks, so clients recover + * transitions missed while disconnected. Busy sessions with an unknown directory are resolved through + * the API and skipped when that lookup fails. + */ private async replaySessionStatusesForTrackedDirectories(): Promise { const client = this.openCodeClient if (!client) return @@ -348,6 +377,10 @@ class SSEAggregator { } } + /** + * Collects every session currently active or scheduled, keyed by session id, and records the owning + * directory for each so a later replay can address it. + */ private getTrackedSessions(): Map { const tracked = new Map() this.activeSessions.forEach((sessionIDs, directory) => { @@ -360,6 +393,10 @@ class SSEAggregator { return tracked } + /** + * Resolves a session's directory through the API and caches it for later event routing, returning + * `null` and logging a warning when the lookup fails. + */ private async resolveSessionDirectory(client: Pick, sessionID: string): Promise { try { const session = await client.api.session.get({ sessionID }) @@ -371,6 +408,11 @@ class SSEAggregator { } } + /** + * Handles a (re)connected upstream stream: broadcasts a resync, or defers it as pending while the resync + * gate is closed, and replays tracked session statuses only on a reconnection rather than the first + * connect. + */ private handleUpstreamOpen(wasConnectedBefore: boolean): void { logger.info('SSE global stream connected') this.upstreamConnected = true @@ -386,6 +428,10 @@ class SSEAggregator { } } + /** + * Announces a fresh upstream connection to the connected-listeners and to clients subscribed to the + * local OpenCode server, isolating any listener that throws. + */ private notifyUpstreamConnected(): void { this.upstreamConnectedListeners.forEach(listener => { try { listener() } catch { /* ignore listener errors */ } @@ -417,12 +463,20 @@ class SSEAggregator { return () => { this.serverConnectedListeners.delete(listener) } } + /** + * Fans an event out to every server-event listener, isolating each listener so a throwing one cannot + * block the others or the dispatch caller. + */ notifyServerEvent(serverId: string, directory: string | null, event: SSEEvent): void { this.serverEventListeners.forEach(listener => { try { listener(serverId, directory, event) } catch { /* ignore listener errors */ } }) } + /** + * Notifies server-connected listeners that a server's stream is available, swallowing per-listener + * errors so one failure does not interrupt the notification of the rest. + */ notifyServerConnected(serverId: string): void { this.serverConnectedListeners.forEach(listener => { try { listener(serverId) } catch { /* ignore listener errors */ } @@ -433,6 +487,11 @@ class SSEAggregator { this.remoteSubagentResolver = resolver } + /** + * Dispatches one local upstream event: directory-scoped events go to that directory's subscribers, + * catalog updates go to every client, and events without a resolvable directory go to all listeners + * unscoped. + */ private handleUpstreamEvent(event: V2Event): void { const { directory, resolvedDirectory } = routeOpenCodeEvent(event, this.sessionDirectories) @@ -454,6 +513,10 @@ class SSEAggregator { this.writeEnvelopeToClients(this.clients.keys(), null, event) } + /** + * Delivers an event to listeners and to the clients subscribed to its directory, writing no client + * frames when no client watches that directory. + */ private deliverEvent(directory: string, event: SSEEvent): void { this.notifyEvent(directory, event) @@ -473,6 +536,10 @@ class SSEAggregator { this.notifyListeners(directory, event) } + /** + * Fans an event out to local listeners with its directory scope and reports it as a local-server event, + * swallowing individual listener failures. + */ private notifyListeners(directory: string | null, event: SSEEvent): void { this.eventListeners.forEach(listener => { try { listener(directory, event) } catch { /* ignore listener errors */ } @@ -495,6 +562,10 @@ class SSEAggregator { } } + /** + * Writes one already-encoded frame to a client, logging the labeled error instead of propagating a + * failure so one broken connection cannot interrupt a broadcast. + */ private writeFrame(client: SSEClient, frame: Uint8Array, errorLabel: string): void { try { client.writeFrame(frame) @@ -511,6 +582,10 @@ class SSEAggregator { this.writeEnvelopeToClients(this.clients.keys(), directory, event, serverId) } + /** + * Sends a remote server event to a single client, but only when that client is subscribed to the + * server and directory the event belongs to. + */ deliverRemoteEnvelopeToClient(clientId: string, serverId: string, directory: string, event: SSEEvent): void { if (!this.hasClientDirectory(clientId, buildServerDirectoryKey(serverId, directory))) return const client = this.clients.get(clientId) @@ -530,6 +605,10 @@ class SSEAggregator { } } + /** + * Collects the IDs of clients subscribed to at least one directory of the given server, each client + * listed once regardless of how many of its directories match. + */ private clientIdsForServer(serverId: string): string[] { const clientIds: string[] = [] for (const client of this.clients.values()) { @@ -543,6 +622,11 @@ class SSEAggregator { return clientIds } + /** + * Updates active-session and subagent bookkeeping from local events before any listener sees them, so + * status queries reflect the event being dispatched: status and execution events move sessions between + * active and idle, deleted sessions are dropped, and sessions with a parent are marked as subagents. + */ private handleEvent(directory: string, event: SSEEvent): void { switch (event.type) { case 'session.status': { @@ -612,6 +696,10 @@ class SSEAggregator { logger.info(`Session active: ${sessionID} in ${directory} (${sessions.size} active)`) } + /** + * Drops a session from the active set of its directory, forgetting the directory once it has no + * active sessions left. + */ private markSessionIdle(directory: string, sessionID: string): void { const sessions = this.activeSessions.get(directory) if (sessions) { @@ -633,6 +721,11 @@ class SSEAggregator { return this.clients.size } + /** + * Records whether a client is in the foreground and which session and server it is viewing, clearing + * both view fields when it is not visible and defaulting the server to the local one. Returns false + * when the client is unknown, leaving stored visibility untouched. + */ setClientVisibility( id: string, visible: boolean, @@ -675,6 +768,10 @@ class SSEAggregator { return new Set(this.getScheduledSessions().map(ref => ref.sessionID)) } + /** + * Reads scheduled session references from the resolver installed by the scheduler, yielding an empty + * list when no resolver is set. + */ private getScheduledSessions(): ScheduledSessionRef[] { return this.scheduledSessionsResolver?.() ?? [] } diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 0a32692a..94d44f4d 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -191,6 +191,10 @@ function buildPromptFields(input: PromptFields) { } } +/** + * Fetches one page of sessions for the given list options and normalizes the + * server cursor so the end of the list is `undefined` rather than null. + */ export async function listSessionPage(input: SessionPageInput, serverId?: string): Promise { const { data, cursor } = await callOpenCode((api) => api.session.list(input), serverId) return { items: data, nextCursor: cursor.next ?? undefined } @@ -519,6 +523,10 @@ export async function listPendingPermissions( return data } +/** + * Replies to a pending permission request with the user's decision, sending the + * optional message only when one is supplied. + */ export async function replyPermission( sessionID: string, requestID: string, diff --git a/frontend/src/api/providers.ts b/frontend/src/api/providers.ts index ad4fb25d..3f349eaf 100644 --- a/frontend/src/api/providers.ts +++ b/frontend/src/api/providers.ts @@ -163,6 +163,10 @@ export async function toggleOpenCodeFavoriteModel(model: ModelSelection): Promis }); } +/** + * Returns the model's display name, falling back to its ID when the catalog + * provides no name. + */ export function formatModelName(model: Model): string { return model.name || model.modelID; } diff --git a/frontend/src/components/session/PermissionRequestDialog.tsx b/frontend/src/components/session/PermissionRequestDialog.tsx index 6f53c913..cbc7019d 100644 --- a/frontend/src/components/session/PermissionRequestDialog.tsx +++ b/frontend/src/components/session/PermissionRequestDialog.tsx @@ -36,6 +36,12 @@ interface PermissionRequestDialogProps { onOpenChange?: (open: boolean) => void } +/** + * Renders a modal prompt for the current pending permission request with + * allow-once, always-allow, and reject actions plus a count of further queued + * requests. Focus starts on allow-once, and the rejection reason resets + * whenever the request changes. + */ export function PermissionRequestDialog({ permission, pendingCount, @@ -60,6 +66,10 @@ export function PermissionRequestDialog({ if (!permission) return null if (parentOpen === false) return null + /** + * Sends the user's reply for the current permission request, passing the trimmed rejection reason + * only for rejections, and reports failures as a toast while clearing the pending action state. + */ const handleResponse = async (response: PermissionReply) => { setIsLoading(true) setLoadingAction(response) diff --git a/frontend/src/components/settings/AgentDialog.tsx b/frontend/src/components/settings/AgentDialog.tsx index 9e2157a3..91936f04 100644 --- a/frontend/src/components/settings/AgentDialog.tsx +++ b/frontend/src/components/settings/AgentDialog.tsx @@ -20,9 +20,18 @@ type ManagedPermissionAction = typeof MANAGED_PERMISSION_ACTIONS[number] type PermissionEffect = OpenCodePermissionRule['effect'] | 'inherit' +/** + * Reports whether a rule is a wildcard (`*` resource) rule for one of the + * managed actions (`edit`, `shell`, `webfetch`), which are the only rules the + * dialog's permission controls own. + */ const isManagedWildcardRule = (rule: OpenCodePermissionRule): boolean => rule.resource === '*' && MANAGED_PERMISSION_ACTIONS.includes(rule.action as ManagedPermissionAction) +/** + * Returns the final rule accepted by `matches`, mirroring OpenCode's + * last-match-wins resolution, or `undefined` when no rule matches. + */ const lastMatchingRule = ( permissions: OpenCodePermissionRule[] | undefined, matches: (rule: OpenCodePermissionRule) => boolean, @@ -36,6 +45,10 @@ const lastMatchingRule = ( return match } +/** + * Resolves the effect of an action's wildcard rule from stored permissions, + * returning `inherit` when the action has no such rule. + */ const permissionEffect = ( permissions: OpenCodePermissionRule[] | undefined, action: ManagedPermissionAction, @@ -72,11 +85,19 @@ const withManagedPermissionEffects = ( return [...updated.slice(0, fallbackIndex), ...fallbacks, ...updated.slice(fallbackIndex)] } +/** + * Parses a text input into a number, yielding `undefined` for blank or + * unparsable input so a cleared form field stays unset. + */ const optionalNumber = (value: string): number | undefined => { const parsed = parseFloat(value) return Number.isNaN(parsed) ? undefined : parsed } +/** + * Reads a numeric sampling value from the agent's raw `request.body`, returning + * `undefined` when the key is absent or holds a non-number. + */ const requestBodyNumber = (agent: OpenCodeAgentConfig | undefined, key: string): number | undefined => { const value = agent?.request?.body?.[key] return typeof value === 'number' ? value : undefined @@ -133,7 +154,17 @@ interface AgentDialogProps { editingAgent?: { name: string; agent: OpenCodeAgentConfig } | null } +/** + * Renders the create/edit agent dialog with identity, prompt, mode, model, + * permission, sampling, and disabled fields, locking the name while editing an + * existing agent. Submitting merges the form into the stored agent so managed + * permission and sampling settings survive the patch. + */ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: AgentDialogProps) { + /** + * Builds the form's initial values for an existing agent, or empty defaults + * when none is supplied, mapping permissions to their winning wildcard rule. + */ const getDefaultValues = (agent?: { name: string; agent: OpenCodeAgentConfig } | null): AgentFormValues => { const modelRef = configModelRef(agent?.agent.model) return { diff --git a/frontend/src/components/settings/AgentsEditor.tsx b/frontend/src/components/settings/AgentsEditor.tsx index 68cc125e..3879d6c5 100644 --- a/frontend/src/components/settings/AgentsEditor.tsx +++ b/frontend/src/components/settings/AgentsEditor.tsx @@ -17,6 +17,10 @@ interface AgentsEditorProps { onDelete: (name: string) => void } +/** + * Renders configured agents alongside agent files discovered in the workspace directory, with add, + * edit and delete entry points against the managed config. + */ export function AgentsEditor({ agents, directoryAgents = [], onSave, onDelete }: AgentsEditorProps) { const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false) const [editingAgent, setEditingAgent] = useState<{ name: string; agent: OpenCodeAgentConfig } | null>(null) diff --git a/frontend/src/components/settings/CommandDialog.tsx b/frontend/src/components/settings/CommandDialog.tsx index 185c144b..a24bd535 100644 --- a/frontend/src/components/settings/CommandDialog.tsx +++ b/frontend/src/components/settings/CommandDialog.tsx @@ -50,12 +50,22 @@ interface CommandDialogProps { editingCommand?: { name: string; command: OpenCodeCommandConfig } | null; } +/** + * Renders the create/edit command dialog with name, template, description, + * agent, model, and subagent fields, locking the name while editing an existing + * command. + */ export function CommandDialog({ open, onOpenChange, onSubmit, editingCommand, }: CommandDialogProps) { + /** + * Builds the form defaults for creating or editing a command, rendering any stored model + * reference in the `provider/model` display format and falling back to empty values when there is + * no command to edit. + */ const getDefaultValues = ( command?: { name: string; command: OpenCodeCommandConfig } | null, ): CommandFormValues => { @@ -81,6 +91,11 @@ export function CommandDialog({ } }, [open, editingCommand, form]); + /** + * Submits the validated command form as a patch that keeps the stored + * command's other fields, nulls emptied optional fields, and then resets and + * closes the dialog. + */ const handleSubmit = (values: CommandFormValues) => { const command: OpenCodeCommandPatch = { ...editingCommand?.command, diff --git a/frontend/src/components/settings/CommandsEditor.tsx b/frontend/src/components/settings/CommandsEditor.tsx index f76e1867..bbce2587 100644 --- a/frontend/src/components/settings/CommandsEditor.tsx +++ b/frontend/src/components/settings/CommandsEditor.tsx @@ -17,6 +17,10 @@ interface CommandsEditorProps { onDelete: (name: string) => void } +/** + * Renders configured commands alongside command files discovered in the workspace directory, + * providing add, edit and delete entry points against the managed config. + */ export function CommandsEditor({ commands, directoryCommands = [], onSave, onDelete }: CommandsEditorProps) { const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false) const [editingCommand, setEditingCommand] = useState<{ name: string; command: OpenCodeCommandConfig } | null>(null) diff --git a/frontend/src/components/settings/McpManager.tsx b/frontend/src/components/settings/McpManager.tsx index 821a4ff8..79635a40 100644 --- a/frontend/src/components/settings/McpManager.tsx +++ b/frontend/src/components/settings/McpManager.tsx @@ -23,6 +23,10 @@ interface McpManagerProps { onDelete: (serverId: string) => Promise } +/** + * Renders the MCP server list, unioning servers from the config with those known only to the live + * server status, and hosts the add, delete, OAuth and remove-auth dialogs. + */ export function McpManager({ mcp, onSave, onDelete }: McpManagerProps) { const [isAddDialogOpen, setIsAddDialogOpen] = useState(false) const [deleteConfirmServer, setDeleteConfirmServer] = useState<{ id: string; name: string } | null>(null) diff --git a/frontend/src/components/settings/OpenCodeConfigEditor.tsx b/frontend/src/components/settings/OpenCodeConfigEditor.tsx index a5535671..d70e1bbc 100644 --- a/frontend/src/components/settings/OpenCodeConfigEditor.tsx +++ b/frontend/src/components/settings/OpenCodeConfigEditor.tsx @@ -34,6 +34,12 @@ interface OpenCodeConfigEditorProps { onUpdate: (request: { content: string; source: OpenCodeConfigSourceName; expectedRevision?: string }) => Promise } +/** + * Renders the raw OpenCode config editor dialog for the chosen config source, + * with find-in-text, inline validation issues, and save feedback. Closing with + * unsaved edits prompts for discard, and the source cannot be switched while + * the draft is dirty or saving. + */ export function OpenCodeConfigEditor({ config, isOpen, @@ -121,6 +127,11 @@ export function OpenCodeConfigEditor({ const getIssueText = (issue: ValidationIssue) => `${issue.path}: ${issue.message}` + /** + * Maps API validation issues to display entries, substituting a readable path + * for empty or dotted ones and resolving each to a best-effort source line in + * the current draft. + */ const resolveIssues = ( issues: OpenCodeConfigValidationIssue[], ): ValidationIssue[] => @@ -135,6 +146,12 @@ export function OpenCodeConfigEditor({ } }) + /** + * Validates the draft as JSONC and saves it through `onUpdate` with the draft + * source and revision, closing the editor on success. Syntax errors, + * validation issues, and revision conflicts are shown in place without + * closing. + */ const updateConfig = async () => { if (!config || !draftSource) return diff --git a/frontend/src/components/settings/OpenCodeConfigManager.tsx b/frontend/src/components/settings/OpenCodeConfigManager.tsx index d0517b14..5c35fca8 100644 --- a/frontend/src/components/settings/OpenCodeConfigManager.tsx +++ b/frontend/src/components/settings/OpenCodeConfigManager.tsx @@ -46,6 +46,11 @@ interface ManagedConfigSectionFallbackProps { errorMessage: string | null } +/** + * Renders the placeholder for a managed config section while its data is loading or unavailable, + * prioritising the loading state, then a 503 message, then a generic error. Returns `null` when + * none of the conditions apply. + */ function ManagedConfigSectionFallback({ isLoading, unavailableMessage, errorMessage }: ManagedConfigSectionFallbackProps) { if (isLoading) { return ( @@ -72,6 +77,12 @@ function ManagedConfigSectionFallback({ isLoading, unavailableMessage, errorMess return null } +/** + * Renders the OpenCode settings panel whose collapsible sections manage + * AGENTS.md, commands, agents, skills, MCP servers, provider models, and host + * import. Config patches are revision-guarded, and a server restart is offered + * whenever saved changes require one. + */ export function OpenCodeConfigManager() { const sectionIdPrefix = useId() const agentsMdContentId = `${sectionIdPrefix}-agents-md` @@ -167,6 +178,10 @@ export function OpenCodeConfigManager() { const getApiErrorMessage = getOpenCodeApiErrorMessage + /** + * Returns the detail of a protected-host import failure, or the standard API + * error text with an import-specific fallback for other errors. + */ const getOpenCodeImportErrorMessage = (error: unknown): string => { if (error instanceof FetchError && error.code === 'OPENCODE_IMPORT_PROTECTED') { return error.detail || error.message @@ -180,12 +195,20 @@ export function OpenCodeConfigManager() { ? getApiErrorMessage(managedConfigError, 'Failed to load the OpenCode configuration') : null + /** + * Builds the section meta label for a managed config collection, substituting loading and + * unavailable states for the configured item count. + */ const getManagedConfigCountLabel = (count: number): string => { if (isManagedConfigLoading) return 'Loading...' if (managedConfigError) return 'Unavailable' return `${count} configured` } + /** + * Returns the section content when managed config is settled, otherwise the shared loading or + * error fallback; the 503 message is only surfaced when the error is an unavailable response. + */ const renderManagedConfigSection = (unavailableMessage: string, content: React.ReactNode) => isManagedConfigPending ? ( +/** + * Parses JSON text, returning `null` instead of throwing when the input is + * malformed. + */ function parseJson(value: string): unknown { try { return JSON.parse(value) as unknown @@ -41,6 +45,10 @@ function parseJson(value: string): unknown { } } +/** + * Parses JSON text and returns it only when it is a plain object, so arrays, + * primitives, and malformed input all yield `null`. + */ function parseJsonObject(value: string): JsonObject | null { const parsed = parseJson(value) if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { @@ -49,6 +57,10 @@ function parseJsonObject(value: string): JsonObject | null { return null } +/** + * Parses JSON text into an object or array, returning `null` for primitives and + * malformed input; callers that need one container kind narrow the result. + */ function parseJsonContainer(value: string): JsonObject | unknown[] | null { const parsed = parseJson(value) if (Array.isArray(parsed)) return parsed @@ -56,11 +68,19 @@ function parseJsonContainer(value: string): JsonObject | unknown[] | null { return null } +/** + * Parses JSON text and returns it only when it is an array, so object-shaped or + * malformed input yields `null`. + */ function parseJsonArray(value: string): unknown[] | null { const parsed = parseJson(value) return Array.isArray(parsed) ? parsed : null } +/** + * Serializes a value as indented JSON for an editable text field, returning an + * empty string for nullish input and for objects with no keys. + */ function stringifyJson(value: unknown): string { if (!value || (typeof value === 'object' && !Array.isArray(value) && Object.keys(value as JsonObject).length === 0)) { return '' @@ -69,16 +89,28 @@ function stringifyJson(value: unknown): string { return JSON.stringify(value, null, 2) } +/** + * Parses an optional JSON object field, treating blank input as absent and + * mapping invalid or non-object values to `undefined` so the patch omits them. + */ function parseOptionalJsonField(value: string): JsonObject | undefined { if (!value.trim()) return undefined return parseJsonObject(value) ?? undefined } +/** + * Parses an optional field holding either a JSON object or array, returning + * `undefined` for blank, primitive, or malformed input. + */ function parseOptionalJsonContainerField(value: string): JsonObject | unknown[] | undefined { if (!value.trim()) return undefined return parseJsonContainer(value) ?? undefined } +/** + * Parses an optional JSON array field, returning `undefined` when the field is + * blank or does not hold an array. + */ function parseOptionalJsonArrayField(value: string): unknown[] | undefined { if (!value.trim()) return undefined return parseJsonArray(value) ?? undefined @@ -90,6 +122,11 @@ function parseOptionalNumber(value: string): number | undefined { return Number.isFinite(parsed) ? parsed : undefined } +/** + * Recursively diffs the previously stored model config against the next one and + * replaces each dropped key with a merge-patch `null` so the server removes it. + * Values are returned untouched unless both sides are objects. + */ function withRemovedKeysAsNull(previous: unknown, next: unknown): unknown { if (!isRecord(previous) || !isRecord(next)) return next @@ -115,6 +152,11 @@ function prettifyModelName(modelId: string): string { .replace(/\b\w/g, (c) => c.toUpperCase()) } +/** + * Builds a schema field for optional JSON object text: blank input passes, and + * any other value must parse as a plain object or an issue named after `label` + * is reported. + */ function jsonObjectField(label: string) { return z.string().superRefine((value, ctx) => { if (!value.trim()) return @@ -127,6 +169,10 @@ function jsonObjectField(label: string) { }) } +/** + * Builds a form schema field that accepts blank input but rejects any non-blank + * value that is not a JSON object or array. + */ function jsonContainerField(label: string) { return z.string().superRefine((value, ctx) => { if (!value.trim()) return @@ -139,6 +185,10 @@ function jsonContainerField(label: string) { }) } +/** + * Builds a form schema field that accepts blank input but rejects any non-blank + * value that is not a valid JSON array. + */ function jsonArrayField(label: string) { return z.string().superRefine((value, ctx) => { if (!value.trim()) return @@ -229,6 +279,12 @@ interface OpenCodeModelDialogProps { } } +/** + * Renders the create/edit model dialog for a provider, including provider + * selection or new-provider fields, debounced model discovery from the provider + * base URL, limits, and free-form JSON fields for the remaining model settings. + * Values reset whenever the dialog opens for a different target. + */ export function OpenCodeModelDialog({ open, onOpenChange, @@ -391,6 +447,11 @@ export function OpenCodeModelDialog({ } }, [open, resetKey, form, getDefaultValues]) + /** + * Converts the validated form values into a model patch, parsing optional JSON + * and numeric fields and nulling keys cleared while editing, then passes the + * patch and any new provider config to `onSubmit` before resetting and closing. + */ const handleSubmit = (values: ModelFormValues) => { const extra = parseOptionalJsonField(values.extraJson) const settings = parseOptionalJsonField(values.settingsJson) diff --git a/frontend/src/components/settings/OpenCodeModelsEditor.tsx b/frontend/src/components/settings/OpenCodeModelsEditor.tsx index 227d59ec..3f5e2b77 100644 --- a/frontend/src/components/settings/OpenCodeModelsEditor.tsx +++ b/frontend/src/components/settings/OpenCodeModelsEditor.tsx @@ -24,6 +24,11 @@ interface EditingModel { model: OpenCodeProviderModelConfig } +/** + * Renders configured provider models grouped by provider, with an empty state and dialogs for + * creating and editing models. Submits the affected providers as a patch map so callers can apply + * the changes in one config update. + */ export function OpenCodeModelsEditor({ providers, onSave }: OpenCodeModelsEditorProps) { const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false) const [editingModel, setEditingModel] = useState(null) @@ -43,6 +48,11 @@ export function OpenCodeModelsEditor({ providers, onSave }: OpenCodeModelsEditor 0 ) + /** + * Builds a provider patch map for the submitted model, adding any new provider + * and nulling the previous provider or model key when an edit moved or renamed + * the entry, then hands the map to `onSave` and closes the dialog state. + */ const handleModelSubmit = ( providerId: string, modelId: string, @@ -53,6 +63,10 @@ export function OpenCodeModelsEditor({ providers, onSave }: OpenCodeModelsEditor ) => { const patches: Record = {} + /** + * Accumulates a provider patch into `patches`, starting from a copy of the existing provider + * config so model maps merge with prior entries instead of replacing them. + */ const addProviderPatch = (id: string, patch: OpenCodeProviderPatch) => { const existing: OpenCodeProviderPatch = patches[id] ?? (providers[id] ? { ...providers[id], models: { ...providers[id].models } } : {}) @@ -90,6 +104,10 @@ export function OpenCodeModelsEditor({ providers, onSave }: OpenCodeModelsEditor setIsCreateDialogOpen(false) } + /** + * Saves the provider with the model's key set to null so the entry is removed + * from the config; unknown providers are ignored. + */ const deleteModel = (providerId: string, modelId: string) => { const provider = providers[providerId] if (!provider) return diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 0c18b395..7b6e5e10 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -322,6 +322,11 @@ export function selectActiveSessionDirectoriesKey( const EventContext = createContext(null) +/** + * Provides stream-derived state to the page tree — SSH host key prompts, permission and form + * queues, stream health, and session-to-repo lookup — and routes stream events, status changes, + * and resyncs into React Query, session status, and running-shell state. + */ export function EventProvider({ children }: { children: React.ReactNode }) { const queryClient = useQueryClient() const navigate = useNavigate() @@ -1050,6 +1055,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) { useEffect(() => { if (!isAuthenticated) return + /** + * Routes one stream event by type into the session status, permission, form, shell and cache + * stores. Goal events are offered to `applySessionGoalEvent` first and skip the switch when it + * consumes them. + */ const handleSSEMessage = (event: OpenCodeStreamEvent) => { const serverId = event.serverId ?? LOCAL_OPENCODE_SERVER_ID @@ -1258,6 +1268,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) { } } + /** + * Repairs caches after the stream reports missed events: a remote server reconciles its own + * directory activity and list caches, while the local server also refreshes session statuses, + * running shells, and pending actions. + */ const handleResync = (subscribedDirectories: string[], serverId?: string) => { queryClient.invalidateQueries({ queryKey: [SESSION_GOAL_QUERY_ROOT] }) if (serverId && !isLocalOpenCodeServer(serverId)) { diff --git a/frontend/src/hooks/useFileSearch.ts b/frontend/src/hooks/useFileSearch.ts index c49e0f2e..2b567732 100644 --- a/frontend/src/hooks/useFileSearch.ts +++ b/frontend/src/hooks/useFileSearch.ts @@ -11,6 +11,11 @@ export interface FileSearchResult { error: Error | null } +/** + * Debounced, server-scoped file search returning matching paths with loading and error state. + * Results are cached per settled query for a minute, and nothing is requested while `enabled` + * is false or the query is still empty. + */ export function useFileSearch( query: string, enabled: boolean = true, diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 7f17d800..3c4ebb64 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -64,6 +64,11 @@ interface SessionListPage { nextParam?: SessionListPageParam } +/** + * Paginated session list merged across the given directories, or a single global stream when + * `allDirectories` is set, returning flattened items plus infinite-scroll controls. Only the + * unfiltered list is restored from disk, so only it keeps the extended `gcTime`. + */ export const useSessionsAcrossDirectories = ( directories: string[], options?: UseSessionsAcrossDirectoriesOptions, diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 7513adb2..903b90e1 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -22,6 +22,10 @@ import type { EventStreamSubscription } from '@/lib/opencode-event-stream' import { serverScopedKey } from '@/lib/serverScope' import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext' +/** + * Narrows a stream event to its directory, returning `undefined` when the payload carries no + * string directory rather than coercing another type. + */ const getEventDirectory = (event: OpenCodeStreamEvent): string | undefined => { return typeof event.directory === 'string' ? event.directory : undefined } @@ -47,6 +51,11 @@ const patchSessionIfCached = ( ) } +/** + * Subscribes the view to the global event stream for one or more directories, projecting session, + * shell, and status events into the React Query cache. Returns connection state plus the current + * error text for reconnection UI; it also reports exposure and visibility to the backend. + */ export const useSSE = (directory?: string | string[], currentSessionId?: string) => { const serverId = useOpenCodeServerId() const directoriesList = useMemo(() => { @@ -210,6 +219,10 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string) } } + /** + * Drops cached session and shell data for this server and re-reads the current session after + * the stream reports missed events. Resyncs for a different server are ignored. + */ const handleResync = (_subscribedDirectories: string[], resyncServerId?: string) => { if (!mountedRef.current) return if ((resyncServerId ?? LOCAL_OPENCODE_SERVER_ID) !== serverId) return diff --git a/frontend/src/hooks/useSessionAgent.ts b/frontend/src/hooks/useSessionAgent.ts index f0cd5ef0..a069623b 100644 --- a/frontend/src/hooks/useSessionAgent.ts +++ b/frontend/src/hooks/useSessionAgent.ts @@ -6,6 +6,10 @@ import type { AgentInfo, ModelRef } from '@opencode-manager/shared/opencode' type SessionAgentInfo = Pick +/** + * Resolves a requested agent id to its canonical primary-agent id, or `undefined` when it is + * absent or no longer selectable. Before the agent list loads the id passes through unchanged. + */ const resolveAvailableAgentId = ( agentId: string | undefined, agents: SessionAgentInfo[] | undefined, @@ -20,6 +24,10 @@ const resolveAvailableAgentId = ( )?.id } +/** + * Returns the first primary agent id once agents have loaded, falling back to `build` while + * loading or when no primary agent is available. + */ export function resolveDefaultSessionAgent( agents: SessionAgentInfo[] | undefined, agentsLoaded: boolean diff --git a/frontend/src/hooks/useSessionTranscript.ts b/frontend/src/hooks/useSessionTranscript.ts index 9430c092..03858936 100644 --- a/frontend/src/hooks/useSessionTranscript.ts +++ b/frontend/src/hooks/useSessionTranscript.ts @@ -29,6 +29,12 @@ interface NewestPageRead { const TRANSCRIPT_FALLBACK_POLL_INTERVAL_MS = 5000 +/** + * Returns the live transcript for one session: messages, pending tool calls, and status, kept + * current by applying stream events on animation frames and re-reading the newest page whenever + * events are missed or the stream reconnects. `fetchOlder` pages backwards through history, and + * polling stands in while the stream is not healthy. + */ export function useSessionTranscript(sessionID: string, directory: string) { const serverId = useOpenCodeServerId() const isRemoteServer = !isLocalOpenCodeServer(serverId) @@ -137,6 +143,10 @@ export function useSessionTranscript(sessionID: string, directory: string) { void readNewestPage().catch(() => undefined) } + /** + * Applies the events queued since the last frame to the cached transcript and requests a resync + * when the projection reports the cache fell behind. + */ const flush = () => { frameRef.current = null const events = queuedEventsRef.current diff --git a/frontend/src/lib/modelSections.ts b/frontend/src/lib/modelSections.ts index 27973f0f..78b08471 100644 --- a/frontend/src/lib/modelSections.ts +++ b/frontend/src/lib/modelSections.ts @@ -43,6 +43,11 @@ function createOption(provider: Provider, model: Model, value: string): ModelOpt } } +/** + * Groups the models of every provider into the Default, Favorites, Recent, and per-provider + * sections of the model picker. A model pinned as the default or a favorite is removed from its + * provider section, and sections left empty are dropped. + */ export function buildModelSections( providers: Provider[], modelState: OpenCodeModelState | undefined, diff --git a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts index 6ddb348b..0a1d05fe 100644 --- a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts +++ b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts @@ -271,6 +271,10 @@ export class OpenCodeEventStream { } } + /** + * Parses one raw stream frame, marks the connection active, and broadcasts the unwrapped event + * to every subscriber. Frames that fail to parse still count as activity. + */ private handleMessage(data: string): void { try { this.markActivity() @@ -421,6 +425,10 @@ export class OpenCodeEventStream { }) } + /** + * Acknowledges a resync request by marking the stream active and notifying each subscriber with the + * directories it tracks and the server the resync belongs to. + */ private handleResync(data?: string): void { this.markActivity() const directories = Array.from(this.directoryRefCounts.keys()) @@ -434,6 +442,10 @@ export class OpenCodeEventStream { }) } + /** + * Delivers an event to every subscriber, isolating each callback so a throwing subscriber cannot + * prevent the remaining subscribers from receiving it. + */ private broadcast(event: OpenCodeStreamEvent): void { this.subscribers.forEach((subscriber) => { try { @@ -499,6 +511,10 @@ export class OpenCodeEventStream { } } +/** + * Reads the optional `serverId` from a resync frame, returning `undefined` when the payload is + * absent, malformed, or carries no string id. + */ function parseResyncServerId(data?: string): string | undefined { if (!data) return undefined try { @@ -509,10 +525,17 @@ function parseResyncServerId(data?: string): string | undefined { } } +/** + * Type guard for a decoded stream payload, requiring an object with a string `type` discriminator. + */ function isEventPayload(value: unknown): value is V2Event | SSHHostKeyRequestEvent { return isRecord(value) && typeof value.type === 'string' } +/** + * Unwraps a transport envelope into the stream event consumers expect, copying `directory` and + * `serverId` onto it when present. Returns `null` when the envelope or its payload is malformed. + */ function flattenEventEnvelope(parsed: unknown): OpenCodeStreamEvent | null { if (!isRecord(parsed) || !isEventPayload(parsed.payload)) return null diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 3678dff0..bad9d603 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -121,6 +121,11 @@ function isSessionNotFoundError(error: unknown): boolean { return error instanceof FetchError && (error.statusCode === 400 || error.statusCode === 404) } +/** + * Renders one session: a header with its title and parent link, the transcript with its composer, + * and the collapsible tool panels. Redirects home for an unknown session and shows a not-found + * state when the repository does not exist. + */ export function SessionDetail() { const serverId = useOpenCodeServerId(); const isRemoteServer = !isLocalOpenCodeServer(serverId); diff --git a/frontend/src/stores/sessionStatusStore.ts b/frontend/src/stores/sessionStatusStore.ts index df8e1bfe..01f5d7c1 100644 --- a/frontend/src/stores/sessionStatusStore.ts +++ b/frontend/src/stores/sessionStatusStore.ts @@ -75,6 +75,10 @@ const clearOptimisticActiveTimer = (sessionID: string): void => { optimisticActiveTimers.delete(sessionID) } +/** + * Hash used to skip redundant status writes: the status type alone, except for retry states, + * which include their attempt metadata so changed retry details still propagate. + */ const getStatusHash = (status: SessionStatusType): string => { if (status.type === 'retry') { return JSON.stringify(status) diff --git a/ocm-cli/src/link.ts b/ocm-cli/src/link.ts index ecea0299..6c433e33 100644 --- a/ocm-cli/src/link.ts +++ b/ocm-cli/src/link.ts @@ -214,6 +214,10 @@ export async function probeOpenCodeServer( } } +/** + * Extracts a human-readable message from an unknown thrown value, falling back to `String(error)` + * for non-`Error` values. + */ function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error) } diff --git a/shared/src/opencode/config-validation.ts b/shared/src/opencode/config-validation.ts index 65a4bd1a..0ec798b6 100644 --- a/shared/src/opencode/config-validation.ts +++ b/shared/src/opencode/config-validation.ts @@ -14,6 +14,10 @@ const standardSchema = Schema.toStandardSchemaV1(Info, { const LEGACY_SKILLS_MESSAGE = 'skills must be a list of skill paths. Replace the legacy `skills: { paths: [...] }` object with `skills: [...]`.' +/** + * Renders a schema issue path as a dotted string, unwrapping the standard-schema key objects and + * falling back to `root` for empty or missing paths. + */ function toIssuePath(path: ReadonlyArray | undefined): string { if (!path || path.length === 0) return 'root' return path @@ -21,6 +25,10 @@ function toIssuePath(path: ReadonlyArray