Files
openchamber/packages/web/server/lib/opencode/server-utils-runtime.js
T
Islam NoflandBohdan Triapitsyn 4523e9c486 perf: reduce re-renders, fix mobile keyboard handling, add chunk load recovery, and improve PATH management (#1028)
* fix: exclude file content from reverted prompt text

Revert and fork now restore only the user's original prompt, not server-injected file content
Uses existing isSyntheticPart helper for type-safe filtering

* fix: keep scrollbar visible when hovering over thumb

* fix: prevent ESC abort from triggering when terminal is focused

* fix: pass directory to permission/question reply calls so approvals actually resolve

* fix: default model selection not responding after Base UI migration

* fix: prevent modal content from shifting and clipping footer buttons

* fix: improve session switching performance and add sub-agent export with prompt collapse

Defer viewport anchor saving to eliminate ~800ms UI freeze when switching sessions
Add export dialog to include sub-agent tasks recursively in markdown export
Add collapse chevron button for expanded user prompts in sticky header

* fix: resolve sidebar scroll and TDZ crash in session sidebar

* perf: reduce CPU overhead and re-renders across chat, layout, and settings

* fix: position collapse button at top of message and prevent ESC abort in terminal

* fix: position collapse button at top and add padding only when expanded

* refactor: extract shared PATH utilities and mobile keyboard hook

* refactor: import shared path-utils in electron, use module-level style constants

- Electron now imports pathLooksUserConfigured/mergePathValues from
  shared path-utils.js instead of inline duplication
- ToolPart collapsedCustomStyle moved from useMemo([]) to module const

* fix: resolve remaining merge conflicts and type errors

- Remove duplicate variable declarations in SessionNodeItem
- Remove orphaned export callback body from conflict resolution
- Fix HelpDialog description -> descriptionKey (i18n rename)

* fix: resolve type-check and lint errors in session-actions.test.ts

- Added missing bun:test type declarations (beforeEach, mock, mock.module)
- Removed unused State import
- Replaced 'as any' casts with proper OpencodeClient and ChildStoreManager types
- Added eslint-disable for unused _ parameter in mock function

* fix PR 1028 export and PATH edge cases

* fix startup retry exhaustion state

* remove opencode package lock change

* fix sub-session rename cancellation

---------

Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
2026-04-26 16:24:07 +03:00

174 lines
4.6 KiB
JavaScript

import { registerOpenCodeProxy } from './proxy.js';
import { pathLooksUserConfigured, mergePathValues } from './path-utils.js';
export const createServerUtilsRuntime = (dependencies) => {
const {
fs,
os,
path,
process,
openCodeReadyGraceMs,
longRequestTimeoutMs,
getRuntime,
getOpenCodeAuthHeaders,
buildOpenCodeUrl,
ensureOpenCodeApiPrefix,
getUiNotificationClients,
getOpenCodePort,
setOpenCodePortState,
syncToHmrState,
markOpenCodeNotReady,
setOpenCodeNotReadySince,
clearLastOpenCodeError,
getLoginShellPath,
} = dependencies;
const setOpenCodePort = (port) => {
if (!Number.isFinite(port) || port <= 0) {
return;
}
const numericPort = Math.trunc(port);
const currentPort = getOpenCodePort();
const portChanged = currentPort !== numericPort;
if (portChanged || currentPort === null) {
setOpenCodePortState(numericPort);
syncToHmrState();
console.log(`Detected OpenCode port: ${numericPort}`);
if (portChanged) {
markOpenCodeNotReady();
}
setOpenCodeNotReadySince(Date.now());
}
clearLastOpenCodeError();
};
const waitForOpenCodePort = async (timeoutMs = 15000) => {
if (getOpenCodePort() !== null) {
return getOpenCodePort();
}
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 50));
if (getOpenCodePort() !== null) {
return getOpenCodePort();
}
}
throw new Error('Timed out waiting for OpenCode port');
};
const buildAugmentedPath = () => {
const currentPath = process.env.PATH || '';
const loginShellPath = getLoginShellPath();
const home = os.homedir();
const currentPathLooksUserConfigured = pathLooksUserConfigured(currentPath, home, path.delimiter);
const primaryPath = currentPathLooksUserConfigured ? currentPath : loginShellPath;
const fallbackPath = currentPathLooksUserConfigured ? loginShellPath : currentPath;
return mergePathValues(primaryPath, fallbackPath, path.delimiter);
};
const buildManagedOpenCodePath = () => {
const currentPath = process.env.PATH || '';
const loginShellPath = getLoginShellPath();
const home = os.homedir();
if (pathLooksUserConfigured(currentPath, home, path.delimiter)) {
return currentPath;
}
return mergePathValues(loginShellPath || '', currentPath, path.delimiter);
};
const parseSseDataPayload = (block) => {
if (!block || typeof block !== 'string') {
return null;
}
const dataLines = block
.split('\n')
.filter((line) => line.startsWith('data:'))
.map((line) => line.slice(5).replace(/^\s/, ''));
if (dataLines.length === 0) {
return null;
}
const payloadText = dataLines.join('\n').trim();
if (!payloadText) {
return null;
}
try {
const parsed = JSON.parse(payloadText);
if (
parsed &&
typeof parsed === 'object' &&
typeof parsed.payload === 'object' &&
parsed.payload !== null
) {
return parsed.payload;
}
return parsed;
} catch {
return null;
}
};
const fetchArraySnapshot = async (route, invalidMessage) => {
if (!getOpenCodePort()) {
throw new Error('OpenCode port is not available');
}
const response = await fetch(buildOpenCodeUrl(route), {
method: 'GET',
headers: { Accept: 'application/json', ...getOpenCodeAuthHeaders() },
});
if (!response.ok) {
throw new Error(`Failed to fetch ${invalidMessage} (status ${response.status})`);
}
const payload = await response.json().catch(() => null);
if (!Array.isArray(payload)) {
throw new Error(`Invalid ${invalidMessage} payload from OpenCode`);
}
return payload;
};
const fetchAgentsSnapshot = () => fetchArraySnapshot('/agent', 'agents snapshot');
const fetchProvidersSnapshot = () => fetchArraySnapshot('/provider', 'providers snapshot');
const fetchModelsSnapshot = () => fetchArraySnapshot('/model', 'models snapshot');
const setupProxy = (app) => {
registerOpenCodeProxy(app, {
fs,
os,
path,
OPEN_CODE_READY_GRACE_MS: openCodeReadyGraceMs,
LONG_REQUEST_TIMEOUT_MS: longRequestTimeoutMs,
getRuntime,
getOpenCodeAuthHeaders,
buildOpenCodeUrl,
ensureOpenCodeApiPrefix,
getUiNotificationClients,
});
};
return {
setOpenCodePort,
waitForOpenCodePort,
buildAugmentedPath,
buildManagedOpenCodePath,
parseSseDataPayload,
fetchAgentsSnapshot,
fetchProvidersSnapshot,
fetchModelsSnapshot,
setupProxy,
};
};