feat: add opencode support (#762)

* feat: add opencode support

* fix: stabilize opencode session startup

* fix: /models

* fix: improveUI for commands

* fix: format commands.js

* feat: load models through provider adapters

Provider model selection had outgrown a single hardcoded service.

The old service mixed shared caching with provider catalogs and CLI lookup details.

That made stale model lists more likely as providers changed on separate schedules.

Move model discovery behind each provider so lookup lives next to the integration.

The shared service now focuses on provider resolution, caching, persistence, and dedupe.

Return cache metadata and add bypassCache because model availability changes outside the app.

The UI and /models command can show freshness and let users force a provider refresh.

Surface model descriptions while keeping fallback catalogs for unavailable CLIs or SDKs.

* feat(models): resolve active session models through provider adapters

The model inventory command was showing a mix of catalog defaults and
composer-local state instead of the model that is actually active for a
real provider session. That made /models, /cost, and /status
misleading once a session had already started, especially for providers
whose effective runtime model can differ from the optimistic model value
held in the UI.

Introduce an explicit getCurrentActiveModel() contract on
IProviderModels so model resolution lives next to each provider's
catalog logic and uses the provider-native source of truth:

- Claude reads the init event from a resumed stream-json run
- Codex reads model from ~/.codex/config.toml
- Cursor reads lastUsedModel from the chat store.db
- OpenCode reads the persisted session model from opencode.db
- Gemini intentionally returns its default because the CLI does not
  provide a reliable active-session lookup

Keep the returned shape intentionally minimal ({ model }). The goal is
to expose only what downstream command consumers need and avoid leaking
provider-specific metadata into a shared transport shape that would
create extra UI coupling and future cleanup cost.

Also make command behavior session-aware: when there is no concrete
session id, do not spawn provider processes or inspect provider session
storage just to answer /models, /cost, or /status. In a new-session
view the correct answer is simply the provider default, and doing more
work there adds latency and unnecessary side effects for no user value.

As part of this, centralize two supporting concerns:

- add a shared helper for building the default current-model result from
  a provider catalog so fallbacks stay aligned with DEFAULT
- move leaf-directory validation into shared utils so Cursor session
  readers and model lookup code enforce the same path-safety rule

Tests were expanded to cover both the new service delegation path and
the sessionless command behavior, while keeping cache-sensitive tests
isolated from persisted host cache state.

Why this change:
- command output should reflect the model actually driving a session
- new-session views should stay fast and side-effect free
- provider-specific active-model lookup should not be scattered across
  routes or UI code
- fallback behavior should be explicit, consistent, and limited to the
  provider default when no true active model can be resolved

* feat: support session-scoped model overrides

Model selection was acting like a provider-level preference.

That made resumed sessions drift back to a default or request-time model.

Users expect /models changes made inside a conversation to affect that session.

Store explicit session choices in app-owned ~/.cloudcli state.

This avoids editing provider transcripts or native provider config.

Resolve the effective model before launching each provider runtime.

Claude, Cursor, Codex, Gemini, and OpenCode now honor stored resume choices.

Expose a backend active-model change endpoint for existing sessions.

The models modal can now distinguish default changes from session overrides.

It also shows when a selected model will apply on the next response.

For Claude, stop probing active model state by resuming with a dummy prompt.

Read the indexed JSONL transcript from the end instead.

This preserves provider history while honoring /model stdout or model fields.

Add service tests for adapter delegation and resume-model precedence.

The tests keep cache state, override state, and requested fallback separate.

* feat: make command modal more compact

* fix: preserve opencode session creation events

OpenCode emits the real session id asynchronously on its first JSON output. The runner
registered that id from a helper that could not see the spawned process because
the process reference was scoped inside the model-resolution callback. That
ReferenceError was swallowed by the generic JSON parse fallback, so the client
never received session_created. Without that event, a new OpenCode chat stayed
on / and the assistant stream was not attached to the new session view.

Keep the process reference in the outer spawn scope so registration can update
the active-process map and websocket writer as soon as OpenCode announces the
session id. Split JSON parsing from event processing so malformed non-JSON
output can still stream as raw text, while registration or adapter failures are
surfaced as real errors instead of being hidden as assistant content.

Add a fake opencode executable regression test to lock in the expected lifecycle
ordering: session_created must be sent before live assistant messages, and the
same session id must carry through stream_end and complete.

* fix: clarify model refresh and onboarding providers

OpenCode is now a supported chat provider, but first-run onboarding still only offered
Claude, Cursor, Codex, and Gemini. That made OpenCode harder to discover and
forced users to finish setup before finding the provider in settings or chat.
Adding it to onboarding keeps first-run setup aligned with the providers the
application already supports elsewhere.

The model refresh control was also doing too much visual work. In the new chat
model picker, the previous Hard Refresh label looked like the dialog heading,
which made the primary task unclear. Users open that dialog to choose a model;
refreshing catalogs is only a secondary maintenance action for stale cached
provider model lists.

Rename and reposition the refresh affordance so the model picker reads as a
model picker first. The copy now explains why catalogs are cached, when a refresh
is useful, and that the refresh checks every provider. The /models modal gets the
same clarification so both model-selection surfaces describe the cache behavior
consistently.

* fix: format opencode model catalog labels

OpenCode returns provider-prefixed ids directly from the CLI. Passing those ids through as
labels made the model picker hard to scan: users saw values like
anthropic/claude-3-5-sonnet-20241022 or lowercased, hyphen-split text instead
of readable model names.

Keep the exact OpenCode id as the option value because that is what the CLI
expects, but derive a presentation label for the frontend. The formatter is
intentionally generic rather than a catalog of known providers. It handles common
identifier structure such as provider/model, hyphen-delimited words, v-prefixed
versions, adjacent numeric version tokens, and 8-digit date suffixes.

This keeps OpenCode usable as its model list expands across many upstream
providers without requiring code changes for every new provider or model family.
The description keeps the raw provider-prefixed id visible so users can still
confirm the precise model being selected.

* feat: add more fallback models for cursor

* docs: move model catalog out of shared

The model catalog is no longer a frontend/backend runtime contract.

Keeping it under shared made ownership misleading. It implied the catalog was
application code shared by runtime consumers, even though it now only supports
README links and public API documentation.

Move the catalog into public so it lives beside the docs surfaces that need it.
This gives the API docs a stable, served module and gives README readers a
linkable source without suggesting frontend or backend runtime dependency.

Render the API docs model list from the exported provider registry instead of a
hardcoded Claude/Cursor/Codex subset. That keeps Gemini and OpenCode visible and
makes future provider documentation changes flow through one docs-specific file.

Update README links, provider maintenance notes, and package files so published
artifacts include the standalone docs page and model catalog without relying on
the old shared path.

* fix: simplify empty-state model selector

Keep the provider empty state focused on the setup action users need there:

choosing a model.

The refresh control, cache timestamp, and refresh explanation made the dialog feel

like a cache-management surface.

That extra action is out of place in the empty state, where the goal is to start

a chat with the selected provider and model.

Remove the refresh-specific UI from ProviderSelectionEmptyState and drop the

now-unused refresh/cache props from the ChatMessagesPane pass-through.

Refresh behavior remains available in the dedicated command result flow.
This commit is contained in:
Haile
2026-05-28 11:50:41 +03:00
committed by GitHub
parent 10f721cf14
commit 374e9de719
87 changed files with 7024 additions and 577 deletions

View File

@@ -22,7 +22,13 @@ import type {
AnyRecord,
ApiSuccessShape,
AppErrorOptions,
LLMProvider,
NormalizedMessage,
ProviderChangeActiveModelInput,
ProviderCurrentActiveModel,
ProviderModelsDefinition,
ProviderSessionActiveModelChange,
ProviderSkillSource,
WorkspacePathValidationResult,
} from '@/shared/types.js';
@@ -413,6 +419,231 @@ export const readStringRecord = (value: unknown): Record<string, string> | undef
return Object.keys(normalized).length > 0 ? normalized : undefined;
};
// ---------------------------
//----------------- PROVIDER MODEL LOOKUP UTILITIES ------------
/**
* Builds the standard "default current model" result used when a provider
* cannot resolve a session-backed active model.
*
* Provider model adapters should call this after loading their supported model
* catalog so the fallback stays aligned with the provider's current `DEFAULT`
* selection instead of drifting to a hard-coded duplicate.
*/
export function buildDefaultProviderCurrentActiveModel(
models: ProviderModelsDefinition,
): ProviderCurrentActiveModel {
return {
model: models.DEFAULT,
};
}
// ---------------------------
//----------------- PROVIDER SESSION MODEL CHANGE UTILITIES ------------
type ProviderSessionActiveModelChangeCacheEntry = ProviderSessionActiveModelChange & {
updatedAt: string;
};
type ProviderSessionActiveModelChangeCacheFile = {
version: number;
entries: Record<string, ProviderSessionActiveModelChangeCacheEntry>;
};
const PROVIDER_SESSION_ACTIVE_MODEL_CHANGE_CACHE_VERSION = 1;
/**
* Resolves the backend-owned cache file used for session-scoped resume model
* overrides.
*
* The file lives under `~/.cloudcli` because these overrides are an application
* concern rather than a provider-native config file. Providers, routes, and
* runtime command launchers should all use this helper instead of re-creating
* the path so the storage location stays consistent.
*/
export function getProviderSessionActiveModelChangesPath(): string {
return path.join(os.homedir(), '.cloudcli', 'provider-session-active-model-changes.json');
}
const buildProviderSessionActiveModelChangeKey = (
provider: LLMProvider,
sessionId: string,
): string => `${provider}:${sessionId}`;
const isProviderSessionActiveModelChangeCacheEntry = (
value: unknown,
): value is ProviderSessionActiveModelChangeCacheEntry => {
const record = readObjectRecord(value);
return Boolean(
record
&& typeof record.provider === 'string'
&& typeof record.sessionId === 'string'
&& typeof record.supported === 'boolean'
&& typeof record.changed === 'boolean'
&& (typeof record.model === 'string' || record.model === null)
&& typeof record.updatedAt === 'string',
);
};
const readProviderSessionActiveModelChangeCacheFile = async (
filePath: string,
): Promise<ProviderSessionActiveModelChangeCacheFile> => {
try {
const raw = await readFile(filePath, 'utf8');
const parsed = readObjectRecord(JSON.parse(raw));
if (
!parsed
|| parsed.version !== PROVIDER_SESSION_ACTIVE_MODEL_CHANGE_CACHE_VERSION
|| !readObjectRecord(parsed.entries)
) {
return {
version: PROVIDER_SESSION_ACTIVE_MODEL_CHANGE_CACHE_VERSION,
entries: {},
};
}
const entries = Object.fromEntries(
Object.entries(parsed.entries).filter((entry): entry is [string, ProviderSessionActiveModelChangeCacheEntry] =>
isProviderSessionActiveModelChangeCacheEntry(entry[1]),
),
);
return {
version: PROVIDER_SESSION_ACTIVE_MODEL_CHANGE_CACHE_VERSION,
entries,
};
} catch {
return {
version: PROVIDER_SESSION_ACTIVE_MODEL_CHANGE_CACHE_VERSION,
entries: {},
};
}
};
const writeProviderSessionActiveModelChangeCacheFile = async (
filePath: string,
payload: ProviderSessionActiveModelChangeCacheFile,
): Promise<void> => {
await mkdir(path.dirname(filePath), { recursive: true });
await writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
};
const buildUnsupportedProviderSessionActiveModelChange = (
provider: LLMProvider,
sessionId: string,
): ProviderSessionActiveModelChange => ({
provider,
sessionId,
supported: false,
changed: false,
model: null,
});
/**
* Reads the persisted session model-change state for one provider session.
*
* Runtime resume paths use this to decide whether they should inject a
* provider-specific model argument/thread option for the next resumed turn.
* Missing cache entries are normalized to `{ changed: false }` so callers can
* treat absence as "use the ordinary model selection flow".
*/
export async function readProviderSessionActiveModelChange(
provider: LLMProvider,
sessionId: string,
options: {
filePath?: string;
supported?: boolean;
} = {},
): Promise<ProviderSessionActiveModelChange> {
const normalizedSessionId = sessionId.trim();
if (!normalizedSessionId) {
return buildUnsupportedProviderSessionActiveModelChange(provider, normalizedSessionId);
}
const supported = options.supported ?? true;
if (!supported) {
return buildUnsupportedProviderSessionActiveModelChange(provider, normalizedSessionId);
}
const filePath = options.filePath ?? getProviderSessionActiveModelChangesPath();
const cacheFile = await readProviderSessionActiveModelChangeCacheFile(filePath);
const cacheEntry = cacheFile.entries[
buildProviderSessionActiveModelChangeKey(provider, normalizedSessionId)
];
if (!cacheEntry || !cacheEntry.changed || !cacheEntry.model?.trim()) {
return {
provider,
sessionId: normalizedSessionId,
supported: true,
changed: false,
model: null,
};
}
return {
provider,
sessionId: normalizedSessionId,
supported: true,
changed: true,
model: cacheEntry.model.trim(),
};
}
/**
* Persists a session model-change request for one provider.
*
* Provider adapters call this when the frontend explicitly selects a different
* model for an existing session. The stored `changed: true` flag is the single
* source of truth used later by resume paths to decide whether they should add
* a provider-native model override on the next invocation.
*/
export async function writeProviderSessionActiveModelChange(
provider: LLMProvider,
input: ProviderChangeActiveModelInput,
options: {
filePath?: string;
supported?: boolean;
} = {},
): Promise<ProviderSessionActiveModelChange> {
const normalizedSessionId = input.sessionId.trim();
const normalizedModel = input.model.trim();
const supported = options.supported ?? true;
if (!supported) {
return buildUnsupportedProviderSessionActiveModelChange(provider, normalizedSessionId);
}
if (!normalizedSessionId || !normalizedModel) {
return {
provider,
sessionId: normalizedSessionId,
supported: true,
changed: false,
model: null,
};
}
const filePath = options.filePath ?? getProviderSessionActiveModelChangesPath();
const cacheFile = await readProviderSessionActiveModelChangeCacheFile(filePath);
cacheFile.entries[buildProviderSessionActiveModelChangeKey(provider, normalizedSessionId)] = {
provider,
sessionId: normalizedSessionId,
supported: true,
changed: true,
model: normalizedModel,
updatedAt: new Date().toISOString(),
};
await writeProviderSessionActiveModelChangeCacheFile(filePath, cacheFile);
return {
provider,
sessionId: normalizedSessionId,
supported: true,
changed: true,
model: normalizedModel,
};
}
// ---------------------------
//----------------- WEBSOCKET PAYLOAD PARSING UTILITIES ------------
/**
@@ -506,6 +737,67 @@ export const writeJsonConfig = async (filePath: string, data: Record<string, unk
// ---------------------------
//----------------- PROVIDER SKILL FILE UTILITIES ------------
async function hasGitMarker(dirPath: string): Promise<boolean> {
try {
const gitMarkerStats = await stat(path.join(dirPath, '.git'));
return gitMarkerStats.isDirectory() || gitMarkerStats.isFile();
} catch {
return false;
}
}
/**
* Finds the highest git worktree root visible from a starting directory.
*
* Provider skill systems such as Codex and OpenCode walk upward through parent
* folders when resolving repository/project skills. Use this helper when a
* provider needs the topmost `.git` marker instead of only the nearest one, so
* monorepos and nested package folders discover shared root-level skills once.
*/
export async function findTopmostGitRoot(startPath: string): Promise<string | null> {
let currentPath = path.resolve(startPath);
let topmostGitRoot: string | null = null;
while (true) {
if (await hasGitMarker(currentPath)) {
topmostGitRoot = currentPath;
}
const parentPath = path.dirname(currentPath);
if (parentPath === currentPath) {
break;
}
currentPath = parentPath;
}
return topmostGitRoot;
}
/**
* Adds one provider skill source after normalizing and de-duplicating its root.
*
* Provider skill lookup rules often point at overlapping folders (for example a
* workspace folder can also be the git root). Use this helper while building a
* provider's `ProviderSkillSource[]` so the shared skills scanner reads each
* physical root once and still preserves provider-specific scope/command data.
*/
export function addUniqueProviderSkillSource(
sources: ProviderSkillSource[],
seenRootDirs: Set<string>,
source: ProviderSkillSource,
): void {
const normalizedRootDir = path.resolve(source.rootDir);
if (seenRootDirs.has(normalizedRootDir)) {
return;
}
seenRootDirs.add(normalizedRootDir);
sources.push({ ...source, rootDir: normalizedRootDir });
}
// ---------------------------
//----------------- PROVIDER SKILL MARKDOWN UTILITIES ------------
/**
* Finds direct child skill markdown files under a provider skill root.
*
@@ -616,6 +908,98 @@ export function normalizeSessionName(rawValue: string | undefined, fallback: str
return normalized.slice(0, 120);
}
// ---------------------------
//----------------- PROVIDER SESSION VALUE NORMALIZATION UTILITIES ------------
/**
* Converts provider-native timestamps into ISO strings.
*
* Provider CLIs commonly persist epoch timestamps as milliseconds, seconds, or
* already-formatted date strings. Use this helper when normalizing session
* metadata or transcript events so every provider writes the same ISO timestamp
* shape to API responses and database rows.
*/
export function normalizeProviderTimestamp(value: unknown): string {
if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
const millis = value < 1_000_000_000_000 ? value * 1000 : value;
return new Date(millis).toISOString();
}
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) {
return normalizeProviderTimestamp(parsed);
}
const date = new Date(value);
if (!Number.isNaN(date.getTime())) {
return date.toISOString();
}
}
return new Date().toISOString();
}
/**
* Parses a JSON string or narrows an existing object into a plain record.
*
* Use this when provider databases store structured JSON inside text columns.
* Invalid JSON, arrays, and primitive values return `null` so callers can skip
* malformed optional metadata without hiding the rest of a session transcript.
*/
export function readJsonRecord(value: unknown): AnyRecord | null {
if (typeof value !== 'string') {
return readObjectRecord(value);
}
try {
return readObjectRecord(JSON.parse(value));
} catch {
return null;
}
}
// ---------------------------
//----------------- OPENCODE SESSION STORAGE UTILITIES ------------
/**
* Resolves the OpenCode SQLite session database path.
*
* OpenCode stores session, message, part, and project metadata in one shared
* `opencode.db` file under its XDG data directory. Provider readers and
* synchronizers should use this path for read-only access and should never store
* it as a deletable transcript path for an individual app session row.
*/
export function getOpenCodeDatabasePath(): string {
return path.join(os.homedir(), '.local', 'share', 'opencode', 'opencode.db');
}
// ---------------------------
//----------------- SAFE DIRECTORY NAME UTILITIES ------------
/**
* Validates that a user or provider supplied identifier can safely be treated
* as one leaf directory name under an existing root folder.
*
* Use this before composing paths like `<root>/<session-id>/file.db>` to block
* path traversal and accidental nested paths. The returned string is trimmed but
* otherwise unchanged so callers can still match the provider's on-disk naming.
*/
export function sanitizeLeafDirectoryName(inputName: string, label = 'directory name'): string {
const normalized = inputName.trim();
if (!normalized) {
throw new Error(`${label} is required.`);
}
if (
normalized.includes('..')
|| normalized.includes(path.posix.sep)
|| normalized.includes(path.win32.sep)
|| normalized !== path.basename(normalized)
) {
throw new Error(`Invalid ${label} "${inputName}".`);
}
return normalized;
}
// ---------------------------
//----------------- SESSION SYNCHRONIZER FILESYSTEM HELPERS ------------
/**