* refactor(settings): settings registry and intent-gated writes
Problem: every setting lived in a flat document with ten hand-maintained
key lists that had drifted (three keys the server silently dropped, five
it kept that nothing read), and three code paths wrote to the server
without a person changing anything: the theme persist effect on mount,
bootstrap seeding of server-missing keys, and the auto-save echoing
values just adopted from the server.
Approach: one registry (packages/ui/src/lib/settings/registry.ts) names
every key with its scope (instance / profile / device), a boundary parser
and its store binding; DesktopSettings, the sanitizer, the mirror, the
apply step and the auto-save derive from it. A generated JSON snapshot
carries the key list to the server and the VS Code bridge. Writes carry
intent: the theme context writes only from its user-facing setters, a
missing server key leaves the local store alone instead of resetting it,
updateDesktopSettings drops values the server already holds, and the
auto-savers treat values applied from the server as a new baseline.
Testing: bun test packages/ui (registry + persistence suites cover zero
writes on load, dedup, toggle-back cancellation, failed-save retry, and
snapshot freshness); tsc for every workspace.
* refactor(ui): read and write settings through the shared path only
Problem: fourteen pages and stores fetched /api/config/settings on their
own and re-parsed the raw document by hand, so the registry could not
guard them and two of them treated a failed load as an empty list.
Approach: loadDesktopSettings() and updateDesktopSettings() (which now
resolves { ok }) replace every direct call; SkillsCatalogPage and
AddCatalogDialog refuse to write the catalog list until it is known.
Testing: bun test packages/ui (403 files), eslint on the changed files.
* refactor(server): validate settings writes against the registry snapshot
Problem: the server whitelist was the only guard on PUT /api/config/settings
and had drifted from the client; dead keys were still persisted.
Approach: settings-helpers.js drops any key the generated registry
snapshot does not list as persistable and strips secret keys from
responses; the dead keys (markdownDisplayMode, toolCallExpansion,
typographySizes, expandedEditorToolbar, gitProviderId/gitModelId) are
gone; the profile keys that were client-only now round-trip. A drift
test requires a valid sample for every persistable registry key.
Testing: vitest run in packages/web (182 files), including the packed
tarball import.
* refactor(vscode): gate bridge settings writes by the registry
Problem: the extension host wrote any key the webview sent straight into
settings.json, and commit-message generation read the dead
gitProviderId/gitModelId pair instead of the small-model setting.
Approach: filterPersistableSettingsChanges applies the registry snapshot
before the file write; chooseBridgeGitGenerationModel honours
smallModelUseDefault/smallModelOverride ahead of the zen fallback.
Testing: bun test packages/vscode (37 files), tsc, build:extension.
* feat(settings): split the user's profile into preferences.json
Problem: one flat settings.json held instance facts, the user's
preferences and device state together, so device state travelled between
installs and the profile had no document of its own to sync from.
Approach: the server keeps one merged document for clients but routes
each key by registry scope on disk (settings-files.js): profile keys go to
preferences.json as { value, updatedAt } entries stamped when the value
changes, everything else stays in settings.json, device keys are dropped
from writes. A missing preferences.json is seeded once from settings.json,
which is left intact; an unreadable one is a failure that pauses profile
writes and never gets overwritten. Server modules that read a profile key
off the disk use the merged sync read. Electron main reads the theme mode
from both files and now owns the splash colours, handed over the
window-theme IPC instead of the settings document. Clients stop sending
device keys, seed them once from a pre-split document, and persist
inputBarOffset locally. The PWA manifest keys are instance facts.
Testing: vitest in packages/web (seed, split write, timestamp retention,
unreadable file), bun test in packages/ui and packages/electron, tsc for
every workspace.
* feat(vscode): write the profile to preferences.json from the extension host
Problem: the extension host writes the shared settings files directly and
had to follow the server's split, and its file writes reported success on
failure.
Approach: settings-files.ts mirrors the server's format and split rules
(seed once, unreadable preferences.json is a failure); persistSettings
routes profile keys to preferences.json and the rest to settings.json,
and the atomic writers now throw so a failed save reaches the webview.
Clearing a key now actually removes it from the owning file.
Testing: bun test packages/vscode (38 files), tsc, build:extension.
* feat(settings): store the per-surface profile fields by surface kind
Problem: theme, chat-layout switches and typography sizes are one value
for every client of an instance, so the phone and the desktop cannot
disagree without a hard-coded runtime branch.
Approach: every settings request carries the client's surface kind in the
x-openchamber-surface header (web, desktop, vscode, mobile — the phone app
and the hosted mobile shell are one kind). For the registry's perSurface
keys the store writes a changed value under fields[key].surfaces[kind] in
preferences.json and never touches the base from a surface; reads resolve
the kind's own value, then the base, then nothing. Writes without a
surface (migrations, the seed) set the base. The VS Code host is always
vscode; Electron main resolves desktop for the native window theme. The
Settings UI is unchanged.
Testing: vitest in packages/web (surface write/read, no base copy, unknown
surface falls back to base), bun test in packages/vscode and packages/ui,
tsc for every workspace, build:extension.
* fix(settings): keep a legacy copy of the profile in settings.json
The first write after the split rewrote settings.json with the instance
part only, and that write happens on startup (relay reconcile). A build
from before the split reads only settings.json, so rolling back would
have lost every preference: theme, default model, all of it.
Every write now stores the profile's base values in settings.json next
to the instance part (`legacySettingsDocumentOf`), on the server and in
the VS Code extension host alike. Current builds ignore the copy because
preferences.json wins in the merged read. When preferences.json is
unreadable the copy already on disk is kept rather than dropped.
Testing: settings-runtime tests updated for the copy; full web suite
(182 files), VS Code tests and extension build, tsc clean. Verified live
on a scratch OPENCHAMBER_DATA_DIR: all 136 keys survive startup, theme
changes land per surface, plain keys land in the base.
* feat(settings): make the UI password and tunnel preset tokens write-only
GET /api/config/settings returned desktopUiPassword and the managed
remote tunnel preset tokens to every authenticated client, including
paired phones and the VS Code webview that never need them.
Both keys are now `secret` in the registry: accepted on write, withheld
from reads. The server answers with a hasDesktopUiPassword flag; the
desktop network page shows "Password set" and sends a value only when
the user types a new one or presses "Remove password" (an empty string
clears it and turns LAN access off). The tunnel page already learned
token presence from the status endpoint. The VS Code bridge strips
secret keys from what it hands the webview while still merging them
from disk on write.
Testing: registry, i18n parity, server settings, VS Code gate tests and
tsc; workspace type-check. Verified against a scratch server: GET
carries the flag and no password, PUT with '' clears, PUT with a value
sets. The desktop-only page itself awaits the owner's run.
* fix(settings): send the surface kind as a query parameter, not a header
The packaged desktop shell (openchamber-ui://app) and the phone app are
cross-origin to the OpenChamber server, so the x-openchamber-surface
header turned every settings request into a CORS preflight the server
did not allow. Settings looked reset and every save reported "Save
failed" without reaching persistSettings. An older remote instance would
refuse the header the same way even with the allow-list fixed.
The client now sends ?surface=<kind>, which keeps the request
CORS-simple on every server version; the server reads the query
parameter and still honours the header. The header is also in the CORS
allow-list for completeness.
Testing: workspace type-check, persistence and registry tests, server
opencode tests. On a scratch server: PUT with ?surface=vscode lands
under surfaces.vscode, GET without or with an unknown surface serves the
base, the header fallback resolves. Confirmed in the owner's rebuilt
desktop and on the phone.
* refactor(settings): drop the show-password toggle from the desktop network page
With the password write-only, the field only ever holds a value the user
is typing right now; the reveal toggle and its strings are gone from
every locale.
* refactor(projects): serve project setup through the server, drop the legacy migration
The shared UI read and wrote ~/.config/openchamber/projects/<id>.json
itself: it resolved the home directory, composed the path, and used the
Files API, which only desktop and VS Code have natively and which cannot
see a remote instance's file at all. It also still carried the months-old
migration from <repo>/.openchamber/openchamber.json, which deleted files in
the folder the upcoming shared project config will use.
The client-owned keys (worktree setup commands, project actions, draft
starters) now live behind GET/PUT /api/projects/:projectId/config.
project-setup.js sanitizes and builds the view; the project-config runtime
merges a patch under the same cross-process lock the scheduled-task writers
hold, so unknown and server-owned keys survive. A wrongly shaped key is a
400, not a silent drop. openchamberConfig.ts keeps its exported functions
and is now an HTTP client. The VS Code webview handles the route locally
and bridges to the extension host, which owns the file with a TS mirror of
the sanitizers.
Testing: server tests for sanitizers, round trip, lock, and invalid patch;
client tests against a mocked route; VS Code sanitizer and bridge tests;
workspace type-check, both VS Code builds, UI isolated suite (409 files),
server projects and project-context suites. Live GET/PUT against a
running server with the owner's real project config.
* feat(projects): read the team's shared config and merge it with the personal one
A project can now carry <repo>/.openchamber/project.json (version 1:
setupWorktree, setupWorktreeWait, projectActions, draftStarters,
plansDir). The server finds the checkout from the path-derived project
id, parses the file, and answers GET /api/projects/:id/config with one
merged view: what runs at the top level, plus shared and personal blocks
so a page can edit the personal file without copying a teammate's entry
into it.
Merge rules: shared setup commands run first (a personal
setupWorktreeMode of "replace" uses the personal list only); the
personal wait flag wins when set; actions union by id with a personal
action replacing the shared one and personal hiddenSharedActionIds
dropping shared ones; starters union by type:name; the primary action is
personal only. A shared file that exists but cannot be parsed, or that
names a plansDir outside the repo, is reported as invalid with a reason
and never treated as "no shared setup". Nothing writes the repo file yet.
Client: getProjectSetup exposes the view; the existing helpers return
effective values, while the Projects page sections and the draft
starters hook edit the personal block only. Shared entries show a quiet
"shared" mark in the actions dropdown and read-only lists above the
editable ones on the Projects page; shared starter chips have no remove
handle. The VS Code extension host mirrors the parser and merge.
Testing: server tests for the parser, plansDir guard, merge table, id
round trip, and a runtime test against a temp checkout; client tests
against a mocked route; VS Code sanitizer, merge, and bridge tests; the
section test covers the shared row; locale parity; workspace type-check;
UI isolated suite (409 files). Live: GET against a temp repo with a
shared file and with a broken one.
* feat(projects): ask before the team's shared commands run, once per set of commands
Shared setup commands and shared actions come from a file a git pull can
change, and they run on the machine of whoever pulls. The first time one
would run, a dialog now shows exactly what would run and asks: "Trust and
run" or "Not this time". A "trust" answer is recorded in the personal
config against a SHA-256 of the executable parts (setup commands and each
action's id, command, and runIn; renames and icons do not count), so a
pull that changes a command brings the prompt back. Nothing asks when the
shared file has nothing that executes.
Worktree creation (session creator, new-worktree dialog, session store,
multi-run launcher, agent-manager empty state) resolves its commands
through the prompt; "not this time" runs only the user's own commands.
The actions dropdown asks before a shared action runs. The Projects page
shows "Trusted on this instance" with a "Reset trust" button next to the
shared actions. The dialog is mounted beside the app-link confirmation on
every shell. The VS Code extension host mirrors the hash and the record.
Testing: server tests for hash stability, ordering, and the trusted flag,
plus a runtime test that changes the shared file and sees trust drop;
client tests for the confirmation store (ask, trust, skip, replace mode,
newer request, failed record, reset); VS Code mirror tests; the actions
button, new-worktree dialog, and issue-2039 tests updated for the trust
path; locale parity; workspace type-check; UI isolated suite (410 files).
* feat(projects): share and unshare setup with the team from the Projects page
The repo file <repo>/.openchamber/project.json is now written by the app,
and only when the user shares something: nothing appears in a repository
until then. PUT /api/projects/:id/config/shared replaces the keys it
names over the current file, writes it pretty-printed with version first
and only the keys that carry something, removes the file (and an empty
.openchamber folder) when nothing is left, refuses a missing checkout or
a plansDir outside the repo, and records trust for the writer, who has
seen what they shared.
On the Projects page, actions and setup commands get "Share with team"
and "Make personal"; shared actions can be hidden for this user; a
checkbox switches to "Use only my setup commands". Project starter chips
get share and make-personal hover buttons. A new "Shared config" block
shows the file's path and status, the shared plans folder, and the trust
status with "Reset trust". A share is a repo write followed by a personal
write; a failure after the first leaves the item visible once, as
personal. The VS Code extension host mirrors the writer.
Testing: server tests for the patch, serialization, emptiness, the write
and removal round trip, the writer's trust record, and the refusals;
client test for the shared route; VS Code bridge test for write and
removal; locale parity; workspace type-check; UI isolated suite (410
files). Live on a scratch server: share, invalid plansDir (400), unshare
to removal of file and folder.
* feat(projects): list, edit, and move plans in the team's shared plans folder
When the shared config names a plansDir, every markdown file in that
folder is a plan on the Plans tab: listed after the user's own plans,
marked shared, addressed as shared:<file>, read and edited in place
(the raw document is written verbatim, so a plan another tool wrote
keeps its shape), and deletable. Share moves one of the user's plans
into the folder; make personal moves it back under a new id; a name
collision gets a numeric suffix. Sharing is refused, with a hint in the
panel, until a shared plans folder is set in Project settings. This
answers the request to read plans from an existing folder such as
docs/plans.
Server: the project-context runtime takes resolveSharedPlansDir from the
project-config runtime; readContext reports sharedPlansDir; POST
.../plans/:id/share and /unshare. Client: movePlan in the context store,
a shared badge and a share / make-personal button per plan row. Session
attachments reference plan ids, so an attached plan that moves has to be
attached again.
Testing: runtime tests for listing, foreign markdown titles, id
traversal, in-place update and delete, share and unshare with a
collision, and the refusal without a folder; HTTP route tests; store and
locale parity tests; workspace type-check; full web suite (183 files);
UI isolated suite (410 files). Live on a scratch server against a temp
repo: list, share, read, unshare.
* fix(server): make OPENCHAMBER_DATA_DIR move every folder, not just the flat files
The variable is documented as the OpenChamber data directory, but only
settings, preferences, auth, and push files followed it; projects,
themes, speech models, and the chats default stayed under
~/.config/openchamber. A second instance started with a custom
directory therefore read and wrote the default instance's project
configs.
Every folder now hangs off the one root. An instance that already used
a custom directory gets projects, themes, and speech-models copied in
once at startup; copied, not moved, so a second instance beside the
default one cannot strip it, and nothing is merged into a folder that
already exists. Existing managed chats are not copied, as with
OPENCHAMBER_CHATS_DIR.
Testing: migration tests for copy-once, no-merge, and same-root no-op;
full web suite; a scratch server with an empty data dir copied the real
project configs and kept its writes in the copy.
* fix(projects): keep a plan's id when it moves into or out of the repository folder
A plan moved into the repository plans folder used to be listed under a
new shared:<file> id, so a session that had attached it lost the
attachment. The manifest entry now stays with a `shared` flag that says
which folder holds the file; the id survives both directions. Only a
plan that never had an entry (one written by another tool) gets an id
when it is brought in. A personal file and a repository file may share
a name because they live in different folders.
Testing: runtime tests for share and unshare with a stable id, reading
and editing the moved plan, the suffix on a name collision, and the
adoption of a foreign file.
* feat(projects): default repository plans folder, "move to repository" wording, tooltips
Plans now have a repository folder without any setup: .openchamber/plans
by default. A custom plansDir replaces the default outright (only that
folder is read and written; moving files between the two is the user's
job), and the field's placeholder and hint say so. The move buttons on
plans are therefore always available.
The word "share" is gone from the UI: it read like publishing, while
the action stores an item in the repository so everyone who pulls it
gets it. Labels are "Move to repository" / "Move to my settings", the
badge is "In repo", the block is "Repository config", and every button
on the Projects page carries a tooltip that says what happens (the
"Move to repository" button explains that edits save first while the
form is dirty). The trust status with "reset trust" moved from the
repository block into the Worktree section next to the commands it
guards; the plan row's badge sits beside the title.
Testing: locale parity, section test, workspace type-check, UI isolated
suite (410 files), full web suite.
* fix(projects): leave the icon key out of the repository file when an action has none
Actions without an icon were written as "icon": null into
.openchamber/project.json. The key is now omitted; readers already fall
back to the play icon. Server and VS Code serializers, tests updated.
* docs: describe the repository config file and how items move into it
A new page in every locale: what stays personal and what can move into
the repository, the .openchamber/project.json format with an example
and every key explained (setup commands, actions with the supported icon
names, starters, plansDir), the merge rules, the trust prompt, and plans
in the repository. Linked from the sidebar and from Project Actions.
Translations written by hand.
857 lines
32 KiB
JavaScript
857 lines
32 KiB
JavaScript
import express from 'express';
|
|
import { createProjectIdFromPath } from '../projects/project-id.js';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import {
|
|
buildDeferredRestartResponse,
|
|
} from './config-mutation-response.js';
|
|
import { getClaudeCliAuthStatus } from './claude-cli-auth.js';
|
|
import { OPENCODE_CONFIG_DIR } from './shared.js';
|
|
import { settingsSurfaceOf } from './settings-files.js';
|
|
|
|
export const registerOpenCodeRoutes = (app, dependencies) => {
|
|
const {
|
|
crypto,
|
|
getOpenCodeResolutionSnapshot,
|
|
getOpenCodeUpgradeCapability,
|
|
formatSettingsResponse,
|
|
readSettingsFromDisk,
|
|
readSettingsFromDiskMigrated,
|
|
persistSettings,
|
|
sanitizeProjects,
|
|
validateDirectoryPath,
|
|
resolveProjectDirectory,
|
|
getProviderSources,
|
|
removeProviderConfig,
|
|
upsertProviderConfig,
|
|
refreshOpenCodeAfterConfigChange,
|
|
buildOpenCodeUrl,
|
|
getOpenCodeAuthHeaders,
|
|
fsPromises = fs.promises,
|
|
} = dependencies;
|
|
|
|
let authLibrary = null;
|
|
const pendingMcpAuthContextByState = new Map();
|
|
const PENDING_MCP_AUTH_TTL_MS = 30 * 60 * 1000;
|
|
const getAuthLibrary = async () => {
|
|
if (!authLibrary) {
|
|
authLibrary = await import('./auth.js');
|
|
}
|
|
return authLibrary;
|
|
};
|
|
|
|
const normalizePendingString = (value) => {
|
|
if (typeof value !== 'string') {
|
|
return null;
|
|
}
|
|
|
|
const trimmed = value.trim();
|
|
return trimmed || null;
|
|
};
|
|
|
|
const escapeHtml = (value) => String(value)
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''');
|
|
|
|
// Self-contained page for the OAuth return leg: the system browser has no UI
|
|
// session, so it cannot load the SPA behind the auth gate — everything it
|
|
// needs ships inline. `openchamber://focus/mcp-auth` raises the desktop app;
|
|
// the link stays visible because some browsers only follow custom-protocol
|
|
// URLs from a user gesture.
|
|
const renderMcpOAuthCallbackPage = ({ title, message, desktopReturn }) => `<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>${escapeHtml(title)} — OpenChamber</title>
|
|
<style>
|
|
:root { color-scheme: light dark; }
|
|
body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
background: Canvas; color: CanvasText; }
|
|
main { max-width: 34rem; padding: 2.5rem 2rem; text-align: center; }
|
|
h1 { font-size: 1.25rem; margin: 0 0 0.75rem; }
|
|
p { margin: 0; line-height: 1.5; opacity: 0.85; }
|
|
a.return { display: inline-block; margin-top: 1.5rem; padding: 0.5rem 1.25rem; border-radius: 0.5rem;
|
|
border: 1px solid color-mix(in srgb, CanvasText 25%, transparent); color: inherit; text-decoration: none; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<main>
|
|
<h1>${escapeHtml(title)}</h1>
|
|
<p>${escapeHtml(message)}</p>
|
|
${desktopReturn ? `<a class="return" href="openchamber://focus/mcp-auth">Return to OpenChamber</a>
|
|
<script>window.location.href = 'openchamber://focus/mcp-auth';</script>` : ''}
|
|
</main>
|
|
</body>
|
|
</html>`;
|
|
|
|
const readOpenCodeCurrentVersion = async () => {
|
|
const healthResponse = await fetch(buildOpenCodeUrl('/global/health', ''), {
|
|
method: 'GET',
|
|
headers: { Accept: 'application/json', ...getOpenCodeAuthHeaders() },
|
|
});
|
|
const health = await healthResponse.json().catch(() => null);
|
|
if (!healthResponse.ok) {
|
|
return { ok: false, status: healthResponse.status, error: health?.error || healthResponse.statusText };
|
|
}
|
|
const currentVersion = typeof health?.version === 'string' ? health.version.replace(/^v/, '') : null;
|
|
return { ok: true, currentVersion };
|
|
};
|
|
|
|
const parseVersionForComparison = (value) => {
|
|
const normalized = String(value || '').replace(/^v/, '').split('+')[0];
|
|
const prereleaseIndex = normalized.indexOf('-');
|
|
const core = prereleaseIndex >= 0 ? normalized.slice(0, prereleaseIndex) : normalized;
|
|
const parts = core.split('.').map((part) => {
|
|
const parsed = Number.parseInt(part || '0', 10);
|
|
return Number.isFinite(parsed) ? parsed : 0;
|
|
});
|
|
return { parts, prerelease: prereleaseIndex >= 0 };
|
|
};
|
|
|
|
const compareVersions = (left, right) => {
|
|
const a = parseVersionForComparison(left);
|
|
const b = parseVersionForComparison(right);
|
|
const length = Math.max(a.parts.length, b.parts.length);
|
|
for (let index = 0; index < length; index += 1) {
|
|
const diff = (a.parts[index] || 0) - (b.parts[index] || 0);
|
|
if (diff !== 0) return diff;
|
|
}
|
|
if (a.prerelease !== b.prerelease) return a.prerelease ? -1 : 1;
|
|
return 0;
|
|
};
|
|
|
|
const fetchLatestOpenCodeVersionFromGithub = async () => {
|
|
const response = await fetch('https://api.github.com/repos/anomalyco/opencode/releases/latest', {
|
|
headers: { Accept: 'application/json' },
|
|
signal: AbortSignal.timeout(10_000),
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(`OpenCode releases responded with ${response.status}`);
|
|
}
|
|
const payload = await response.json();
|
|
const tag = typeof payload?.tag_name === 'string' ? payload.tag_name.trim() : '';
|
|
return tag.replace(/^v/, '');
|
|
};
|
|
|
|
const fetchLatestOpenCodeVersionFromNpm = async () => {
|
|
const response = await fetch('https://registry.npmjs.org/opencode-ai/latest', {
|
|
headers: { Accept: 'application/json' },
|
|
signal: AbortSignal.timeout(10_000),
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(`OpenCode npm registry responded with ${response.status}`);
|
|
}
|
|
const payload = await response.json();
|
|
return typeof payload?.version === 'string' ? payload.version.trim().replace(/^v/, '') : '';
|
|
};
|
|
|
|
const fetchLatestOpenCodeVersion = async () => {
|
|
const results = await Promise.allSettled([
|
|
fetchLatestOpenCodeVersionFromNpm(),
|
|
fetchLatestOpenCodeVersionFromGithub(),
|
|
]);
|
|
const versions = results
|
|
.filter((result) => result.status === 'fulfilled' && result.value)
|
|
.map((result) => result.value);
|
|
if (versions.length === 0) {
|
|
const failure = results.find((result) => result.status === 'rejected');
|
|
throw failure?.reason instanceof Error ? failure.reason : new Error('Failed to resolve latest OpenCode version');
|
|
}
|
|
return versions.sort((left, right) => compareVersions(right, left))[0];
|
|
};
|
|
|
|
// OpenCode's `/global/upgrade` requires an explicit semver target and rejects
|
|
// a bodyless call, so "update to the latest" has to name the version. The
|
|
// release lookup is the same one the upgrade-status check already uses to
|
|
// decide there is anything to offer.
|
|
const resolveOpenCodeUpgradeTarget = async (requestedTarget) => {
|
|
if (typeof requestedTarget === 'string' && requestedTarget.trim().length > 0) {
|
|
return { resolved: true, target: requestedTarget.trim() };
|
|
}
|
|
try {
|
|
const latest = await fetchLatestOpenCodeVersion();
|
|
if (!latest) {
|
|
return { resolved: false, reason: 'The latest OpenCode version could not be determined.' };
|
|
}
|
|
return { resolved: true, target: latest };
|
|
} catch (error) {
|
|
return {
|
|
resolved: false,
|
|
reason: error instanceof Error ? error.message : 'The latest OpenCode version could not be determined.',
|
|
};
|
|
}
|
|
};
|
|
|
|
// OpenCode reports a rejected upgrade as `{ name, data: { message, kind } }`,
|
|
// which carries no `error` field. Reading only `error` left the user with the
|
|
// bare HTTP status text ("Bad Request") and nothing to act on.
|
|
const readOpenCodeUpgradeErrorMessage = (payload, response) => {
|
|
const candidates = [payload?.error, payload?.data?.message, payload?.message];
|
|
for (const candidate of candidates) {
|
|
if (typeof candidate === 'string' && candidate.trim().length > 0) {
|
|
return candidate.trim();
|
|
}
|
|
}
|
|
return response.statusText || 'Failed to upgrade OpenCode';
|
|
};
|
|
|
|
const pruneExpiredPendingMcpAuthContexts = () => {
|
|
const now = Date.now();
|
|
for (const [state, entry] of pendingMcpAuthContextByState.entries()) {
|
|
if (!entry || typeof entry.expiresAt !== 'number' || entry.expiresAt <= now) {
|
|
pendingMcpAuthContextByState.delete(state);
|
|
}
|
|
}
|
|
};
|
|
|
|
app.get('/api/config/settings', async (req, res) => {
|
|
try {
|
|
// The surface kind resolves the per-surface profile keys; absent means base.
|
|
const settings = await readSettingsFromDiskMigrated({ surface: settingsSurfaceOf(req) });
|
|
res.json(formatSettingsResponse(settings));
|
|
} catch (error) {
|
|
console.error('Failed to read settings:', error);
|
|
res.status(500).json({ error: 'Failed to read settings' });
|
|
}
|
|
});
|
|
|
|
app.get('/api/config/opencode-resolution', async (_req, res) => {
|
|
try {
|
|
const settings = await readSettingsFromDiskMigrated();
|
|
const resolution = await getOpenCodeResolutionSnapshot(settings);
|
|
res.json(resolution);
|
|
} catch (error) {
|
|
console.error('Failed to resolve OpenCode binary:', error);
|
|
res.status(500).json({ error: 'Failed to resolve OpenCode binary' });
|
|
}
|
|
});
|
|
|
|
let openCodeUpgradePromise = null;
|
|
|
|
app.post('/api/opencode/upgrade', async (req, res) => {
|
|
try {
|
|
const capability = getOpenCodeUpgradeCapability();
|
|
if (!capability.supported) {
|
|
return res.status(409).json({
|
|
success: false,
|
|
code: capability.reason === 'bundled'
|
|
? 'OPENCODE_UPGRADE_MANAGED_BY_OPENCHAMBER'
|
|
: 'OPENCODE_UPGRADE_UNSUPPORTED',
|
|
error: capability.reason === 'bundled'
|
|
? 'OpenCode is bundled with OpenChamber Desktop and updates with the app.'
|
|
: 'This OpenCode runtime cannot be upgraded by OpenChamber.',
|
|
});
|
|
}
|
|
if (openCodeUpgradePromise) {
|
|
return res.status(409).json({
|
|
success: false,
|
|
code: 'OPENCODE_UPGRADE_IN_PROGRESS',
|
|
error: 'An OpenCode upgrade is already in progress.',
|
|
});
|
|
}
|
|
|
|
const requestedTarget = req.body?.target;
|
|
// The target lookup reaches the network, so it runs inside the operation:
|
|
// the in-flight lock is taken synchronously above, and a second click
|
|
// cannot slip past while the release version is being resolved.
|
|
const upgradeOperation = (async () => {
|
|
const targetResolution = await resolveOpenCodeUpgradeTarget(requestedTarget);
|
|
if (!targetResolution.resolved) {
|
|
return {
|
|
status: 502,
|
|
body: {
|
|
success: false,
|
|
code: 'OPENCODE_UPGRADE_TARGET_UNRESOLVED',
|
|
error: `Could not determine which OpenCode version to install: ${targetResolution.reason}`,
|
|
},
|
|
};
|
|
}
|
|
|
|
const response = await fetch(buildOpenCodeUrl('/global/upgrade', ''), {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Accept: 'application/json',
|
|
...getOpenCodeAuthHeaders(),
|
|
},
|
|
body: JSON.stringify({ target: targetResolution.target }),
|
|
});
|
|
const payload = await response.json().catch(() => null);
|
|
if (!response.ok) {
|
|
return {
|
|
status: response.status,
|
|
body: {
|
|
success: false,
|
|
error: readOpenCodeUpgradeErrorMessage(payload, response),
|
|
},
|
|
};
|
|
}
|
|
|
|
try {
|
|
await refreshOpenCodeAfterConfigChange('OpenCode upgrade');
|
|
} catch (restartError) {
|
|
return {
|
|
status: 500,
|
|
body: {
|
|
success: false,
|
|
upgraded: true,
|
|
error: restartError instanceof Error
|
|
? `OpenCode upgraded, but restart failed: ${restartError.message}`
|
|
: 'OpenCode upgraded, but restart failed',
|
|
},
|
|
};
|
|
}
|
|
|
|
return {
|
|
status: 200,
|
|
body: { ...(payload ?? { success: true }), restarted: true },
|
|
};
|
|
})();
|
|
openCodeUpgradePromise = upgradeOperation;
|
|
|
|
try {
|
|
const result = await upgradeOperation;
|
|
return res.status(result.status).json(result.body);
|
|
} finally {
|
|
if (openCodeUpgradePromise === upgradeOperation) {
|
|
openCodeUpgradePromise = null;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error('Failed to upgrade OpenCode:', error);
|
|
return res.status(500).json({
|
|
success: false,
|
|
error: error instanceof Error ? error.message : 'Failed to upgrade OpenCode',
|
|
});
|
|
}
|
|
});
|
|
|
|
app.get('/api/opencode/upgrade-status', async (_req, res) => {
|
|
try {
|
|
const capability = getOpenCodeUpgradeCapability();
|
|
if (!capability.supported) {
|
|
const current = await readOpenCodeCurrentVersion().catch(() => ({ ok: false, currentVersion: null }));
|
|
return res.json({
|
|
available: false,
|
|
currentVersion: current.ok ? current.currentVersion : null,
|
|
latestVersion: null,
|
|
upgrade: capability,
|
|
});
|
|
}
|
|
|
|
const [healthResponse, latestVersion] = await Promise.all([
|
|
fetch(buildOpenCodeUrl('/global/health', ''), {
|
|
method: 'GET',
|
|
headers: { Accept: 'application/json', ...getOpenCodeAuthHeaders() },
|
|
}),
|
|
fetchLatestOpenCodeVersion(),
|
|
]);
|
|
const health = await healthResponse.json().catch(() => null);
|
|
if (!healthResponse.ok) {
|
|
return res.status(healthResponse.status).json({
|
|
available: null,
|
|
error: health?.error || healthResponse.statusText || 'Failed to read OpenCode version',
|
|
});
|
|
}
|
|
const currentVersion = typeof health?.version === 'string' ? health.version.replace(/^v/, '') : null;
|
|
if (!currentVersion || !latestVersion) {
|
|
return res.json({ available: null, currentVersion, latestVersion: latestVersion || null });
|
|
}
|
|
const available = compareVersions(latestVersion, currentVersion) > 0;
|
|
return res.json({
|
|
available,
|
|
currentVersion,
|
|
latestVersion,
|
|
upgrade: capability,
|
|
});
|
|
} catch (error) {
|
|
return res.status(500).json({
|
|
available: null,
|
|
error: error instanceof Error ? error.message : 'Failed to check OpenCode upgrade status',
|
|
});
|
|
}
|
|
});
|
|
|
|
app.get('/api/opencode/health', async (_req, res) => {
|
|
try {
|
|
const healthResponse = await fetch(buildOpenCodeUrl('/global/health', ''), {
|
|
method: 'GET',
|
|
headers: { Accept: 'application/json', ...getOpenCodeAuthHeaders() },
|
|
});
|
|
const health = await healthResponse.json().catch(() => null);
|
|
if (!healthResponse.ok) {
|
|
return res.status(healthResponse.status).json({
|
|
healthy: false,
|
|
error: health?.error || healthResponse.statusText || 'OpenCode health check failed',
|
|
});
|
|
}
|
|
return res.json({ healthy: health?.healthy === true });
|
|
} catch (error) {
|
|
return res.status(503).json({
|
|
healthy: false,
|
|
error: error instanceof Error ? error.message : 'OpenCode health check failed',
|
|
});
|
|
}
|
|
});
|
|
|
|
app.get('/api/opencode/version', async (_req, res) => {
|
|
try {
|
|
const healthResponse = await fetch(buildOpenCodeUrl('/global/health', ''), {
|
|
method: 'GET',
|
|
headers: { Accept: 'application/json', ...getOpenCodeAuthHeaders() },
|
|
});
|
|
const health = await healthResponse.json().catch(() => null);
|
|
if (!healthResponse.ok) {
|
|
return res.status(healthResponse.status).json({
|
|
version: null,
|
|
error: health?.error || healthResponse.statusText || 'Failed to read OpenCode version',
|
|
});
|
|
}
|
|
const version = typeof health?.version === 'string' ? health.version.replace(/^v/, '') : null;
|
|
return res.json({ version });
|
|
} catch (error) {
|
|
return res.status(500).json({
|
|
version: null,
|
|
error: error instanceof Error ? error.message : 'Failed to read OpenCode version',
|
|
});
|
|
}
|
|
});
|
|
|
|
app.put('/api/config/settings', async (req, res) => {
|
|
try {
|
|
const updated = await persistSettings(req.body ?? {}, { surface: settingsSurfaceOf(req) });
|
|
res.json(updated);
|
|
} catch (error) {
|
|
console.error('[API:PUT /api/config/settings] Failed to save settings:', error);
|
|
console.error('[API:PUT /api/config/settings] Error stack:', error.stack);
|
|
res.status(500).json({ error: 'Failed to save settings' });
|
|
}
|
|
});
|
|
|
|
// The body parser is per-route on this server; without it req.body is
|
|
// undefined here, the state read as absent, and the "parked" context was
|
|
// silently never stored — the callback then always failed as unknown.
|
|
app.post('/api/mcp/auth/pending', express.json({ limit: '16kb' }), async (req, res) => {
|
|
try {
|
|
pruneExpiredPendingMcpAuthContexts();
|
|
|
|
const state = normalizePendingString(req.body?.state);
|
|
if (!state) {
|
|
return res.json({ success: true, context: null });
|
|
}
|
|
|
|
const name = normalizePendingString(req.body?.name);
|
|
if (!name) {
|
|
return res.status(400).json({ error: 'MCP server name is required' });
|
|
}
|
|
|
|
const entry = {
|
|
name,
|
|
directory: normalizePendingString(req.body?.directory),
|
|
// Which surface started the flow. It belongs here rather than in the
|
|
// redirect URI: that URI is written into the server's config once and
|
|
// deliberately never rewritten, so anything encoded in it would be
|
|
// frozen at whatever runtime authorised first.
|
|
origin: normalizePendingString(req.body?.origin),
|
|
expiresAt: Date.now() + PENDING_MCP_AUTH_TTL_MS,
|
|
};
|
|
pendingMcpAuthContextByState.set(state, entry);
|
|
|
|
return res.json({
|
|
success: true,
|
|
context: {
|
|
name: entry.name,
|
|
directory: entry.directory,
|
|
origin: entry.origin,
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Failed to store pending MCP auth context:', error);
|
|
return res.status(500).json({ error: error.message || 'Failed to store pending MCP auth context' });
|
|
}
|
|
});
|
|
|
|
app.get('/api/mcp/auth/pending', async (req, res) => {
|
|
try {
|
|
pruneExpiredPendingMcpAuthContexts();
|
|
|
|
const state = normalizePendingString(Array.isArray(req.query?.state) ? req.query.state[0] : req.query?.state);
|
|
if (!state) {
|
|
return res.json(null);
|
|
}
|
|
|
|
const pendingMcpAuthContext = pendingMcpAuthContextByState.get(state) ?? null;
|
|
if (!pendingMcpAuthContext) {
|
|
return res.status(404).json({ error: 'No pending MCP auth context' });
|
|
}
|
|
|
|
return res.json(pendingMcpAuthContext);
|
|
} catch (error) {
|
|
console.error('Failed to read pending MCP auth context:', error);
|
|
return res.status(500).json({ error: error.message || 'Failed to read pending MCP auth context' });
|
|
}
|
|
});
|
|
|
|
app.delete('/api/mcp/auth/pending', async (req, res) => {
|
|
try {
|
|
const state = normalizePendingString(Array.isArray(req.query?.state) ? req.query.state[0] : req.query?.state);
|
|
if (!state) {
|
|
return res.json({ success: true });
|
|
}
|
|
|
|
pendingMcpAuthContextByState.delete(state);
|
|
return res.json({ success: true });
|
|
} catch (error) {
|
|
console.error('Failed to clear pending MCP auth context:', error);
|
|
return res.status(500).json({ error: error.message || 'Failed to clear pending MCP auth context' });
|
|
}
|
|
});
|
|
|
|
// Browser return leg of the MCP OAuth flow, completed entirely server-side.
|
|
//
|
|
// The provider redirects the SYSTEM browser here, and that browser has no
|
|
// OpenChamber UI session — the SPA route this path used to land on sits
|
|
// behind the client-side auth gate, so the user saw a login page instead of
|
|
// a finished authorization. No session can be required on this path.
|
|
//
|
|
// Safe without auth because it acts only on a code+state pair whose `state`
|
|
// matches a context parked by an authenticated start call: `state` is the
|
|
// OAuth CSRF secret, generated per flow and known only to the initiating
|
|
// client and the provider. Without a match the code is NOT forwarded, so an
|
|
// unauthenticated caller cannot bind this server's MCP entry to a foreign
|
|
// account by fabricating a callback. The endpoint reads nothing and mutates
|
|
// nothing else.
|
|
app.get('/mcp/oauth/callback', async (req, res) => {
|
|
const queryValue = (key) => normalizePendingString(Array.isArray(req.query?.[key]) ? req.query[key][0] : req.query?.[key]);
|
|
const state = queryValue('state');
|
|
const code = queryValue('code');
|
|
const providerError = queryValue('error');
|
|
const providerErrorDescription = queryValue('error_description');
|
|
|
|
pruneExpiredPendingMcpAuthContexts();
|
|
const context = state ? pendingMcpAuthContextByState.get(state) ?? null : null;
|
|
const startedFromDesktop = context?.origin === 'desktop';
|
|
|
|
const finish = (status, { title, message }) => {
|
|
if (state) pendingMcpAuthContextByState.delete(state);
|
|
res.status(status).type('html').send(renderMcpOAuthCallbackPage({
|
|
title,
|
|
message,
|
|
// Browsers only follow custom-protocol links from a user gesture in
|
|
// some configurations, so the page both tries the jump and keeps a
|
|
// visible link as the fallback.
|
|
desktopReturn: startedFromDesktop,
|
|
}));
|
|
};
|
|
|
|
if (providerError) {
|
|
return finish(400, {
|
|
title: 'Authorization Failed',
|
|
message: providerErrorDescription || providerError,
|
|
});
|
|
}
|
|
if (!code) {
|
|
return finish(400, {
|
|
title: 'Authorization Failed',
|
|
message: 'The provider did not return an authorization code. Start authorization again from MCP Settings.',
|
|
});
|
|
}
|
|
if (!context?.name) {
|
|
return finish(400, {
|
|
title: 'Authorization Failed',
|
|
message: 'This authorization session has expired or is unknown to the running app. Return to OpenChamber and click Authorize again.',
|
|
});
|
|
}
|
|
|
|
try {
|
|
const callbackUrl = new URL(buildOpenCodeUrl(`/mcp/${encodeURIComponent(context.name)}/auth/callback`, ''));
|
|
if (context.directory) callbackUrl.searchParams.set('directory', context.directory);
|
|
const upstream = await fetch(callbackUrl, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...getOpenCodeAuthHeaders() },
|
|
body: JSON.stringify({ code }),
|
|
});
|
|
if (!upstream.ok) {
|
|
const payload = await upstream.json().catch(() => null);
|
|
return finish(502, {
|
|
title: 'Authorization Failed',
|
|
message: payload?.error || payload?.message || `OpenCode rejected the authorization code (${upstream.status}). Start authorization again from MCP Settings.`,
|
|
});
|
|
}
|
|
return finish(200, {
|
|
title: 'Authorization Complete',
|
|
message: 'You can close this tab and return to OpenChamber.',
|
|
});
|
|
} catch (error) {
|
|
return finish(502, {
|
|
title: 'Authorization Failed',
|
|
message: error?.message || 'Failed to complete MCP authorization.',
|
|
});
|
|
}
|
|
});
|
|
|
|
app.get('/api/provider/:providerId/source', async (req, res) => {
|
|
try {
|
|
const { providerId } = req.params;
|
|
if (!providerId) {
|
|
return res.status(400).json({ error: 'Provider ID is required' });
|
|
}
|
|
|
|
const headerDirectory = typeof req.get === 'function' ? req.get('x-opencode-directory') : null;
|
|
const queryDirectory = Array.isArray(req.query?.directory)
|
|
? req.query.directory[0]
|
|
: req.query?.directory;
|
|
const requestedDirectory = headerDirectory || queryDirectory || null;
|
|
|
|
let directory = null;
|
|
const resolved = await resolveProjectDirectory(req);
|
|
if (resolved.directory) {
|
|
directory = resolved.directory;
|
|
} else if (requestedDirectory) {
|
|
return res.status(400).json({ error: resolved.error });
|
|
}
|
|
|
|
const sources = getProviderSources(providerId, directory);
|
|
const { getProviderAuth } = await getAuthLibrary();
|
|
const auth = getProviderAuth(providerId);
|
|
sources.sources.auth.exists = providerId === 'claude-code'
|
|
? getClaudeCliAuthStatus().connected
|
|
: Boolean(auth);
|
|
|
|
return res.json({
|
|
providerId,
|
|
sources: sources.sources,
|
|
});
|
|
} catch (error) {
|
|
console.error('Failed to get provider sources:', error);
|
|
return res.status(500).json({ error: error.message || 'Failed to get provider sources' });
|
|
}
|
|
});
|
|
|
|
app.put('/api/provider', async (req, res) => {
|
|
try {
|
|
const providerID = typeof req.body?.providerID === 'string'
|
|
? req.body.providerID.trim()
|
|
: (typeof req.body?.providerId === 'string' ? req.body.providerId.trim() : '');
|
|
const config = req.body?.config;
|
|
const scope = typeof req.body?.scope === 'string' ? req.body.scope : 'user';
|
|
|
|
if (!providerID) {
|
|
return res.status(400).json({ error: 'Provider ID is required' });
|
|
}
|
|
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
|
return res.status(400).json({ error: 'Provider config is required' });
|
|
}
|
|
if (scope !== 'user' && scope !== 'project' && scope !== 'custom') {
|
|
return res.status(400).json({ error: 'Invalid scope' });
|
|
}
|
|
|
|
const headerDirectory = typeof req.get === 'function' ? req.get('x-opencode-directory') : null;
|
|
const queryDirectory = Array.isArray(req.query?.directory)
|
|
? req.query.directory[0]
|
|
: req.query?.directory;
|
|
const requestedDirectory = headerDirectory || queryDirectory || null;
|
|
|
|
let directory = null;
|
|
if (scope === 'project' || requestedDirectory) {
|
|
const resolved = await resolveProjectDirectory(req);
|
|
if (!resolved.directory) {
|
|
return res.status(400).json({ error: resolved.error || 'Working directory is required' });
|
|
}
|
|
directory = resolved.directory;
|
|
} else {
|
|
const resolved = await resolveProjectDirectory(req);
|
|
if (resolved.directory) {
|
|
directory = resolved.directory;
|
|
}
|
|
}
|
|
|
|
const { getProviderAuth } = await getAuthLibrary();
|
|
const hasStoredAuth = Boolean(getProviderAuth(providerID));
|
|
const upsertResult = upsertProviderConfig(providerID, config, directory, scope, { hasStoredAuth });
|
|
|
|
return res.json({
|
|
...buildDeferredRestartResponse(
|
|
`Provider ${providerID} saved. Restart OpenCode to apply.`,
|
|
),
|
|
providerId: upsertResult.providerId,
|
|
path: upsertResult.path,
|
|
config: upsertResult.config,
|
|
});
|
|
} catch (error) {
|
|
const status = typeof error?.statusCode === 'number' ? error.statusCode : 500;
|
|
console.error('Failed to upsert provider config:', error);
|
|
return res.status(status).json({ error: error.message || 'Failed to save provider config' });
|
|
}
|
|
});
|
|
|
|
app.delete('/api/provider/:providerId/auth', async (req, res) => {
|
|
try {
|
|
const { providerId } = req.params;
|
|
if (!providerId) {
|
|
return res.status(400).json({ error: 'Provider ID is required' });
|
|
}
|
|
|
|
const scope = typeof req.query?.scope === 'string' ? req.query.scope : 'auth';
|
|
const headerDirectory = typeof req.get === 'function' ? req.get('x-opencode-directory') : null;
|
|
const queryDirectory = Array.isArray(req.query?.directory)
|
|
? req.query.directory[0]
|
|
: req.query?.directory;
|
|
const requestedDirectory = headerDirectory || queryDirectory || null;
|
|
let directory = null;
|
|
|
|
if (scope === 'project' || requestedDirectory) {
|
|
const resolved = await resolveProjectDirectory(req);
|
|
if (!resolved.directory) {
|
|
return res.status(400).json({ error: resolved.error });
|
|
}
|
|
directory = resolved.directory;
|
|
} else {
|
|
const resolved = await resolveProjectDirectory(req);
|
|
if (resolved.directory) {
|
|
directory = resolved.directory;
|
|
}
|
|
}
|
|
|
|
let removed = false;
|
|
if (scope === 'auth') {
|
|
const { removeProviderAuth } = await getAuthLibrary();
|
|
removed = removeProviderAuth(providerId);
|
|
} else if (scope === 'user' || scope === 'project' || scope === 'custom') {
|
|
removed = removeProviderConfig(providerId, directory, scope);
|
|
} else if (scope === 'all') {
|
|
const { removeProviderAuth } = await getAuthLibrary();
|
|
const authRemoved = removeProviderAuth(providerId);
|
|
const userRemoved = removeProviderConfig(providerId, directory, 'user');
|
|
const projectRemoved = directory ? removeProviderConfig(providerId, directory, 'project') : false;
|
|
const customRemoved = removeProviderConfig(providerId, directory, 'custom');
|
|
removed = authRemoved || userRemoved || projectRemoved || customRemoved;
|
|
} else {
|
|
return res.status(400).json({ error: 'Invalid scope' });
|
|
}
|
|
|
|
if (removed) {
|
|
return res.json({
|
|
success: true,
|
|
removed,
|
|
...buildDeferredRestartResponse('Provider disconnected successfully. Restart OpenCode to apply.'),
|
|
});
|
|
}
|
|
|
|
return res.json({
|
|
success: true,
|
|
removed,
|
|
requiresReload: false,
|
|
message: 'Provider was not connected',
|
|
});
|
|
} catch (error) {
|
|
console.error('Failed to disconnect provider:', error);
|
|
return res.status(500).json({ error: error.message || 'Failed to disconnect provider' });
|
|
}
|
|
});
|
|
|
|
app.post('/api/opencode/directory', async (req, res) => {
|
|
try {
|
|
const requestedPath = typeof req.body?.path === 'string' ? req.body.path.trim() : '';
|
|
if (!requestedPath) {
|
|
return res.status(400).json({ error: 'Path is required' });
|
|
}
|
|
|
|
if (req.body?.create === true) {
|
|
await fsPromises.mkdir(path.resolve(requestedPath), { recursive: true });
|
|
}
|
|
|
|
const validated = await validateDirectoryPath(requestedPath);
|
|
if (!validated.ok) {
|
|
return res.status(400).json({ error: validated.error });
|
|
}
|
|
|
|
const resolvedPath = validated.directory;
|
|
const currentSettings = await readSettingsFromDisk();
|
|
const existingProjects = sanitizeProjects(currentSettings.projects) || [];
|
|
const existing = existingProjects.find((project) => project.path === resolvedPath) || null;
|
|
|
|
const nextProjects = existing
|
|
? existingProjects
|
|
: [
|
|
...existingProjects,
|
|
{
|
|
id: createProjectIdFromPath(resolvedPath),
|
|
path: resolvedPath,
|
|
addedAt: Date.now(),
|
|
lastOpenedAt: Date.now(),
|
|
},
|
|
];
|
|
|
|
const activeProjectId = existing ? existing.id : nextProjects[nextProjects.length - 1].id;
|
|
|
|
const updated = await persistSettings({
|
|
projects: nextProjects,
|
|
activeProjectId,
|
|
lastDirectory: resolvedPath,
|
|
});
|
|
|
|
return res.json({
|
|
success: true,
|
|
restarted: false,
|
|
path: resolvedPath,
|
|
settings: updated,
|
|
});
|
|
} catch (error) {
|
|
console.error('Failed to update OpenCode working directory:', error);
|
|
return res.status(500).json({ error: error.message || 'Failed to update working directory' });
|
|
}
|
|
});
|
|
|
|
// Behavior / Global AGENTS.md endpoints
|
|
const AGENTS_MD_PATH = path.join(OPENCODE_CONFIG_DIR, 'AGENTS.md');
|
|
const MAX_BEHAVIOR_PROMPT_SIZE = 1024 * 1024; // 1 MB
|
|
|
|
app.get('/api/behavior/agents-md', async (_req, res) => {
|
|
try {
|
|
try {
|
|
await fs.promises.access(AGENTS_MD_PATH);
|
|
} catch {
|
|
return res.json({ content: '', exists: false, path: AGENTS_MD_PATH });
|
|
}
|
|
const content = await fs.promises.readFile(AGENTS_MD_PATH, 'utf8');
|
|
return res.json({ content, exists: true, path: AGENTS_MD_PATH });
|
|
} catch (error) {
|
|
console.error('Failed to read AGENTS.md:', error);
|
|
return res.status(500).json({ error: 'Failed to read AGENTS.md' });
|
|
}
|
|
});
|
|
|
|
app.put('/api/behavior/agents-md', async (req, res) => {
|
|
try {
|
|
const content = typeof req.body?.content === 'string' ? req.body.content : '';
|
|
|
|
if (content.length > MAX_BEHAVIOR_PROMPT_SIZE) {
|
|
return res.status(413).json({ error: `Content exceeds maximum size of ${MAX_BEHAVIOR_PROMPT_SIZE} bytes` });
|
|
}
|
|
|
|
// Ensure parent directory exists
|
|
const parentDir = path.dirname(AGENTS_MD_PATH);
|
|
try {
|
|
await fs.promises.access(parentDir);
|
|
} catch {
|
|
await fs.promises.mkdir(parentDir, { recursive: true });
|
|
}
|
|
|
|
await fs.promises.writeFile(AGENTS_MD_PATH, content, 'utf8');
|
|
|
|
return res.json(buildDeferredRestartResponse(
|
|
'AGENTS.md saved. Restart OpenCode to apply.',
|
|
));
|
|
} catch (error) {
|
|
console.error('Failed to write AGENTS.md:', error);
|
|
return res.status(500).json({ error: error.message || 'Failed to write AGENTS.md' });
|
|
}
|
|
});
|
|
};
|