mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
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.
This commit is contained in:
1 parent
64e87ba1ea
commit
6297403a41
41 files changed
+691
No files matched your search
@@ -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<SessionPage> {
|
||||
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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -23,6 +23,10 @@ interface McpManagerProps {
|
||||
onDelete: (serverId: string) => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
|
||||
@@ -34,6 +34,12 @@ interface OpenCodeConfigEditorProps {
|
||||
onUpdate: (request: { content: string; source: OpenCodeConfigSourceName; expectedRevision?: string }) => Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
|
||||
@@ -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 ? (
|
||||
<ManagedConfigSectionFallback
|
||||
@@ -220,6 +243,11 @@ export function OpenCodeConfigManager() {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists an agent or command entry under `name`; when a rename occurred it also nulls the
|
||||
* previous key so the old entry is removed in the same patch. Fire-and-forget, surfacing failures
|
||||
* as a toast.
|
||||
*/
|
||||
const saveManagedEntity = (
|
||||
key: 'agents' | 'commands',
|
||||
name: string,
|
||||
|
||||
@@ -33,6 +33,10 @@ const handledModelKeys = new Set([
|
||||
|
||||
type JsonObject = Record<string, unknown>
|
||||
|
||||
/**
|
||||
* 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)
|
||||
|
||||
@@ -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<EditingModel | null>(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<string, OpenCodeProviderPatch> = {}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -322,6 +322,11 @@ export function selectActiveSessionDirectoriesKey(
|
||||
|
||||
const EventContext = createContext<EventContextValue | null>(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)) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -6,6 +6,10 @@ import type { AgentInfo, ModelRef } from '@opencode-manager/shared/opencode'
|
||||
|
||||
type SessionAgentInfo = Pick<AgentInfo, 'id' | 'mode' | 'hidden'>
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user