* 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.
858 lines
35 KiB
TypeScript
858 lines
35 KiB
TypeScript
import type { DesktopSettings } from '@/lib/desktop';
|
|
import { useUIStore } from '@/stores/useUIStore';
|
|
import { loadAppearancePreferences, applyAppearancePreferences } from '@/lib/appearancePersistence';
|
|
import { getRegisteredRuntimeAPIs } from '@/contexts/runtimeAPIRegistry';
|
|
import { setStoredMobileKeyboardMode } from '@/lib/mobileKeyboardMode';
|
|
import { runtimeFetch } from '@/lib/runtime-fetch';
|
|
import { isCapacitorApp } from '@/lib/platform';
|
|
import { getRuntimeKey, subscribeRuntimeEndpointChanged, subscribeRuntimeEndpointWillChange } from '@/lib/runtime-switch';
|
|
import { useSessionDisplayStore } from '@/stores/useSessionDisplayStore';
|
|
import {
|
|
applySettingsToStores,
|
|
isDeviceSettingsKey,
|
|
isWritableSettingsKey,
|
|
MIRRORED_KEYS,
|
|
parseSettingsDocument,
|
|
SETTINGS_KEYS,
|
|
} from '@/lib/settings/registry';
|
|
import { SETTINGS_SURFACE_QUERY, getSettingsSurface } from '@/lib/settings/surface';
|
|
|
|
export const applyPersistedHomeDirectoryToWindow = (homeDirectory: string): void => {
|
|
if (typeof window === 'undefined') {
|
|
return;
|
|
}
|
|
if (typeof window.__OPENCHAMBER_HOME__ === 'string' && window.__OPENCHAMBER_HOME__.length > 0) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
window.__OPENCHAMBER_HOME__ = homeDirectory;
|
|
} catch {
|
|
/* read-only contextBridge property — leave preload-seeded value */
|
|
}
|
|
};
|
|
|
|
const SETTINGS_MIRROR_INDEX_KEY = 'openchamber.settingsMirror.v2.index';
|
|
// Set once a runtime's device fields have been read from the server document
|
|
// (installs that predate the settings split still carry them there). After
|
|
// that the local store is the only owner and the server copy is ignored.
|
|
const DEVICE_SEED_KEY_PREFIX = 'openchamber.deviceSeeded.v1:';
|
|
const getDeviceSeedStorageKey = (runtimeKey: string): string => `${DEVICE_SEED_KEY_PREFIX}${encodeURIComponent(runtimeKey)}`;
|
|
|
|
/**
|
|
* The part of a server document this window may apply: everything but device
|
|
* fields, plus the device fields exactly once per runtime as a migration seed.
|
|
*/
|
|
const withoutStaleDeviceFields = (settings: DesktopSettings, runtimeKey: string): DesktopSettings => {
|
|
const seedKey = getDeviceSeedStorageKey(runtimeKey);
|
|
let seedDevice = false;
|
|
try {
|
|
seedDevice = localStorage.getItem(seedKey) === null;
|
|
if (seedDevice) localStorage.setItem(seedKey, String(Date.now()));
|
|
} catch {
|
|
seedDevice = false;
|
|
}
|
|
if (seedDevice) return settings;
|
|
const next: DesktopSettings = {};
|
|
for (const key of SETTINGS_KEYS) {
|
|
if (settings[key] === undefined || isDeviceSettingsKey(key)) continue;
|
|
Object.assign(next, { [key]: settings[key] });
|
|
}
|
|
return next;
|
|
};
|
|
const SETTINGS_MIRROR_KEY_PREFIX = 'openchamber.settingsMirror.v2:';
|
|
const MAX_SETTINGS_MIRROR_RUNTIMES = 5;
|
|
|
|
export const getRuntimeSettingsMirrorStorageKey = (runtimeKey: string): string =>
|
|
`${SETTINGS_MIRROR_KEY_PREFIX}${encodeURIComponent(runtimeKey)}`;
|
|
|
|
const setOrRemoveLocalStorage = (key: string, value: string | null): void => {
|
|
if (value === null) {
|
|
localStorage.removeItem(key);
|
|
} else {
|
|
localStorage.setItem(key, value);
|
|
}
|
|
};
|
|
|
|
const persistRuntimeSettingsMirror = (settings: DesktopSettings, runtimeKey: string): void => {
|
|
// Every user-owned field the server holds for this runtime, so a later
|
|
// phase can serve the profile from the mirror; secrets and computed flags
|
|
// never land in browser storage.
|
|
const mirror: DesktopSettings = {};
|
|
for (const key of MIRRORED_KEYS) {
|
|
if (settings[key] !== undefined) Object.assign(mirror, { [key]: settings[key] });
|
|
}
|
|
localStorage.setItem(getRuntimeSettingsMirrorStorageKey(runtimeKey), JSON.stringify(mirror));
|
|
|
|
let previous: string[] = [];
|
|
try {
|
|
const parsed = JSON.parse(localStorage.getItem(SETTINGS_MIRROR_INDEX_KEY) ?? '[]') as unknown;
|
|
if (Array.isArray(parsed)) previous = parsed.filter((entry): entry is string => typeof entry === 'string');
|
|
} catch {
|
|
previous = [];
|
|
}
|
|
const runtimes = [runtimeKey, ...previous.filter((entry) => entry !== runtimeKey)].slice(0, MAX_SETTINGS_MIRROR_RUNTIMES);
|
|
for (const staleRuntime of previous) {
|
|
if (!runtimes.includes(staleRuntime)) localStorage.removeItem(getRuntimeSettingsMirrorStorageKey(staleRuntime));
|
|
}
|
|
localStorage.setItem(SETTINGS_MIRROR_INDEX_KEY, JSON.stringify(runtimes));
|
|
};
|
|
|
|
const persistToLocalStorage = (settings: DesktopSettings) => {
|
|
if (typeof window === 'undefined') {
|
|
return;
|
|
}
|
|
|
|
persistRuntimeSettingsMirror(settings, getRuntimeKey());
|
|
setOrRemoveLocalStorage('lastDirectory', settings.lastDirectory || null);
|
|
if (settings.homeDirectory) {
|
|
localStorage.setItem('homeDirectory', settings.homeDirectory);
|
|
applyPersistedHomeDirectoryToWindow(settings.homeDirectory);
|
|
} else {
|
|
localStorage.removeItem('homeDirectory');
|
|
}
|
|
if (Array.isArray(settings.projects) && settings.projects.length > 0) {
|
|
localStorage.setItem('projects', JSON.stringify(settings.projects));
|
|
} else {
|
|
localStorage.removeItem('projects');
|
|
}
|
|
if (settings.activeProjectId) {
|
|
localStorage.setItem('activeProjectId', settings.activeProjectId);
|
|
} else {
|
|
localStorage.removeItem('activeProjectId');
|
|
}
|
|
if (Array.isArray(settings.pinnedDirectories) && settings.pinnedDirectories.length > 0) {
|
|
localStorage.setItem('pinnedDirectories', JSON.stringify(settings.pinnedDirectories));
|
|
} else {
|
|
localStorage.removeItem('pinnedDirectories');
|
|
}
|
|
|
|
if (Array.isArray(settings.projects) && settings.projects.length > 0) {
|
|
const collapsed = settings.projects
|
|
.filter((project) => project.sidebarCollapsed === true)
|
|
.map((project) => project.id)
|
|
.filter((id): id is string => typeof id === 'string' && id.length > 0);
|
|
if (collapsed.length > 0) {
|
|
localStorage.setItem('oc.sessions.projectCollapse', JSON.stringify(collapsed));
|
|
} else {
|
|
localStorage.removeItem('oc.sessions.projectCollapse');
|
|
}
|
|
} else {
|
|
localStorage.removeItem('oc.sessions.projectCollapse');
|
|
}
|
|
if (typeof settings.gitmojiEnabled === 'boolean') {
|
|
localStorage.setItem('gitmojiEnabled', String(settings.gitmojiEnabled));
|
|
} else {
|
|
localStorage.removeItem('gitmojiEnabled');
|
|
}
|
|
if (typeof settings.directoryShowHidden === 'boolean') {
|
|
localStorage.setItem('directoryTreeShowHidden', settings.directoryShowHidden ? 'true' : 'false');
|
|
} else {
|
|
localStorage.removeItem('directoryTreeShowHidden');
|
|
}
|
|
if (typeof settings.filesViewShowGitignored === 'boolean') {
|
|
localStorage.setItem('filesViewShowGitignored', settings.filesViewShowGitignored ? 'true' : 'false');
|
|
} else {
|
|
localStorage.removeItem('filesViewShowGitignored');
|
|
}
|
|
setOrRemoveLocalStorage('openInAppId', typeof settings.openInAppId === 'string' && settings.openInAppId.length > 0 ? settings.openInAppId : null);
|
|
if (typeof settings.pwaAppName === 'string') {
|
|
const normalized = settings.pwaAppName.trim().replace(/\s+/g, ' ').slice(0, 64);
|
|
if (normalized.length > 0) {
|
|
localStorage.setItem('openchamber.pwaName', normalized);
|
|
} else {
|
|
localStorage.removeItem('openchamber.pwaName');
|
|
}
|
|
} else {
|
|
localStorage.removeItem('openchamber.pwaName');
|
|
}
|
|
setStoredMobileKeyboardMode(settings.mobileKeyboardMode);
|
|
if (typeof settings.openCodeUpdateToastDismissedVersion === 'string') {
|
|
const version = settings.openCodeUpdateToastDismissedVersion.trim();
|
|
if (version) {
|
|
localStorage.setItem('opencode-update-toast-dismissed-version', version);
|
|
} else {
|
|
localStorage.removeItem('opencode-update-toast-dismissed-version');
|
|
}
|
|
} else {
|
|
localStorage.removeItem('opencode-update-toast-dismissed-version');
|
|
}
|
|
if (typeof settings.dictationEnabled === 'boolean') {
|
|
localStorage.setItem('dictationEnabled', String(settings.dictationEnabled));
|
|
} else {
|
|
localStorage.removeItem('dictationEnabled');
|
|
}
|
|
if (settings.sttProvider === 'local' || settings.sttProvider === 'openai-compatible') {
|
|
localStorage.setItem('sttProvider', settings.sttProvider);
|
|
} else {
|
|
localStorage.removeItem('sttProvider');
|
|
}
|
|
setOrRemoveLocalStorage('sttServerUrl', typeof settings.sttServerUrl === 'string' ? settings.sttServerUrl : null);
|
|
setOrRemoveLocalStorage('sttModel', typeof settings.sttModel === 'string' ? settings.sttModel : null);
|
|
setOrRemoveLocalStorage('sttLocalModel', typeof settings.sttLocalModel === 'string' ? settings.sttLocalModel : null);
|
|
setOrRemoveLocalStorage('sttLanguage', typeof settings.sttLanguage === 'string' ? settings.sttLanguage : null);
|
|
};
|
|
|
|
export interface SettingsSyncedDetail {
|
|
settings: DesktopSettings;
|
|
/** Whether listeners may adopt authoritative state that this window owns a
|
|
live copy of (workspace pointers, theme). True only for a bootstrap-grade
|
|
sync: the settings document is shared by every window of this server, so
|
|
a mid-session reconciliation adopting them would hijack this window's
|
|
choices with another window's. Every settings save echoes the full
|
|
document back as a sync event with bootstrap=false — the echo itself is
|
|
not filtered; listeners gate their adoption on this flag and keep their
|
|
live state for the fields they own. */
|
|
bootstrap: boolean;
|
|
/** Whether this sync may replace this window's theme preferences. VS Code
|
|
settings broadcasts remain bootstrap-grade for shared workspace pointers,
|
|
but must not copy one webview's theme into another webview. */
|
|
adoptTheme: boolean;
|
|
}
|
|
|
|
const dispatchSettingsSynced = (settings: DesktopSettings, bootstrap: boolean, adoptTheme = bootstrap): void => {
|
|
if (typeof window === 'undefined') {
|
|
return;
|
|
}
|
|
window.dispatchEvent(new CustomEvent<SettingsSyncedDetail>('openchamber:settings-synced', {
|
|
detail: { settings, bootstrap, adoptTheme },
|
|
}));
|
|
};
|
|
|
|
type SettingsSaveState = 'idle' | 'saving' | 'error';
|
|
|
|
let _settingsSaveState: SettingsSaveState = 'idle';
|
|
let _settingsSaveStateResetTimer: ReturnType<typeof setTimeout> | null = null;
|
|
const _settingsSaveStateListeners = new Set<() => void>();
|
|
|
|
export const getSettingsSaveState = (): SettingsSaveState => _settingsSaveState;
|
|
|
|
export const subscribeToSettingsSaveState = (listener: () => void): (() => void) => {
|
|
_settingsSaveStateListeners.add(listener);
|
|
return () => _settingsSaveStateListeners.delete(listener);
|
|
};
|
|
|
|
/**
|
|
* Drive the shared settings save indicator from pages that persist through
|
|
* their own APIs instead of updateDesktopSettings. 'error' resets to idle.
|
|
*/
|
|
export const reportSettingsSaveState = (state: 'saving' | 'saved' | 'error'): void => {
|
|
dispatchSettingsSaveState(state);
|
|
};
|
|
|
|
const dispatchSettingsSaveState = (state: 'saving' | 'saved' | 'error'): void => {
|
|
if (_settingsSaveStateResetTimer) {
|
|
clearTimeout(_settingsSaveStateResetTimer);
|
|
_settingsSaveStateResetTimer = null;
|
|
}
|
|
|
|
// Quiet indicator: success is the normal case and renders nothing ('saved' → idle);
|
|
// only in-flight saves and failures surface in the UI.
|
|
const nextState: SettingsSaveState = state === 'saved' ? 'idle' : state;
|
|
if (nextState !== _settingsSaveState) {
|
|
_settingsSaveState = nextState;
|
|
_settingsSaveStateListeners.forEach((listener) => listener());
|
|
}
|
|
|
|
if (nextState === 'error') {
|
|
_settingsSaveStateResetTimer = setTimeout(() => dispatchSettingsSaveState('saved'), 6000);
|
|
}
|
|
|
|
if (typeof window === 'undefined') {
|
|
return;
|
|
}
|
|
window.dispatchEvent(new CustomEvent<'saving' | 'saved' | 'error'>('openchamber:settings-save-state', { detail: state }));
|
|
};
|
|
|
|
type PersistApi = {
|
|
hasHydrated?: () => boolean;
|
|
onFinishHydration?: (callback: () => void) => (() => void) | undefined;
|
|
};
|
|
|
|
const getPersistApi = (): PersistApi | undefined => {
|
|
const candidate = useUIStore.persist;
|
|
if (candidate && typeof candidate === 'object') {
|
|
return candidate;
|
|
}
|
|
return undefined;
|
|
};
|
|
|
|
const getRuntimeSettingsAPI = () => getRegisteredRuntimeAPIs()?.settings ?? null;
|
|
|
|
const settingsEndpointForSurface = (): string => `/api/config/settings?${SETTINGS_SURFACE_QUERY}=${getSettingsSurface()}`;
|
|
|
|
/** Copy a parsed snapshot into the live stores. Omitted keys stay as they are. */
|
|
const applyDesktopUiPreferences = (settings: DesktopSettings): void => {
|
|
applySettingsToStores(settings);
|
|
};
|
|
|
|
/** Parse an untrusted settings document at the boundary; `null` when it is not an object at all. */
|
|
const sanitizeWebSettings = (payload: unknown): DesktopSettings | null => parseSettingsDocument(payload);
|
|
|
|
type SettingsRuntimeContext = { runtimeKey: string; generation: number };
|
|
/** Whether a settings write reached its store. A no-op (nothing to send) counts as ok. */
|
|
export type SettingsWriteResult = { ok: boolean };
|
|
type SettingsMutation = { revision: number; changes: Partial<DesktopSettings> };
|
|
type SettingsOperation = { revision: number };
|
|
|
|
class SettingsMutationTracker {
|
|
private revision = 0;
|
|
private mutations: SettingsMutation[] = [];
|
|
private operations = new Set<SettingsOperation>();
|
|
|
|
record(changes: Partial<DesktopSettings>): number {
|
|
this.revision += 1;
|
|
if (this.operations.size > 0) {
|
|
const latest = this.mutations.at(-1);
|
|
// A new segment is only needed when an operation started after the last one.
|
|
const crossedOperationBoundary = latest
|
|
? [...this.operations].some((operation) => operation.revision >= latest.revision)
|
|
: true;
|
|
if (latest && !crossedOperationBoundary) {
|
|
latest.revision = this.revision;
|
|
latest.changes = { ...latest.changes, ...changes };
|
|
} else {
|
|
this.mutations.push({ revision: this.revision, changes });
|
|
}
|
|
}
|
|
return this.revision;
|
|
}
|
|
|
|
begin(revision = this.revision): SettingsOperation {
|
|
const operation = { revision };
|
|
this.operations.add(operation);
|
|
return operation;
|
|
}
|
|
|
|
reconcile(settings: DesktopSettings, operation: SettingsOperation): DesktopSettings {
|
|
let reconciled = settings;
|
|
for (const mutation of this.mutations) {
|
|
if (mutation.revision <= operation.revision) continue;
|
|
reconciled = { ...reconciled, ...mutation.changes };
|
|
}
|
|
return reconciled;
|
|
}
|
|
|
|
finish(operation: SettingsOperation): void {
|
|
if (!this.operations.delete(operation)) return;
|
|
if (this.operations.size === 0) {
|
|
this.mutations = [];
|
|
return;
|
|
}
|
|
const oldestRevision = Math.min(...[...this.operations].map(({ revision }) => revision));
|
|
this.mutations = this.mutations.filter((mutation) => mutation.revision > oldestRevision);
|
|
}
|
|
|
|
reset(): void {
|
|
this.mutations = [];
|
|
this.operations.clear();
|
|
}
|
|
}
|
|
|
|
// Short-lived cache + in-flight dedup for settings fetches to avoid repeated GET calls during startup
|
|
let _settingsRuntimeGeneration = 0;
|
|
let _settingsCache: { value: DesktopSettings | null; at: number; context: SettingsRuntimeContext } | null = null;
|
|
// The last value the server was seen holding for each key, for the current
|
|
// runtime. A write whose value equals it is redundant and is dropped before it
|
|
// reaches the wire — this is what turns "the store changed because we adopted
|
|
// the server's value" into zero PUTs instead of an echo (appearanceAutoSave and
|
|
// the model-prefs auto-save both subscribe to the store, not to intent).
|
|
let _serverKnownSettings: Partial<DesktopSettings> = {};
|
|
// True while server values are being copied into the stores. Store
|
|
// subscribers that mirror changes back to the server (appearanceAutoSave,
|
|
// modelPrefsAutoSave) read this to tell "a person changed it" from "we just
|
|
// adopted it" — the second must never become a write.
|
|
let _applyingServerSettings = false;
|
|
|
|
export const isApplyingServerSettings = (): boolean => _applyingServerSettings;
|
|
|
|
const applyServerSettings = (settings: DesktopSettings): void => {
|
|
_applyingServerSettings = true;
|
|
try {
|
|
applyDesktopUiPreferences(settings);
|
|
} finally {
|
|
_applyingServerSettings = false;
|
|
}
|
|
};
|
|
let _settingsInflight: { promise: Promise<DesktopSettings | null>; context: SettingsRuntimeContext } | null = null;
|
|
let _pendingSettingsChanges: Partial<DesktopSettings> | null = null;
|
|
let _pendingSettingsContext: SettingsRuntimeContext | null = null;
|
|
let _settingsFlushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
let _settingsFlushWaiters: Array<(result: SettingsWriteResult) => void> = [];
|
|
let _settingsLifecycleInitialized = false;
|
|
let _pendingSettingsRevision = 0;
|
|
const _settingsMutationTracker = new SettingsMutationTracker();
|
|
const SETTINGS_CACHE_TTL = 2_000; // 2 seconds — covers the startup burst
|
|
const SETTINGS_DEBOUNCE_MS = 200;
|
|
|
|
const captureSettingsRuntimeContext = (): SettingsRuntimeContext => ({
|
|
runtimeKey: getRuntimeKey(),
|
|
generation: _settingsRuntimeGeneration,
|
|
});
|
|
|
|
type SettingsKey = keyof DesktopSettings;
|
|
type SettingsValue = DesktopSettings[SettingsKey];
|
|
|
|
// SAFETY: a Partial<DesktopSettings> here always comes from the typed stores or
|
|
// from `sanitizeWebSettings`, both of which only ever set DesktopSettings keys.
|
|
const settingsKeysOf = (changes: Partial<DesktopSettings>): SettingsKey[] => Object.keys(changes) as SettingsKey[];
|
|
|
|
const isSameSettingValue = (left: SettingsValue | undefined, right: SettingsValue | undefined): boolean => {
|
|
if (left === right) return true;
|
|
if (left === undefined || right === undefined) return false;
|
|
return JSON.stringify(left) === JSON.stringify(right);
|
|
};
|
|
|
|
const rememberServerSettings = (settings: Partial<DesktopSettings>): void => {
|
|
_serverKnownSettings = { ..._serverKnownSettings, ...settings };
|
|
};
|
|
|
|
const forgetServerSettings = (keys: SettingsKey[]): void => {
|
|
const next: Partial<DesktopSettings> = { ..._serverKnownSettings };
|
|
for (const key of keys) delete next[key];
|
|
_serverKnownSettings = next;
|
|
};
|
|
|
|
/** Keys of `changes` whose value differs from what the server is known to hold. */
|
|
const withoutRedundantSettings = (changes: Partial<DesktopSettings>): Partial<DesktopSettings> => {
|
|
const next: Partial<DesktopSettings> = {};
|
|
for (const key of settingsKeysOf(changes)) {
|
|
if (isSameSettingValue(changes[key], _serverKnownSettings[key])) continue;
|
|
Object.assign(next, { [key]: changes[key] });
|
|
}
|
|
return next;
|
|
};
|
|
|
|
const isSameSettingsRuntimeContext = (left: SettingsRuntimeContext, right: SettingsRuntimeContext): boolean => (
|
|
left.runtimeKey === right.runtimeKey && left.generation === right.generation
|
|
);
|
|
|
|
const isSettingsRuntimeContextCurrent = (context: SettingsRuntimeContext): boolean => (
|
|
context.generation === _settingsRuntimeGeneration && context.runtimeKey === getRuntimeKey()
|
|
);
|
|
|
|
// Best-effort flush of the pending debounced settings write at a lifecycle
|
|
// boundary. Clearing the timer before flushing means the write happens exactly
|
|
// once — the flush consumes the pending changes, so a timer that already fired
|
|
// cannot double-write. A hard process kill (crash, task-manager kill) can
|
|
// still lose the in-flight request; this narrows the loss window to the
|
|
// request itself instead of the whole debounce interval (#2197).
|
|
const flushPendingSettingsBeforeSuspend = (): void => {
|
|
if (!_pendingSettingsChanges) return;
|
|
if (_settingsFlushTimer) {
|
|
clearTimeout(_settingsFlushTimer);
|
|
_settingsFlushTimer = null;
|
|
}
|
|
// `keepalive` is what makes this flush actually land: a plain fetch started
|
|
// from pagehide/beforeunload is cancelled with the document. Settings payloads
|
|
// are a few KB, far under the 64 KB keepalive budget. `navigator.sendBeacon`
|
|
// is not an option here — it cannot carry the runtime bearer header, so the
|
|
// write would be rejected as unauthenticated.
|
|
void _flushSettingsUpdate({ keepalive: true });
|
|
};
|
|
|
|
const ensureSettingsRuntimeLifecycle = (): void => {
|
|
if (_settingsLifecycleInitialized || typeof window === 'undefined') return;
|
|
_settingsLifecycleInitialized = true;
|
|
|
|
subscribeRuntimeEndpointWillChange((detail) => {
|
|
if (detail.runtimeKey === detail.previousRuntimeKey) return;
|
|
if (_settingsFlushTimer) clearTimeout(_settingsFlushTimer);
|
|
if (_pendingSettingsChanges) void _flushSettingsUpdate();
|
|
});
|
|
subscribeRuntimeEndpointChanged((detail) => {
|
|
if (detail.runtimeKey === detail.previousRuntimeKey) return;
|
|
_settingsRuntimeGeneration += 1;
|
|
_settingsMutationTracker.reset();
|
|
_pendingSettingsRevision = 0;
|
|
_settingsCache = null;
|
|
_settingsInflight = null;
|
|
_serverKnownSettings = {};
|
|
});
|
|
|
|
// Mirror the deferred safe-storage lifecycle: without these listeners, a
|
|
// settings change made within SETTINGS_DEBOUNCE_MS of closing the window is
|
|
// silently dropped, and the stale server snapshot wins on next startup.
|
|
try {
|
|
window.addEventListener('pagehide', flushPendingSettingsBeforeSuspend, { capture: true });
|
|
window.addEventListener('beforeunload', flushPendingSettingsBeforeSuspend, { capture: true });
|
|
if (typeof document !== 'undefined') {
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (document.visibilityState === 'hidden') flushPendingSettingsBeforeSuspend();
|
|
});
|
|
document.addEventListener('freeze', flushPendingSettingsBeforeSuspend);
|
|
}
|
|
// Capacitor: iOS/Android suspend the app without firing pagehide or
|
|
// beforeunload, and `visibilitychange` alone is not dependable in a
|
|
// WKWebView. `App.appStateChange` is the authoritative foreground signal on
|
|
// native (same source `usePushVisibilityBeacon` trusts), so flush there too.
|
|
if (isCapacitorApp()) {
|
|
void import('@capacitor/app')
|
|
.then(({ App }) => App.addListener('appStateChange', ({ isActive }) => {
|
|
if (!isActive) flushPendingSettingsBeforeSuspend();
|
|
}))
|
|
.catch(() => undefined);
|
|
}
|
|
} catch {
|
|
// Restricted environments can reject listeners; the debounce timer still flushes.
|
|
}
|
|
};
|
|
|
|
const fetchWebSettings = async (context = captureSettingsRuntimeContext()): Promise<DesktopSettings | null> => {
|
|
ensureSettingsRuntimeLifecycle();
|
|
// Return cached if fresh
|
|
if (_settingsCache && isSameSettingsRuntimeContext(_settingsCache.context, context) && Date.now() - _settingsCache.at < SETTINGS_CACHE_TTL) {
|
|
return _settingsCache.value;
|
|
}
|
|
|
|
// Dedup concurrent calls
|
|
if (_settingsInflight && isSameSettingsRuntimeContext(_settingsInflight.context, context)) return _settingsInflight.promise;
|
|
|
|
const inflight = {
|
|
context,
|
|
promise: (async (): Promise<DesktopSettings | null> => {
|
|
const runtimeSettings = getRuntimeSettingsAPI();
|
|
if (runtimeSettings) {
|
|
try {
|
|
const result = await runtimeSettings.load();
|
|
if (!isSettingsRuntimeContextCurrent(context)) return null;
|
|
const settings = sanitizeWebSettings(result.settings);
|
|
_settingsCache = { value: settings, at: Date.now(), context };
|
|
if (settings) rememberServerSettings(settings);
|
|
return settings;
|
|
} catch (error) {
|
|
if (!isSettingsRuntimeContextCurrent(context)) return null;
|
|
console.warn('Failed to load shared settings from runtime settings API:', error);
|
|
}
|
|
}
|
|
|
|
if (!isSettingsRuntimeContextCurrent(context)) return null;
|
|
try {
|
|
// The surface kind travels as a query parameter, not a header: a header
|
|
// would turn the request into a CORS preflight, which older instances
|
|
// (and the packaged desktop's cross-origin shell) refuse.
|
|
const response = await runtimeFetch(settingsEndpointForSurface(), {
|
|
method: 'GET',
|
|
headers: { Accept: 'application/json' },
|
|
});
|
|
if (!isSettingsRuntimeContextCurrent(context)) return null;
|
|
if (!response.ok) {
|
|
return null;
|
|
}
|
|
const data = await response.json().catch(() => null);
|
|
if (!isSettingsRuntimeContextCurrent(context)) return null;
|
|
const settings = sanitizeWebSettings(data);
|
|
_settingsCache = { value: settings, at: Date.now(), context };
|
|
if (settings) rememberServerSettings(settings);
|
|
return settings;
|
|
} catch (error) {
|
|
if (!isSettingsRuntimeContextCurrent(context)) return null;
|
|
console.warn('Failed to load shared settings from server:', error);
|
|
return null;
|
|
}
|
|
})(),
|
|
};
|
|
_settingsInflight = inflight;
|
|
void inflight.promise.finally(() => {
|
|
if (_settingsInflight === inflight) _settingsInflight = null;
|
|
});
|
|
|
|
return inflight.promise;
|
|
};
|
|
|
|
/** Forget everything cached about the server document: the GET cache and the
|
|
* last-known per-key values used to drop redundant writes. */
|
|
export const invalidateSettingsCache = (): void => {
|
|
_settingsCache = null;
|
|
_serverKnownSettings = {};
|
|
};
|
|
|
|
export const syncDesktopSettings = async (options?: { bootstrap?: boolean; adoptTheme?: boolean }): Promise<void> => {
|
|
const bootstrap = options?.bootstrap !== false;
|
|
const adoptTheme = options?.adoptTheme ?? bootstrap;
|
|
if (typeof window === 'undefined') {
|
|
return;
|
|
}
|
|
ensureSettingsRuntimeLifecycle();
|
|
const context = captureSettingsRuntimeContext();
|
|
const operation = _settingsMutationTracker.begin();
|
|
|
|
const persistApis = [getPersistApi(), useSessionDisplayStore.persist];
|
|
|
|
// Wait for Zustand persist hydration before applying server settings.
|
|
// Otherwise `set()`-calls race with hydration: we set X, then hydration
|
|
// reads localStorage and overwrites back to the persisted value.
|
|
const waitForPersistHydration = (persistApi: PersistApi | undefined): Promise<void> => {
|
|
if (!persistApi?.hasHydrated || persistApi.hasHydrated()) {
|
|
return Promise.resolve();
|
|
}
|
|
if (!persistApi.onFinishHydration) {
|
|
return Promise.resolve();
|
|
}
|
|
return new Promise<void>((resolve) => {
|
|
let settled = false;
|
|
const finish = () => {
|
|
if (settled) return;
|
|
settled = true;
|
|
resolve();
|
|
};
|
|
const unsubscribe = persistApi.onFinishHydration!(() => {
|
|
unsubscribe?.();
|
|
finish();
|
|
});
|
|
// Guard: hydration may have flipped to true between the hasHydrated
|
|
// check and the onFinishHydration subscription — resolve immediately.
|
|
if (persistApi.hasHydrated?.()) finish();
|
|
});
|
|
};
|
|
const waitForHydration = (): Promise<void> => Promise.all(
|
|
persistApis.map(waitForPersistHydration),
|
|
).then(() => undefined);
|
|
|
|
// Each step is wrapped in try/catch so a failure in one side-effect (e.g.
|
|
// a TypeError from writing to a contextBridge-protected global) doesn't
|
|
// prevent server settings from reaching the Zustand store.
|
|
// Local changes sitting in the debounce buffer are not yet tracked as
|
|
// mutations (record() only stores while a request is in flight), so a GET
|
|
// racing the debounce window would briefly revert them. Reapply the
|
|
// pending buffer over every reconciled result.
|
|
const overlayPendingChanges = (settings: DesktopSettings): DesktopSettings => {
|
|
if (!_pendingSettingsChanges || !_pendingSettingsContext) return settings;
|
|
if (!isSettingsRuntimeContextCurrent(_pendingSettingsContext)) return settings;
|
|
return { ...settings, ..._pendingSettingsChanges };
|
|
};
|
|
|
|
const applySettings = async (loadedSettings: DesktopSettings) => {
|
|
if (!isSettingsRuntimeContextCurrent(context)) return;
|
|
let settings = overlayPendingChanges(_settingsMutationTracker.reconcile(loadedSettings, operation));
|
|
await waitForHydration();
|
|
if (!isSettingsRuntimeContextCurrent(context)) return;
|
|
settings = withoutStaleDeviceFields(
|
|
overlayPendingChanges(_settingsMutationTracker.reconcile(loadedSettings, operation)),
|
|
context.runtimeKey,
|
|
);
|
|
// Keys the server omits are "unset", not "reset": this window keeps
|
|
// whatever it already holds for them and nothing is written back. A
|
|
// bootstrap therefore never seeds the server from local state — a write
|
|
// only ever carries a change a person made in this window.
|
|
try {
|
|
persistToLocalStorage(settings);
|
|
} catch (error) {
|
|
console.warn('persistToLocalStorage failed:', error);
|
|
}
|
|
try {
|
|
applyServerSettings(settings);
|
|
} catch (error) {
|
|
console.warn('applyDesktopUiPreferences failed:', error);
|
|
}
|
|
|
|
dispatchSettingsSynced(settings, bootstrap, adoptTheme);
|
|
};
|
|
|
|
try {
|
|
const webSettings = await fetchWebSettings(context);
|
|
if (webSettings && isSettingsRuntimeContextCurrent(context)) {
|
|
await applySettings(webSettings);
|
|
}
|
|
} catch (error) {
|
|
console.warn('Failed to synchronise settings:', error);
|
|
} finally {
|
|
_settingsMutationTracker.finish(operation);
|
|
}
|
|
};
|
|
|
|
// Coalesce rapid updateDesktopSettings calls into a single PUT
|
|
// `keepalive` is set only on the lifecycle-suspend path, where the document may
|
|
// be torn down mid-request; the ordinary debounced write uses a plain fetch.
|
|
async function _flushSettingsUpdate({ keepalive = false }: { keepalive?: boolean } = {}): Promise<void> {
|
|
let ok = false;
|
|
const changes = _pendingSettingsChanges;
|
|
const context = _pendingSettingsContext;
|
|
const revision = _pendingSettingsRevision;
|
|
const waiters = _settingsFlushWaiters;
|
|
_pendingSettingsChanges = null;
|
|
_pendingSettingsContext = null;
|
|
_pendingSettingsRevision = 0;
|
|
_settingsFlushTimer = null;
|
|
_settingsFlushWaiters = [];
|
|
try {
|
|
if (!changes || !context || Object.keys(changes).length === 0 || !isSettingsRuntimeContextCurrent(context)) {
|
|
// Nothing will be written — clear any pending "Saving…" indicator.
|
|
ok = true;
|
|
dispatchSettingsSaveState('saved');
|
|
return;
|
|
}
|
|
const operation = _settingsMutationTracker.begin(revision);
|
|
// Assume the merge lands so a same-value write arriving mid-flight is not
|
|
// sent twice; a failed request forgets these keys so a retry goes through.
|
|
rememberServerSettings(changes);
|
|
const forgetSentSettings = () => forgetServerSettings(settingsKeysOf(changes));
|
|
|
|
try {
|
|
const runtimeSettings = getRuntimeSettingsAPI();
|
|
if (runtimeSettings) {
|
|
try {
|
|
// The runtime API hands back whatever the bridge or server returned;
|
|
// it is parsed here like any other boundary payload.
|
|
const updated = sanitizeWebSettings(await runtimeSettings.save(changes));
|
|
if (!isSettingsRuntimeContextCurrent(context)) return;
|
|
if (updated) {
|
|
rememberServerSettings(updated);
|
|
const reconciled = _settingsMutationTracker.reconcile(updated, operation);
|
|
applyServerSettings(reconciled);
|
|
dispatchSettingsSynced(reconciled, false);
|
|
_settingsCache = null;
|
|
}
|
|
if (!updated) forgetSentSettings();
|
|
ok = Boolean(updated);
|
|
dispatchSettingsSaveState(updated ? 'saved' : 'error');
|
|
return;
|
|
} catch (error) {
|
|
if (!isSettingsRuntimeContextCurrent(context)) return;
|
|
console.warn('Failed to update settings via runtime settings API:', error);
|
|
}
|
|
}
|
|
|
|
if (!isSettingsRuntimeContextCurrent(context)) return;
|
|
try {
|
|
const response = await runtimeFetch(settingsEndpointForSurface(), {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Accept: 'application/json',
|
|
},
|
|
body: JSON.stringify(changes),
|
|
keepalive,
|
|
});
|
|
|
|
if (!isSettingsRuntimeContextCurrent(context)) return;
|
|
if (!response.ok) {
|
|
console.warn('Failed to update shared settings via API:', response.status, response.statusText);
|
|
forgetSentSettings();
|
|
dispatchSettingsSaveState('error');
|
|
return;
|
|
}
|
|
|
|
const updated = sanitizeWebSettings(await response.json().catch(() => null));
|
|
if (!isSettingsRuntimeContextCurrent(context)) return;
|
|
if (updated) {
|
|
rememberServerSettings(updated);
|
|
const reconciled = _settingsMutationTracker.reconcile(updated, operation);
|
|
applyServerSettings(reconciled);
|
|
dispatchSettingsSynced(reconciled, false);
|
|
ok = true;
|
|
dispatchSettingsSaveState('saved');
|
|
// Invalidate GET cache so next read sees the fresh data
|
|
_settingsCache = null;
|
|
} else {
|
|
forgetSentSettings();
|
|
dispatchSettingsSaveState('error');
|
|
}
|
|
} catch (error) {
|
|
if (isSettingsRuntimeContextCurrent(context)) {
|
|
console.warn('Failed to update shared settings via API:', error);
|
|
forgetSentSettings();
|
|
dispatchSettingsSaveState('error');
|
|
}
|
|
}
|
|
} finally {
|
|
_settingsMutationTracker.finish(operation);
|
|
}
|
|
} finally {
|
|
waiters.forEach((resolve) => resolve({ ok }));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Load the shared settings document for the current runtime (cached briefly
|
|
* during startup bursts). Pages that need a field the stores do not carry read
|
|
* it from here instead of fetching the endpoint themselves. `null` is a load
|
|
* failure, never an empty document.
|
|
*/
|
|
export const loadDesktopSettings = (): Promise<DesktopSettings | null> => fetchWebSettings();
|
|
|
|
/**
|
|
* Queue a change a person made in this window for the debounced write. Keys
|
|
* whose value the server already holds are dropped; computed server flags are
|
|
* never sent. Resolves once the write (or the decision not to write) settled.
|
|
*/
|
|
export const updateDesktopSettings = async (changes: Partial<DesktopSettings>): Promise<SettingsWriteResult> => {
|
|
if (typeof window === 'undefined') {
|
|
return { ok: false };
|
|
}
|
|
ensureSettingsRuntimeLifecycle();
|
|
const context = captureSettingsRuntimeContext();
|
|
|
|
if (_pendingSettingsContext && !isSameSettingsRuntimeContext(_pendingSettingsContext, context)) {
|
|
if (_settingsFlushTimer) clearTimeout(_settingsFlushTimer);
|
|
void _flushSettingsUpdate();
|
|
}
|
|
|
|
// Merge first, then drop keys that now equal the server: a toggle back to
|
|
// the server's value inside the debounce window cancels the pending write
|
|
// for that key instead of leaving the earlier value queued.
|
|
const writable: Partial<DesktopSettings> = {};
|
|
for (const key of settingsKeysOf(changes)) {
|
|
if (isWritableSettingsKey(key)) Object.assign(writable, { [key]: changes[key] });
|
|
}
|
|
const pending = withoutRedundantSettings({ ...(_pendingSettingsChanges ?? {}), ...writable });
|
|
if (Object.keys(pending).length === 0) {
|
|
_pendingSettingsChanges = null;
|
|
_pendingSettingsContext = null;
|
|
if (_settingsFlushTimer) {
|
|
clearTimeout(_settingsFlushTimer);
|
|
_settingsFlushTimer = null;
|
|
}
|
|
const waiters = _settingsFlushWaiters;
|
|
_settingsFlushWaiters = [];
|
|
waiters.forEach((resolve) => resolve({ ok: true }));
|
|
dispatchSettingsSaveState('saved');
|
|
return { ok: true };
|
|
}
|
|
_pendingSettingsChanges = pending;
|
|
_pendingSettingsContext = context;
|
|
_pendingSettingsRevision = _settingsMutationTracker.record(withoutRedundantSettings(writable));
|
|
dispatchSettingsSaveState('saving');
|
|
|
|
if (_settingsFlushTimer) {
|
|
clearTimeout(_settingsFlushTimer);
|
|
}
|
|
const flushed = new Promise<SettingsWriteResult>((resolve) => {
|
|
_settingsFlushWaiters.push(resolve);
|
|
});
|
|
_settingsFlushTimer = setTimeout(() => void _flushSettingsUpdate(), SETTINGS_DEBOUNCE_MS);
|
|
return flushed;
|
|
};
|
|
|
|
export const initializeAppearancePreferences = async (): Promise<void> => {
|
|
if (typeof window === 'undefined') {
|
|
return;
|
|
}
|
|
|
|
const persistApi = getPersistApi();
|
|
|
|
try {
|
|
const appearance = await loadAppearancePreferences();
|
|
if (!appearance) {
|
|
return;
|
|
}
|
|
|
|
const applyAppearance = () => applyAppearancePreferences(appearance);
|
|
|
|
if (persistApi?.hasHydrated?.()) {
|
|
applyAppearance();
|
|
return;
|
|
}
|
|
|
|
applyAppearance();
|
|
if (persistApi?.onFinishHydration) {
|
|
const unsubscribe = persistApi.onFinishHydration(() => {
|
|
unsubscribe?.();
|
|
applyAppearance();
|
|
});
|
|
}
|
|
} catch (error) {
|
|
console.warn('Failed to load appearance preferences:', error);
|
|
}
|
|
};
|