Decouple bundled UI from runtime API and add remote instance tooling (#1228)
Add a packaged-client runtime boundary so the shared UI can talk to local, desktop, remote, and VS Code runtimes through the right transport instead of assuming one same-origin web server. Centralize OpenChamber-owned API access behind RuntimeAPIs, runtimeFetch, and runtime URL helpers, while keeping official OpenCode traffic on the SDK path. Support runtime switching, remote host selection, desktop client credentials, and headless connection links for pairing packaged clients with remote OpenChamber servers. Harden the new auth model by moving long-lived client tokens out of browser URLs, introducing short-lived scoped URL tokens for browser-owned transports, restricting URL-token access to explicit readable/realtime routes, and making client-token management session-scoped or self-scoped as appropriate. Update browser-owned assets and preview proxy flows to work with the split runtime model, including authenticated project icons, preview token propagation, CSP-safe preview bridge injection, and preview proxy auth that survives short-lived URL-token expiry. Tighten Electron security boundaries for packaged clients by gating privileged preload state to trusted origins and requiring explicit confirmation before connect deep-links import or switch remote runtimes. Also refresh agent guidance and project skills so future runtime/API, auth, preview, UI, CLI, settings, locale, and drag-to-reorder work follows the new architecture.
This commit is contained in:
committed by
GitHub
parent
a4314c189b
commit
2031e3b4a8
@@ -0,0 +1,63 @@
|
||||
import type {
|
||||
ClientAuthAPI,
|
||||
RemoteClientCreateResult,
|
||||
RemoteClientPurgeRevokedResult,
|
||||
RemoteClientRecord,
|
||||
RemoteClientRevokeResult,
|
||||
} from '@openchamber/ui/lib/api/types';
|
||||
import { runtimeFetch } from '@openchamber/ui/lib/runtime-fetch';
|
||||
|
||||
const jsonOrNull = async <T>(response: Response): Promise<T | null> => {
|
||||
return (await response.json().catch(() => null)) as T | null;
|
||||
};
|
||||
|
||||
export const createWebClientAuthAPI = (): ClientAuthAPI => ({
|
||||
async listClients(): Promise<RemoteClientRecord[]> {
|
||||
const response = await runtimeFetch('/api/client-auth/clients', {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
const payload = await jsonOrNull<{ clients?: RemoteClientRecord[]; error?: string }>(response);
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to load remote clients');
|
||||
}
|
||||
return Array.isArray(payload.clients) ? payload.clients : [];
|
||||
},
|
||||
|
||||
async createClient(input = {}): Promise<RemoteClientCreateResult> {
|
||||
const response = await runtimeFetch('/api/client-auth/clients', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ label: input.label ?? '' }),
|
||||
});
|
||||
const payload = await jsonOrNull<RemoteClientCreateResult & { error?: string }>(response);
|
||||
if (!response.ok || !payload?.client || typeof payload.token !== 'string') {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to create remote client token');
|
||||
}
|
||||
return payload;
|
||||
},
|
||||
|
||||
async revokeClient(id: string): Promise<RemoteClientRevokeResult> {
|
||||
const response = await runtimeFetch(`/api/client-auth/clients/${encodeURIComponent(id)}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
const payload = await jsonOrNull<RemoteClientRevokeResult & { error?: string }>(response);
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to revoke remote client');
|
||||
}
|
||||
return payload;
|
||||
},
|
||||
|
||||
async purgeRevokedClients(): Promise<RemoteClientPurgeRevokedResult> {
|
||||
const response = await runtimeFetch('/api/client-auth/clients', {
|
||||
method: 'DELETE',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
const payload = await jsonOrNull<RemoteClientPurgeRevokedResult & { error?: string }>(response);
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to clear revoked clients');
|
||||
}
|
||||
return payload;
|
||||
},
|
||||
});
|
||||
@@ -4,9 +4,15 @@ import type {
|
||||
FileSearchResult,
|
||||
FilesAPI,
|
||||
} from '@openchamber/ui/lib/api/types';
|
||||
import { runtimeFetch } from '@openchamber/ui/lib/runtime-fetch';
|
||||
import type { RuntimeUrlResolver } from '@openchamber/ui/lib/runtime-url';
|
||||
|
||||
const normalizePath = (path: string): string => path.replace(/\\/g, '/');
|
||||
|
||||
interface WebFilesAPIOptions {
|
||||
urls: RuntimeUrlResolver;
|
||||
}
|
||||
|
||||
type WebDirectoryEntry = {
|
||||
name?: string;
|
||||
path?: string;
|
||||
@@ -39,7 +45,7 @@ const toDirectoryListResult = (fallbackDirectory: string, payload: WebDirectoryL
|
||||
};
|
||||
};
|
||||
|
||||
export const createWebFilesAPI = (): FilesAPI => ({
|
||||
export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
async listDirectory(path: string, options): Promise<DirectoryListResult> {
|
||||
const target = normalizePath(path);
|
||||
const params = new URLSearchParams();
|
||||
@@ -50,7 +56,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
params.set('respectGitignore', 'true');
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/fs/list${params.toString() ? `?${params.toString()}` : ''}`);
|
||||
const response = await runtimeFetch(urls.api('/api/fs/list', params));
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
@@ -77,7 +83,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
params.set('limit', String(payload.maxResults));
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/find/file?${params.toString()}`);
|
||||
const response = await runtimeFetch(urls.api('/api/find/file', params));
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
@@ -95,7 +101,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
|
||||
async createDirectory(path: string): Promise<{ success: boolean; path: string }> {
|
||||
const target = normalizePath(path);
|
||||
const response = await fetch('/api/fs/mkdir', {
|
||||
const response = await runtimeFetch(urls.api('/api/fs/mkdir'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ path: target }),
|
||||
@@ -119,7 +125,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
if (options?.allowOutsideWorkspace) {
|
||||
params.set('allowOutsideWorkspace', 'true');
|
||||
}
|
||||
const response = await fetch(`/api/fs/stat?${params.toString()}`);
|
||||
const response = await runtimeFetch(urls.api('/api/fs/stat', params));
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
@@ -144,7 +150,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
if (options?.optional) {
|
||||
params.set('optional', 'true');
|
||||
}
|
||||
const response = await fetch(`/api/fs/read?${params.toString()}`, {
|
||||
const response = await runtimeFetch(urls.api('/api/fs/read', params), {
|
||||
cache: options?.optional ? 'no-store' : 'default',
|
||||
});
|
||||
|
||||
@@ -159,7 +165,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
|
||||
async writeFile(path: string, content: string): Promise<{ success: boolean; path: string }> {
|
||||
const target = normalizePath(path);
|
||||
const response = await fetch('/api/fs/write', {
|
||||
const response = await runtimeFetch(urls.api('/api/fs/write'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ path: target, content }),
|
||||
@@ -179,7 +185,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
|
||||
async delete(path: string): Promise<{ success: boolean }> {
|
||||
const target = normalizePath(path);
|
||||
const response = await fetch('/api/fs/delete', {
|
||||
const response = await runtimeFetch(urls.api('/api/fs/delete'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ path: target }),
|
||||
@@ -195,7 +201,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
},
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<{ success: boolean; path: string }> {
|
||||
const response = await fetch('/api/fs/rename', {
|
||||
const response = await runtimeFetch(urls.api('/api/fs/rename'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ oldPath, newPath }),
|
||||
@@ -214,7 +220,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
},
|
||||
|
||||
async revealPath(targetPath: string): Promise<{ success: boolean }> {
|
||||
const response = await fetch('/api/fs/reveal', {
|
||||
const response = await runtimeFetch(urls.api('/api/fs/reveal'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ path: normalizePath(targetPath) }),
|
||||
@@ -231,7 +237,7 @@ export const createWebFilesAPI = (): FilesAPI => ({
|
||||
|
||||
async downloadFile(path: string): Promise<void> {
|
||||
const target = normalizePath(path);
|
||||
const url = `/api/fs/raw?path=${encodeURIComponent(target)}&download=true`;
|
||||
const url = urls.rawFile(target, { download: true });
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = target.split('/').pop() || 'file';
|
||||
|
||||
@@ -19,14 +19,20 @@ import type {
|
||||
GitHubDeviceFlowStart,
|
||||
GitHubUserSummary,
|
||||
} from '@openchamber/ui/lib/api/types';
|
||||
import { runtimeFetch } from '@openchamber/ui/lib/runtime-fetch';
|
||||
import type { RuntimeUrlResolver } from '@openchamber/ui/lib/runtime-url';
|
||||
|
||||
interface WebGitHubAPIOptions {
|
||||
urls: RuntimeUrlResolver;
|
||||
}
|
||||
|
||||
const jsonOrNull = async <T>(response: Response): Promise<T | null> => {
|
||||
return (await response.json().catch(() => null)) as T | null;
|
||||
};
|
||||
|
||||
export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
export const createWebGitHubAPI = ({ urls }: WebGitHubAPIOptions): GitHubAPI => ({
|
||||
async authStatus(): Promise<GitHubAuthStatus> {
|
||||
const response = await fetch('/api/github/auth/status', { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const response = await runtimeFetch('/api/github/auth/status', { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const payload = await jsonOrNull<GitHubAuthStatus & { error?: string }>(response);
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to load GitHub status');
|
||||
@@ -35,7 +41,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async authStart(): Promise<GitHubDeviceFlowStart> {
|
||||
const response = await fetch('/api/github/auth/start', {
|
||||
const response = await runtimeFetch('/api/github/auth/start', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
@@ -48,7 +54,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async authComplete(deviceCode: string): Promise<GitHubDeviceFlowComplete> {
|
||||
const response = await fetch('/api/github/auth/complete', {
|
||||
const response = await runtimeFetch('/api/github/auth/complete', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ deviceCode }),
|
||||
@@ -61,7 +67,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async authDisconnect(): Promise<{ removed: boolean }> {
|
||||
const response = await fetch('/api/github/auth', { method: 'DELETE', headers: { Accept: 'application/json' } });
|
||||
const response = await runtimeFetch('/api/github/auth', { method: 'DELETE', headers: { Accept: 'application/json' } });
|
||||
const payload = await jsonOrNull<{ removed?: boolean; error?: string }>(response);
|
||||
if (!response.ok) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to disconnect GitHub');
|
||||
@@ -70,7 +76,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async authActivate(accountId: string): Promise<GitHubAuthStatus> {
|
||||
const response = await fetch('/api/github/auth/activate', {
|
||||
const response = await runtimeFetch('/api/github/auth/activate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ accountId }),
|
||||
@@ -83,7 +89,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async me(): Promise<GitHubUserSummary> {
|
||||
const response = await fetch('/api/github/me', { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const response = await runtimeFetch('/api/github/me', { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const payload = await jsonOrNull<GitHubUserSummary & { error?: string }>(response);
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to fetch GitHub user');
|
||||
@@ -98,7 +104,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
...(remote ? { remote } : {}),
|
||||
...(options?.force ? { force: 'true' } : {}),
|
||||
});
|
||||
const response = await fetch(
|
||||
const response = await runtimeFetch(
|
||||
`/api/github/pr/status?${params.toString()}`,
|
||||
{ method: 'GET', headers: { Accept: 'application/json' } }
|
||||
);
|
||||
@@ -110,7 +116,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async prCreate(payload: GitHubPullRequestCreateInput): Promise<GitHubPullRequest> {
|
||||
const response = await fetch('/api/github/pr/create', {
|
||||
const response = await runtimeFetch('/api/github/pr/create', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
@@ -123,7 +129,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async prUpdate(payload: GitHubPullRequestUpdateInput): Promise<GitHubPullRequest> {
|
||||
const response = await fetch('/api/github/pr/update', {
|
||||
const response = await runtimeFetch('/api/github/pr/update', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
@@ -136,7 +142,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async prMerge(payload: GitHubPullRequestMergeInput): Promise<GitHubPullRequestMergeResult> {
|
||||
const response = await fetch('/api/github/pr/merge', {
|
||||
const response = await runtimeFetch('/api/github/pr/merge', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
@@ -149,7 +155,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async prReady(payload: GitHubPullRequestReadyInput): Promise<GitHubPullRequestReadyResult> {
|
||||
const response = await fetch('/api/github/pr/ready', {
|
||||
const response = await runtimeFetch('/api/github/pr/ready', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
@@ -162,7 +168,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async repoUpstream(directory: string): Promise<GitHubRepoUpstreamResult> {
|
||||
const response = await fetch(
|
||||
const response = await runtimeFetch(
|
||||
`/api/github/repo/upstream?directory=${encodeURIComponent(directory)}`,
|
||||
{ method: 'GET', headers: { Accept: 'application/json' } }
|
||||
);
|
||||
@@ -174,7 +180,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async repoBranches(owner: string, repo: string): Promise<string[]> {
|
||||
const response = await fetch(
|
||||
const response = await runtimeFetch(
|
||||
`/api/github/repo/branches?owner=${encodeURIComponent(owner)}&repo=${encodeURIComponent(repo)}`,
|
||||
{ method: 'GET', headers: { Accept: 'application/json' } }
|
||||
);
|
||||
@@ -187,7 +193,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
|
||||
async prsList(directory: string, options?: { page?: number }): Promise<GitHubPullRequestsListResult> {
|
||||
const page = options?.page ?? 1;
|
||||
const response = await fetch(
|
||||
const response = await runtimeFetch(
|
||||
`/api/github/pulls/list?directory=${encodeURIComponent(directory)}&page=${encodeURIComponent(String(page))}`,
|
||||
{ method: 'GET', headers: { Accept: 'application/json' } }
|
||||
);
|
||||
@@ -203,20 +209,18 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
number: number,
|
||||
options?: { includeDiff?: boolean; includeCheckDetails?: boolean; sourceRepo?: { owner: string; repo: string } | null }
|
||||
): Promise<GitHubPullRequestContextResult> {
|
||||
const url = new URL('/api/github/pulls/context', window.location.origin);
|
||||
url.searchParams.set('directory', directory);
|
||||
url.searchParams.set('number', String(number));
|
||||
const params = new URLSearchParams({ directory, number: String(number) });
|
||||
if (options?.includeDiff) {
|
||||
url.searchParams.set('diff', '1');
|
||||
params.set('diff', '1');
|
||||
}
|
||||
if (options?.includeCheckDetails) {
|
||||
url.searchParams.set('checkDetails', '1');
|
||||
params.set('checkDetails', '1');
|
||||
}
|
||||
if (options?.sourceRepo?.owner && options.sourceRepo.repo) {
|
||||
url.searchParams.set('owner', options.sourceRepo.owner);
|
||||
url.searchParams.set('repo', options.sourceRepo.repo);
|
||||
params.set('owner', options.sourceRepo.owner);
|
||||
params.set('repo', options.sourceRepo.repo);
|
||||
}
|
||||
const response = await fetch(url.toString(), { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const response = await runtimeFetch(urls.api('/api/github/pulls/context', params), { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const body = await jsonOrNull<GitHubPullRequestContextResult & { error?: string }>(response);
|
||||
if (!response.ok || !body) {
|
||||
throw new Error(body?.error || response.statusText || 'Failed to load pull request context');
|
||||
@@ -226,7 +230,7 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
|
||||
async issuesList(directory: string, options?: { page?: number }): Promise<GitHubIssuesListResult> {
|
||||
const page = options?.page ?? 1;
|
||||
const response = await fetch(
|
||||
const response = await runtimeFetch(
|
||||
`/api/github/issues/list?directory=${encodeURIComponent(directory)}&page=${encodeURIComponent(String(page))}`,
|
||||
{ method: 'GET', headers: { Accept: 'application/json' } }
|
||||
);
|
||||
@@ -238,14 +242,12 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async issueGet(directory: string, number: number, options?: { sourceRepo?: { owner: string; repo: string } | null }): Promise<GitHubIssueGetResult> {
|
||||
const url = new URL('/api/github/issues/get', window.location.origin);
|
||||
url.searchParams.set('directory', directory);
|
||||
url.searchParams.set('number', String(number));
|
||||
const params = new URLSearchParams({ directory, number: String(number) });
|
||||
if (options?.sourceRepo?.owner && options.sourceRepo.repo) {
|
||||
url.searchParams.set('owner', options.sourceRepo.owner);
|
||||
url.searchParams.set('repo', options.sourceRepo.repo);
|
||||
params.set('owner', options.sourceRepo.owner);
|
||||
params.set('repo', options.sourceRepo.repo);
|
||||
}
|
||||
const response = await fetch(url.toString(), { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const response = await runtimeFetch(urls.api('/api/github/issues/get', params), { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const payload = await jsonOrNull<GitHubIssueGetResult & { error?: string }>(response);
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to load issue');
|
||||
@@ -254,14 +256,12 @@ export const createWebGitHubAPI = (): GitHubAPI => ({
|
||||
},
|
||||
|
||||
async issueComments(directory: string, number: number, options?: { sourceRepo?: { owner: string; repo: string } | null }): Promise<GitHubIssueCommentsResult> {
|
||||
const url = new URL('/api/github/issues/comments', window.location.origin);
|
||||
url.searchParams.set('directory', directory);
|
||||
url.searchParams.set('number', String(number));
|
||||
const params = new URLSearchParams({ directory, number: String(number) });
|
||||
if (options?.sourceRepo?.owner && options.sourceRepo.repo) {
|
||||
url.searchParams.set('owner', options.sourceRepo.owner);
|
||||
url.searchParams.set('repo', options.sourceRepo.repo);
|
||||
params.set('owner', options.sourceRepo.owner);
|
||||
params.set('repo', options.sourceRepo.repo);
|
||||
}
|
||||
const response = await fetch(url.toString(), { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const response = await runtimeFetch(urls.api('/api/github/issues/comments', params), { method: 'GET', headers: { Accept: 'application/json' } });
|
||||
const payload = await jsonOrNull<GitHubIssueCommentsResult & { error?: string }>(response);
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to load issue comments');
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import type { RuntimeAPIs } from '@openchamber/ui/lib/api/types';
|
||||
import {
|
||||
createRuntimeUrlResolver,
|
||||
getRuntimeUrlResolver,
|
||||
setRuntimeUrlResolver,
|
||||
type RuntimeUrlResolver,
|
||||
} from '@openchamber/ui/lib/runtime-url';
|
||||
import { createWebTerminalAPI } from './terminal';
|
||||
import { createWebGitAPI } from './git';
|
||||
import { createWebFilesAPI } from './files';
|
||||
@@ -8,16 +14,38 @@ import { createWebNotificationsAPI } from './notifications';
|
||||
import { createWebToolsAPI } from './tools';
|
||||
import { createWebPushAPI } from './push';
|
||||
import { createWebGitHubAPI } from './github';
|
||||
import { createWebClientAuthAPI } from './clientAuth';
|
||||
|
||||
export const createWebAPIs = (): RuntimeAPIs => ({
|
||||
export interface WebAPIsOptions {
|
||||
urls?: RuntimeUrlResolver;
|
||||
}
|
||||
|
||||
const createActiveRuntimeUrlResolver = (): RuntimeUrlResolver => ({
|
||||
api: (...args) => getRuntimeUrlResolver().api(...args),
|
||||
authenticatedAsset: (...args) => getRuntimeUrlResolver().authenticatedAsset(...args),
|
||||
auth: (...args) => getRuntimeUrlResolver().auth(...args),
|
||||
health: (...args) => getRuntimeUrlResolver().health(...args),
|
||||
rawFile: (...args) => getRuntimeUrlResolver().rawFile(...args),
|
||||
sse: (...args) => getRuntimeUrlResolver().sse(...args),
|
||||
websocket: (...args) => getRuntimeUrlResolver().websocket(...args),
|
||||
});
|
||||
|
||||
export const createWebAPIs = (options: WebAPIsOptions = {}): RuntimeAPIs => {
|
||||
const urls = options.urls ?? createRuntimeUrlResolver();
|
||||
setRuntimeUrlResolver(urls);
|
||||
const activeUrls = createActiveRuntimeUrlResolver();
|
||||
|
||||
return {
|
||||
runtime: { platform: 'web', isDesktop: false, isVSCode: false, label: 'web' },
|
||||
terminal: createWebTerminalAPI(),
|
||||
git: createWebGitAPI(),
|
||||
files: createWebFilesAPI(),
|
||||
files: createWebFilesAPI({ urls: activeUrls }),
|
||||
settings: createWebSettingsAPI(),
|
||||
permissions: createWebPermissionsAPI(),
|
||||
notifications: createWebNotificationsAPI(),
|
||||
github: createWebGitHubAPI(),
|
||||
github: createWebGitHubAPI({ urls: activeUrls }),
|
||||
push: createWebPushAPI(),
|
||||
clientAuth: createWebClientAuthAPI(),
|
||||
tools: createWebToolsAPI(),
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
type MockNotificationConstructor = {
|
||||
new (title: string, options?: NotificationOptions): Notification;
|
||||
permission: NotificationPermission;
|
||||
requestPermission: () => Promise<NotificationPermission>;
|
||||
};
|
||||
|
||||
const originalNotification = globalThis.Notification;
|
||||
const originalNavigator = globalThis.navigator;
|
||||
const originalDocument = globalThis.document;
|
||||
const originalWindow = globalThis.window;
|
||||
|
||||
const installNotificationMock = (onCreate: (title: string, options?: NotificationOptions) => void) => {
|
||||
const MockNotification = function Notification(this: Notification, title: string, options?: NotificationOptions) {
|
||||
onCreate(title, options);
|
||||
return this;
|
||||
} as unknown as MockNotificationConstructor;
|
||||
MockNotification.permission = 'granted';
|
||||
MockNotification.requestPermission = vi.fn(async () => 'granted' as NotificationPermission);
|
||||
|
||||
Object.defineProperty(globalThis, 'Notification', {
|
||||
configurable: true,
|
||||
value: MockNotification,
|
||||
});
|
||||
};
|
||||
|
||||
const installWindowMock = () => {
|
||||
const storage = new Map<string, string>();
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: {
|
||||
localStorage: {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => storage.set(key, value),
|
||||
removeItem: (key: string) => storage.delete(key),
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.resetModules();
|
||||
Object.defineProperty(globalThis, 'Notification', { configurable: true, value: originalNotification });
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: originalNavigator });
|
||||
Object.defineProperty(globalThis, 'document', { configurable: true, value: originalDocument });
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: originalWindow });
|
||||
});
|
||||
|
||||
describe('web notifications API', () => {
|
||||
it('deduplicates repeated foreground notifications by tag', async () => {
|
||||
installWindowMock();
|
||||
const created: Array<{ title: string; options?: NotificationOptions }> = [];
|
||||
installNotificationMock((title, options) => created.push({ title, options }));
|
||||
|
||||
const { createWebNotificationsAPI } = await import('./notifications');
|
||||
const api = createWebNotificationsAPI();
|
||||
|
||||
await expect(api.notifyAgentCompletion({ title: 'Ready', body: 'Done', tag: 'ready-session' })).resolves.toBe(true);
|
||||
await expect(api.notifyAgentCompletion({ title: 'Ready', body: 'Done', tag: 'ready-session' })).resolves.toBe(true);
|
||||
|
||||
expect(created).toHaveLength(1);
|
||||
expect(created[0]?.title).toBe('Ready');
|
||||
});
|
||||
|
||||
it('defers hidden-page notification delivery to active push subscription without claiming foreground delivery', async () => {
|
||||
installWindowMock();
|
||||
const created: Array<{ title: string; options?: NotificationOptions }> = [];
|
||||
installNotificationMock((title, options) => created.push({ title, options }));
|
||||
const showNotification = vi.fn(async () => undefined);
|
||||
let visibilityState: DocumentVisibilityState = 'hidden';
|
||||
let focused = false;
|
||||
|
||||
Object.defineProperty(globalThis, 'document', {
|
||||
configurable: true,
|
||||
value: {
|
||||
get visibilityState() {
|
||||
return visibilityState;
|
||||
},
|
||||
hasFocus: () => focused,
|
||||
},
|
||||
});
|
||||
Object.defineProperty(globalThis, 'navigator', {
|
||||
configurable: true,
|
||||
value: {
|
||||
serviceWorker: {
|
||||
getRegistration: vi.fn(async () => ({
|
||||
active: {},
|
||||
showNotification,
|
||||
pushManager: {
|
||||
getSubscription: vi.fn(async () => ({ endpoint: 'https://push.example/subscription' })),
|
||||
},
|
||||
})),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { createWebNotificationsAPI } = await import('./notifications');
|
||||
const api = createWebNotificationsAPI();
|
||||
|
||||
await expect(api.notifyAgentCompletion({ title: 'Ready', body: 'Done', tag: 'ready-session' })).resolves.toBe(true);
|
||||
|
||||
expect(showNotification).not.toHaveBeenCalled();
|
||||
expect(created).toHaveLength(0);
|
||||
|
||||
visibilityState = 'visible';
|
||||
focused = true;
|
||||
|
||||
await expect(api.notifyAgentCompletion({ title: 'Ready', body: 'Done', tag: 'ready-session' })).resolves.toBe(true);
|
||||
|
||||
expect(showNotification).toHaveBeenCalledTimes(1);
|
||||
expect(showNotification).toHaveBeenCalledWith('Ready', expect.objectContaining({ body: 'Done', tag: 'ready-session' }));
|
||||
expect(created).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,66 @@
|
||||
import type { NotificationPayload, NotificationsAPI } from '@openchamber/ui/lib/api/types';
|
||||
|
||||
const SW_READY_TIMEOUT_MS = 1500;
|
||||
const NOTIFICATION_DEDUPE_TTL_MS = 5000;
|
||||
const NOTIFICATION_DEDUPE_STORAGE_PREFIX = 'openchamber-notification-claim:';
|
||||
|
||||
const notificationClaims = new Map<string, number>();
|
||||
|
||||
const isClientFocused = (): boolean => {
|
||||
if (typeof document === 'undefined') return true;
|
||||
return document.visibilityState === 'visible' && document.hasFocus();
|
||||
};
|
||||
|
||||
const getNotificationClaimKey = (payload?: NotificationPayload): string => {
|
||||
const tag = typeof payload?.tag === 'string' ? payload.tag.trim() : '';
|
||||
if (tag) return tag;
|
||||
|
||||
return [payload?.sessionId, payload?.kind, payload?.title, payload?.body]
|
||||
.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
|
||||
.map((value) => value.trim())
|
||||
.join('|');
|
||||
};
|
||||
|
||||
const pruneNotificationClaims = (now: number): void => {
|
||||
for (const [key, claimedAt] of notificationClaims) {
|
||||
if (now - claimedAt > NOTIFICATION_DEDUPE_TTL_MS) {
|
||||
notificationClaims.delete(key);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const claimNotificationPayload = (payload?: NotificationPayload): boolean => {
|
||||
const key = getNotificationClaimKey(payload);
|
||||
if (!key) return true;
|
||||
|
||||
const now = Date.now();
|
||||
pruneNotificationClaims(now);
|
||||
|
||||
const claimedAt = notificationClaims.get(key) ?? 0;
|
||||
if (now - claimedAt < NOTIFICATION_DEDUPE_TTL_MS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof window !== 'undefined' && window.localStorage) {
|
||||
const storageKey = `${NOTIFICATION_DEDUPE_STORAGE_PREFIX}${key}`;
|
||||
const stored = Number(window.localStorage.getItem(storageKey) ?? '0');
|
||||
if (Number.isFinite(stored) && now - stored < NOTIFICATION_DEDUPE_TTL_MS) {
|
||||
notificationClaims.set(key, stored);
|
||||
return false;
|
||||
}
|
||||
if (Number.isFinite(stored) && stored > 0) {
|
||||
window.localStorage.removeItem(storageKey);
|
||||
}
|
||||
window.localStorage.setItem(storageKey, String(now));
|
||||
}
|
||||
} catch {
|
||||
// Storage is best-effort; in-memory dedupe still covers duplicate streams in this tab.
|
||||
}
|
||||
|
||||
notificationClaims.set(key, now);
|
||||
return true;
|
||||
};
|
||||
|
||||
const getNotificationRegistration = async (): Promise<ServiceWorkerRegistration | null> => {
|
||||
if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) {
|
||||
@@ -54,7 +114,24 @@ const notifyWithServiceWorker = async (payload?: NotificationPayload): Promise<b
|
||||
}
|
||||
};
|
||||
|
||||
const hasActivePushSubscription = async (): Promise<boolean> => {
|
||||
const registration = await getNotificationRegistration();
|
||||
if (!registration || !('pushManager' in registration) || !registration.pushManager) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return Boolean(await registration.pushManager.getSubscription());
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const notifyWithWebAPI = async (payload?: NotificationPayload): Promise<boolean> => {
|
||||
if (payload?.requireHidden && typeof document !== 'undefined' && document.hasFocus()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof Notification === 'undefined') {
|
||||
console.info('Notifications not supported in this environment', payload);
|
||||
return false;
|
||||
@@ -73,6 +150,17 @@ const notifyWithWebAPI = async (payload?: NotificationPayload): Promise<boolean>
|
||||
return false;
|
||||
}
|
||||
|
||||
// Background push is the delivery channel when the web/PWA client is not
|
||||
// focused. Keep the main notification toggle and templates enabled, but avoid
|
||||
// also showing the same foreground notification from a hidden page.
|
||||
if (!isClientFocused() && await hasActivePushSubscription()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!claimNotificationPayload(payload)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
// Some installed PWAs expose Notification.permission but only allow
|
||||
// notifications through an active service worker registration.
|
||||
@@ -91,7 +179,7 @@ const notifyWithWebAPI = async (payload?: NotificationPayload): Promise<boolean>
|
||||
}
|
||||
};
|
||||
|
||||
const notifyWithTauri = async (payload?: NotificationPayload): Promise<boolean> => {
|
||||
const notifyWithDesktop = async (payload?: NotificationPayload): Promise<boolean> => {
|
||||
if (typeof window === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
@@ -107,18 +195,22 @@ const notifyWithTauri = async (payload?: NotificationPayload): Promise<boolean>
|
||||
title: payload?.title,
|
||||
body: payload?.body,
|
||||
tag: payload?.tag,
|
||||
kind: payload?.kind,
|
||||
sessionId: payload?.sessionId,
|
||||
directory: payload?.directory,
|
||||
requireHidden: payload?.requireHidden,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('Failed to send native notification (tauri)', error);
|
||||
console.warn('Failed to send native notification (desktop)', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const createWebNotificationsAPI = (): NotificationsAPI => ({
|
||||
async notifyAgentCompletion(payload?: NotificationPayload): Promise<boolean> {
|
||||
return (await notifyWithTauri(payload)) || (await notifyWithWebAPI(payload));
|
||||
return (await notifyWithDesktop(payload)) || (await notifyWithWebAPI(payload));
|
||||
},
|
||||
canNotify: () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { PushAPI, PushSubscribePayload, PushUnsubscribePayload } from '@openchamber/ui/lib/api/types';
|
||||
import { runtimeFetch } from '@openchamber/ui/lib/runtime-fetch';
|
||||
|
||||
const fetchJson = async <T>(input: RequestInfo | URL, init?: RequestInit): Promise<T | null> => {
|
||||
const fetchJson = async <T>(input: string | URL | Request, init?: RequestInit): Promise<T | null> => {
|
||||
try {
|
||||
const res = await fetch(input, {
|
||||
const res = await runtimeFetch(input, {
|
||||
...init,
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { SettingsAPI, SettingsLoadResult, SettingsPayload } from '@openchamber/ui/lib/api/types';
|
||||
import { runtimeFetch } from '@openchamber/ui/lib/runtime-fetch';
|
||||
|
||||
const SETTINGS_ENDPOINT = '/api/config/settings';
|
||||
const RELOAD_ENDPOINT = '/api/config/reload';
|
||||
@@ -12,7 +13,7 @@ const sanitizePayload = (data: unknown): SettingsPayload => {
|
||||
|
||||
export const createWebSettingsAPI = (): SettingsAPI => ({
|
||||
async load(): Promise<SettingsLoadResult> {
|
||||
const response = await fetch(SETTINGS_ENDPOINT, {
|
||||
const response = await runtimeFetch(SETTINGS_ENDPOINT, {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
@@ -29,7 +30,7 @@ export const createWebSettingsAPI = (): SettingsAPI => ({
|
||||
},
|
||||
|
||||
async save(changes: Partial<SettingsPayload>): Promise<SettingsPayload> {
|
||||
const response = await fetch(SETTINGS_ENDPOINT, {
|
||||
const response = await runtimeFetch(SETTINGS_ENDPOINT, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -48,7 +49,7 @@ export const createWebSettingsAPI = (): SettingsAPI => ({
|
||||
},
|
||||
|
||||
async restartOpenCode(): Promise<{ restarted: boolean }> {
|
||||
const response = await fetch(RELOAD_ENDPOINT, { method: 'POST' });
|
||||
const response = await runtimeFetch(RELOAD_ENDPOINT, { method: 'POST' });
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
throw new Error(error.error || 'Failed to restart OpenCode');
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { ToolsAPI } from '@openchamber/ui/lib/api/types';
|
||||
import { runtimeFetch } from '@openchamber/ui/lib/runtime-fetch';
|
||||
|
||||
export const createWebToolsAPI = (): ToolsAPI => ({
|
||||
async getAvailableTools(): Promise<string[]> {
|
||||
|
||||
const response = await fetch('/api/experimental/tool/ids');
|
||||
const response = await runtimeFetch('/api/experimental/tool/ids');
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Tools API returned ${response.status} ${response.statusText}`);
|
||||
|
||||
Reference in New Issue
Block a user