mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
chore(lint): replace ESLint with Oxlint and clear anti-slop findings
This commit is contained in:
1 parent
c6c13335e5
commit
b625acfc0c
1083 files changed
+67089
-80136
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
|
||||
import { z } from 'zod'
|
||||
import { ChangeWalkthroughStateSchema, walkthroughSourceKey } from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
ChangeWalkthroughState,
|
||||
GenerateChangeWalkthroughRequest,
|
||||
@@ -14,8 +15,10 @@ function walkthroughUrl(sessionId: string): string {
|
||||
|
||||
const HELPER_SESSIONS_URL = `${API_BASE_URL}/api/change-walkthroughs/helper-sessions`
|
||||
|
||||
const helperSessionIdsSchema = z.object({ sessionIds: z.array(z.string()) })
|
||||
|
||||
export async function getWalkthroughHelperSessionIds(): Promise<string[]> {
|
||||
const response = await fetchWrapper<{ sessionIds: string[] }>(HELPER_SESSIONS_URL)
|
||||
const response = await fetchWrapper(HELPER_SESSIONS_URL, helperSessionIdsSchema)
|
||||
return response.sessionIds
|
||||
}
|
||||
|
||||
@@ -23,7 +26,7 @@ export async function getChangeWalkthrough(
|
||||
sessionId: string,
|
||||
source: WalkthroughSource,
|
||||
): Promise<ChangeWalkthroughState> {
|
||||
return fetchWrapper<ChangeWalkthroughState>(walkthroughUrl(sessionId), {
|
||||
return fetchWrapper(walkthroughUrl(sessionId), ChangeWalkthroughStateSchema, {
|
||||
params: { source: walkthroughSourceKey(source) },
|
||||
})
|
||||
}
|
||||
@@ -32,7 +35,7 @@ export async function generateChangeWalkthrough(
|
||||
sessionId: string,
|
||||
request: GenerateChangeWalkthroughRequest,
|
||||
): Promise<ChangeWalkthroughState> {
|
||||
return fetchWrapper<ChangeWalkthroughState>(walkthroughUrl(sessionId), {
|
||||
return fetchWrapper(walkthroughUrl(sessionId), ChangeWalkthroughStateSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -43,7 +46,7 @@ export async function refineChangeWalkthrough(
|
||||
sessionId: string,
|
||||
request: RefineChangeWalkthroughRequest,
|
||||
): Promise<ChangeWalkthroughState> {
|
||||
return fetchWrapper<ChangeWalkthroughState>(`${walkthroughUrl(sessionId)}/refine`, {
|
||||
return fetchWrapper(`${walkthroughUrl(sessionId)}/refine`, ChangeWalkthroughStateSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import {
|
||||
DevicePairingAvailabilitySchema,
|
||||
DevicePairingLinksResponseSchema,
|
||||
PairedDevicesResponseSchema,
|
||||
RedeemDevicePairingCodeResponseSchema,
|
||||
RemoteAccessHeadersResponseSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
CreateDevicePairingLinksRequest,
|
||||
DevicePairingAvailability,
|
||||
DevicePairingLinksResponse,
|
||||
PairedDevice,
|
||||
PairedDevicesResponse,
|
||||
RedeemDevicePairingCodeRequest,
|
||||
RedeemDevicePairingCodeResponse,
|
||||
RemoteAccessHeadersResponse,
|
||||
@@ -15,12 +21,12 @@ import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
|
||||
const REMOTE_ACCESS_HEADERS_URL = `${API_BASE_URL}/api/settings/remote-access-headers`
|
||||
|
||||
/** Redeems a browser pairing code and starts a session for the paired user. */
|
||||
export async function redeemDevicePairingCode(
|
||||
body: RedeemDevicePairingCodeRequest,
|
||||
): Promise<RedeemDevicePairingCodeResponse> {
|
||||
return fetchWrapper<RedeemDevicePairingCodeResponse>(
|
||||
return fetchWrapper(
|
||||
`${getAuthBaseUrl()}/device-pairing/redeem`,
|
||||
RedeemDevicePairingCodeResponseSchema,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -29,59 +35,54 @@ export async function redeemDevicePairingCode(
|
||||
)
|
||||
}
|
||||
|
||||
/** Reads the names of the stored remote-access headers without their values. */
|
||||
export async function getRemoteAccessHeaders(): Promise<RemoteAccessHeadersResponse> {
|
||||
return fetchWrapper<RemoteAccessHeadersResponse>(REMOTE_ACCESS_HEADERS_URL)
|
||||
return fetchWrapper(REMOTE_ACCESS_HEADERS_URL, RemoteAccessHeadersResponseSchema)
|
||||
}
|
||||
|
||||
/** Replaces the stored remote-access headers, keeping stored values for blank entries. */
|
||||
export async function replaceRemoteAccessHeaders(
|
||||
body: ReplaceRemoteAccessHeadersRequest,
|
||||
): Promise<RemoteAccessHeadersResponse> {
|
||||
return fetchWrapper<RemoteAccessHeadersResponse>(REMOTE_ACCESS_HEADERS_URL, {
|
||||
return fetchWrapper(REMOTE_ACCESS_HEADERS_URL, RemoteAccessHeadersResponseSchema, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
/** Removes every stored remote-access header. */
|
||||
export async function clearRemoteAccessHeaders(): Promise<RemoteAccessHeadersResponse> {
|
||||
return fetchWrapper<RemoteAccessHeadersResponse>(REMOTE_ACCESS_HEADERS_URL, {
|
||||
return fetchWrapper(REMOTE_ACCESS_HEADERS_URL, RemoteAccessHeadersResponseSchema, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
/** Mints a pairing code and builds the app and browser links for this origin. */
|
||||
export async function createDevicePairingLinks(
|
||||
body: CreateDevicePairingLinksRequest = {},
|
||||
): Promise<DevicePairingLinksResponse> {
|
||||
return fetchWrapper<DevicePairingLinksResponse>(`${API_BASE_URL}/api/device-pairing/links`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/device-pairing/links`, DevicePairingLinksResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
/** Reads whether the Manager can mint pairing codes for an address without minting one. */
|
||||
export async function getDevicePairingAvailability(
|
||||
origin: string,
|
||||
): Promise<DevicePairingAvailability> {
|
||||
return fetchWrapper<DevicePairingAvailability>(
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/device-pairing/availability`,
|
||||
DevicePairingAvailabilitySchema,
|
||||
{ params: { origin } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Lists the devices signed in to this account. */
|
||||
export async function listPairedDevices(): Promise<PairedDevice[]> {
|
||||
const response = await fetchWrapper<PairedDevicesResponse>(
|
||||
const response = await fetchWrapper(
|
||||
`${getAuthBaseUrl()}/device-pairing/devices`,
|
||||
PairedDevicesResponseSchema,
|
||||
)
|
||||
return response.devices
|
||||
}
|
||||
|
||||
/** Signs one paired device out. */
|
||||
export async function revokePairedDevice(id: string): Promise<void> {
|
||||
return fetchWrapperVoid(`${getAuthBaseUrl()}/device-pairing/devices/revoke`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -1,32 +1,55 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
import { createFetchFake, type FetchRouteResult } from '@/test/fetchFake'
|
||||
import { FetchError, fetchWrapper } from './fetchWrapper'
|
||||
|
||||
function respondWith(body: string, status: number) {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { status })))
|
||||
function installFailingRoute(reply: FetchRouteResult): void {
|
||||
const fetchFake = createFetchFake([{ method: 'GET', path: '/api/x', respond: () => reply }])
|
||||
fetchFake.install()
|
||||
}
|
||||
|
||||
describe('fetchWrapper error bodies', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('uses the JSON error message', async () => {
|
||||
respondWith(JSON.stringify({ error: 'Session not found', code: 'NOT_FOUND' }), 404)
|
||||
installFailingRoute({ status: 404, json: { error: 'Session not found', code: 'NOT_FOUND' } })
|
||||
|
||||
await expect(fetchWrapper('/api/x')).rejects.toMatchObject({ message: 'Session not found', statusCode: 404, code: 'NOT_FOUND' })
|
||||
const request = fetchWrapper('/api/x', z.object({}))
|
||||
|
||||
await expect(request).rejects.toBeInstanceOf(FetchError)
|
||||
await expect(request).rejects.toMatchObject({
|
||||
message: 'Session not found',
|
||||
statusCode: 404,
|
||||
code: 'NOT_FOUND',
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a plain-text error body', async () => {
|
||||
respondWith('upstream unavailable', 502)
|
||||
installFailingRoute({ status: 502, text: 'upstream unavailable' })
|
||||
|
||||
await expect(fetchWrapper('/api/x')).rejects.toMatchObject({ message: 'upstream unavailable' })
|
||||
await expect(fetchWrapper('/api/x', z.object({}))).rejects.toMatchObject({
|
||||
message: 'upstream unavailable',
|
||||
})
|
||||
})
|
||||
|
||||
it('replaces an HTML error page with a status message', async () => {
|
||||
respondWith('<!DOCTYPE html><html><body>A timeout occurred</body></html>', 524)
|
||||
installFailingRoute({ status: 524, text: '<!DOCTYPE html><html><body>A timeout occurred</body></html>' })
|
||||
|
||||
const error = await fetchWrapper('/api/x').catch((caught: unknown) => caught)
|
||||
expect(error).toBeInstanceOf(FetchError)
|
||||
expect((error as FetchError).message).toBe('Request failed with status 524')
|
||||
await expect(fetchWrapper('/api/x', z.object({}))).rejects.toMatchObject({
|
||||
message: 'Request failed with status 524',
|
||||
})
|
||||
})
|
||||
|
||||
it('renders validation detail paths that contain array indexes', async () => {
|
||||
installFailingRoute({
|
||||
status: 400,
|
||||
json: {
|
||||
error: 'Invalid request body',
|
||||
details: [{ path: ['items', 0, 'name'], message: 'Required' }],
|
||||
},
|
||||
})
|
||||
|
||||
await expect(fetchWrapper('/api/x', z.object({}))).rejects.toMatchObject({
|
||||
message: 'Invalid request body',
|
||||
detail: 'items.0.name: Required',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from 'zod'
|
||||
import { JsonValueSchema, parseJsonText, type JsonValue } from '@opencode-manager/shared/utils'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import type { ApiErrorResponse } from '@opencode-manager/shared'
|
||||
|
||||
export { FetchError }
|
||||
|
||||
@@ -9,43 +10,58 @@ interface FetchWrapperOptions extends RequestInit {
|
||||
acceptedStatuses?: number[]
|
||||
}
|
||||
|
||||
function formatDetails(details: unknown): string | undefined {
|
||||
const validationIssueSchema = z.object({
|
||||
path: z.string(),
|
||||
message: z.string(),
|
||||
})
|
||||
|
||||
const apiErrorResponseSchema = z.object({
|
||||
error: z.string().optional(),
|
||||
code: z.string().optional(),
|
||||
detail: z.string().optional(),
|
||||
details: JsonValueSchema.optional(),
|
||||
validationIssues: z.array(validationIssueSchema).optional(),
|
||||
message: z.string().optional(),
|
||||
data: z.object({ message: z.string().optional() }).optional(),
|
||||
})
|
||||
|
||||
const validationDetailSchema = z.object({
|
||||
path: z.array(z.union([z.string(), z.number()])).optional(),
|
||||
message: z.string().optional(),
|
||||
})
|
||||
|
||||
type ApiErrorBody = z.infer<typeof apiErrorResponseSchema>
|
||||
|
||||
function formatDetails(details: JsonValue | undefined): string | undefined {
|
||||
if (Array.isArray(details)) {
|
||||
return details
|
||||
.map((d) => {
|
||||
if (typeof d !== 'object' || d === null) return null
|
||||
const path = Array.isArray((d as Record<string, unknown>).path)
|
||||
? ((d as Record<string, unknown>).path as string[])
|
||||
: undefined
|
||||
const message = typeof (d as Record<string, unknown>).message === 'string'
|
||||
? (d as Record<string, unknown>).message as string
|
||||
: undefined
|
||||
return path?.length ? `${path.join('.')}: ${message}` : message
|
||||
.map((detail) => {
|
||||
const parsed = validationDetailSchema.safeParse(detail)
|
||||
if (!parsed.success) return null
|
||||
const path = parsed.data.path
|
||||
const message = parsed.data.message
|
||||
return path && path.length > 0 ? `${path.join('.')}: ${message}` : message
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join('; ')
|
||||
}
|
||||
if (typeof details === 'string') return details
|
||||
return undefined
|
||||
const text = z.string().safeParse(details)
|
||||
return text.success ? text.data : undefined
|
||||
}
|
||||
|
||||
function parseErrorBody(text: string, status: number): ApiErrorBody {
|
||||
if (!text) return { error: 'An error occurred' }
|
||||
const parsed = apiErrorResponseSchema.safeParse(parseJsonText(text))
|
||||
if (parsed.success) return parsed.data
|
||||
return { error: /^\s*</.test(text) ? `Request failed with status ${status}` : text }
|
||||
}
|
||||
|
||||
async function handleResponse(response: Response): Promise<never> {
|
||||
const text = await response.text().catch(() => '')
|
||||
const data: ApiErrorResponse = (() => {
|
||||
if (!text) return { error: 'An error occurred' }
|
||||
try {
|
||||
return JSON.parse(text) as ApiErrorResponse
|
||||
} catch {
|
||||
return { error: /^\s*</.test(text) ? `Request failed with status ${response.status}` : text }
|
||||
}
|
||||
})()
|
||||
const errorData = data as ApiErrorResponse & { message?: string; data?: { message?: unknown } }
|
||||
const openCodeMessage = typeof errorData.data?.message === 'string'
|
||||
? errorData.data.message
|
||||
: undefined
|
||||
const data = parseErrorBody(text, response.status)
|
||||
const detail = data.detail || formatDetails(data.details)
|
||||
throw new FetchError(
|
||||
data.error || errorData.message || openCodeMessage || 'Request failed',
|
||||
data.error || data.message || data.data?.message || 'Request failed',
|
||||
response.status,
|
||||
data.code,
|
||||
detail,
|
||||
@@ -101,17 +117,21 @@ async function fetchWithTimeout(
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchWrapper<T = unknown>(
|
||||
async function fetchWrapper<T>(
|
||||
url: string,
|
||||
schema: z.ZodType<T>,
|
||||
options: FetchWrapperOptions = {}
|
||||
): Promise<T> {
|
||||
const response = await fetchWithTimeout(url, options)
|
||||
|
||||
try {
|
||||
return await response.json()
|
||||
} catch {
|
||||
const body = await response.json().catch(() => {
|
||||
throw new FetchError('Invalid JSON response', response.status, 'INVALID_JSON')
|
||||
})
|
||||
const parsed = schema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
throw new FetchError('Unexpected response body', response.status, 'INVALID_RESPONSE', parsed.error.message)
|
||||
}
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
async function fetchWrapperVoid(
|
||||
|
||||
@@ -2,7 +2,13 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { fetchWrapper, fetchWrapperBlob } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { saveFile } from '@/lib/download'
|
||||
import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@/types/files'
|
||||
import { z } from 'zod'
|
||||
import { ChunkedFileInfoSchema, FileInfoSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@opencode-manager/shared/types'
|
||||
|
||||
const ignoredPathsResponseSchema = z.object({ ignoredPaths: z.array(z.string()) })
|
||||
|
||||
const filePatchResponseSchema = z.object({ success: z.boolean(), totalLines: z.number() })
|
||||
|
||||
interface FileApiUrlOptions {
|
||||
route?: string
|
||||
@@ -24,7 +30,7 @@ export function getFileApiUrl(path: string, options: FileApiUrlOptions = {}): st
|
||||
}
|
||||
|
||||
async function fetchFile(path: string): Promise<FileInfo> {
|
||||
return fetchWrapper(getFileApiUrl(path))
|
||||
return fetchWrapper(getFileApiUrl(path), FileInfoSchema)
|
||||
}
|
||||
|
||||
export function useFile(path: string | undefined) {
|
||||
@@ -36,13 +42,13 @@ export function useFile(path: string | undefined) {
|
||||
}
|
||||
|
||||
export async function fetchFileRange(path: string, startLine: number, endLine: number): Promise<ChunkedFileInfo> {
|
||||
return fetchWrapper(getFileApiUrl(path), {
|
||||
return fetchWrapper(getFileApiUrl(path), ChunkedFileInfoSchema, {
|
||||
params: { startLine, endLine },
|
||||
})
|
||||
}
|
||||
|
||||
export async function getIgnoredPaths(path: string): Promise<{ ignoredPaths: string[] }> {
|
||||
return fetchWrapper(getFileApiUrl(path, { route: 'ignored-paths' }))
|
||||
return fetchWrapper(getFileApiUrl(path, { route: 'ignored-paths' }), ignoredPathsResponseSchema)
|
||||
}
|
||||
|
||||
export interface DownloadOptions {
|
||||
@@ -66,7 +72,7 @@ export async function downloadDirectoryAsZip(path: string, options?: DownloadOpt
|
||||
|
||||
export async function applyFilePatches(path: string, patches: PatchOperation[]): Promise<{ success: boolean; totalLines: number }> {
|
||||
const url = getFileApiUrl(path)
|
||||
return fetchWrapper(url, {
|
||||
return fetchWrapper(url, filePatchResponseSchema, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ patches }),
|
||||
})
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { BrowseDirectoryResponseSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { BrowseDirectoryResponse } from '@opencode-manager/shared/types'
|
||||
|
||||
export async function browseDirectory(path?: string): Promise<BrowseDirectoryResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/filesystem/browse`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/filesystem/browse`, BrowseDirectoryResponseSchema, {
|
||||
params: { path },
|
||||
})
|
||||
}
|
||||
+113
-41
@@ -1,15 +1,81 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import {
|
||||
DeleteBranchResultSchema,
|
||||
GitOperationStateSchema,
|
||||
GitStashEntrySchema,
|
||||
IntegrateBranchResultSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { DeleteBranchRequest, DeleteBranchResult, GitStashEntry, IntegrateBranchRequest, IntegrateBranchResult, RenameBranchRequest, StashApplyRequest, StashDropRequest, StashPushRequest } from '@opencode-manager/shared'
|
||||
import type { GitStatusResponse, FileDiffResponse, GitCommit, CommitDetails } from '@/types/git'
|
||||
|
||||
const gitFileStatusTypeSchema = z.enum(['modified', 'added', 'deleted', 'renamed', 'untracked', 'copied'])
|
||||
|
||||
const gitFileStatusSchema = z.object({
|
||||
path: z.string(),
|
||||
status: gitFileStatusTypeSchema,
|
||||
staged: z.boolean(),
|
||||
oldPath: z.string().optional(),
|
||||
additions: z.number().optional(),
|
||||
deletions: z.number().optional(),
|
||||
})
|
||||
|
||||
const gitStatusResponseSchema: z.ZodType<GitStatusResponse> = z.object({
|
||||
branch: z.string(),
|
||||
ahead: z.number(),
|
||||
behind: z.number(),
|
||||
files: z.array(gitFileStatusSchema),
|
||||
hasChanges: z.boolean(),
|
||||
operation: GitOperationStateSchema.nullable(),
|
||||
})
|
||||
|
||||
const fileDiffResponseSchema: z.ZodType<FileDiffResponse> = z.object({
|
||||
path: z.string(),
|
||||
status: gitFileStatusTypeSchema,
|
||||
diff: z.string().nullable(),
|
||||
additions: z.number(),
|
||||
deletions: z.number(),
|
||||
isBinary: z.boolean(),
|
||||
truncated: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const gitCommitBaseSchema = z.object({
|
||||
hash: z.string(),
|
||||
authorName: z.string(),
|
||||
authorEmail: z.string(),
|
||||
date: z.string(),
|
||||
message: z.string(),
|
||||
unpushed: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const commitFileSchema = z.object({
|
||||
path: z.string(),
|
||||
status: gitFileStatusTypeSchema,
|
||||
oldPath: z.string().optional(),
|
||||
additions: z.number(),
|
||||
deletions: z.number(),
|
||||
})
|
||||
|
||||
const gitCommitSchema: z.ZodType<GitCommit> = gitCommitBaseSchema
|
||||
|
||||
const commitDetailsSchema: z.ZodType<CommitDetails> = gitCommitBaseSchema.extend({
|
||||
files: z.array(commitFileSchema),
|
||||
})
|
||||
|
||||
const gitLogResponseSchema = z.object({ commits: z.array(gitCommitSchema) })
|
||||
const gitStashesResponseSchema = z.object({ stashes: z.array(GitStashEntrySchema) })
|
||||
const commitMessageResponseSchema = z.object({ message: z.string() })
|
||||
const deleteBranchResponseSchema = DeleteBranchResultSchema.extend({ status: gitStatusResponseSchema })
|
||||
const integrateBranchResponseSchema = IntegrateBranchResultSchema.extend({ targetStatus: gitStatusResponseSchema })
|
||||
|
||||
export async function fetchGitStatus(repoId: number): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/status`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/status`, gitStatusResponseSchema)
|
||||
}
|
||||
|
||||
export async function fetchReposGitStatus(repoIds: number[]): Promise<Map<number, GitStatusResponse>> {
|
||||
const data = await fetchWrapper<Record<string, GitStatusResponse>>(`${API_BASE_URL}/api/repos/git-status-batch`, {
|
||||
const data = await fetchWrapper(`${API_BASE_URL}/api/repos/git-status-batch`, z.record(z.string(), gitStatusResponseSchema), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ repoIds })
|
||||
@@ -18,48 +84,48 @@ export async function fetchReposGitStatus(repoIds: number[]): Promise<Map<number
|
||||
}
|
||||
|
||||
export async function fetchFileDiff(repoId: number, path: string, includeStaged?: boolean): Promise<FileDiffResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/diff-full`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/diff-full`, fileDiffResponseSchema, {
|
||||
params: { path, includeStaged },
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchCommitFileDiff(repoId: number, commitHash: string, path: string): Promise<FileDiffResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit/${commitHash}/diff`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit/${commitHash}/diff`, fileDiffResponseSchema, {
|
||||
params: { path },
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchGitDiff(repoId: number, path: string): Promise<{ diff: string }> {
|
||||
const data = await fetchWrapper<string>(`${API_BASE_URL}/api/repos/${repoId}/git/diff`, {
|
||||
const data = await fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/diff`, z.string(), {
|
||||
params: { path },
|
||||
})
|
||||
return { diff: data }
|
||||
}
|
||||
|
||||
export async function fetchGitLog(repoId: number, limit?: number, branch?: string): Promise<{ commits: GitCommit[] }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/log`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/log`, gitLogResponseSchema, {
|
||||
params: { limit, branch },
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchCommitDetails(repoId: number, hash: string): Promise<CommitDetails> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit/${hash}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit/${hash}`, commitDetailsSchema)
|
||||
}
|
||||
|
||||
export async function gitFetch(repoId: number): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/fetch`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/fetch`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function gitPull(repoId: number): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/pull`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/pull`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function gitPush(repoId: number, setUpstream: boolean = false): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/push`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/push`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ setUpstream }),
|
||||
@@ -67,7 +133,7 @@ export async function gitPush(repoId: number, setUpstream: boolean = false): Pro
|
||||
}
|
||||
|
||||
export async function gitCommit(repoId: number, message: string, stagedPaths?: string[]): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message, stagedPaths }),
|
||||
@@ -75,13 +141,13 @@ export async function gitCommit(repoId: number, message: string, stagedPaths?: s
|
||||
}
|
||||
|
||||
export async function gitGenerateCommitMessage(repoId: number): Promise<{ message: string }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit-message`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/commit-message`, commitMessageResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function gitStageFiles(repoId: number, paths: string[]): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stage`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stage`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths }),
|
||||
@@ -89,7 +155,7 @@ export async function gitStageFiles(repoId: number, paths: string[]): Promise<Gi
|
||||
}
|
||||
|
||||
export async function gitUnstageFiles(repoId: number, paths: string[]): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/unstage`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/unstage`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths }),
|
||||
@@ -97,7 +163,7 @@ export async function gitUnstageFiles(repoId: number, paths: string[]): Promise<
|
||||
}
|
||||
|
||||
export async function gitDiscardFiles(repoId: number, paths: string[], staged: boolean): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/discard`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/discard`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ paths, staged }),
|
||||
@@ -105,7 +171,7 @@ export async function gitDiscardFiles(repoId: number, paths: string[], staged: b
|
||||
}
|
||||
|
||||
export async function gitReset(repoId: number, commitHash: string): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/reset`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/reset`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ commitHash }),
|
||||
@@ -113,7 +179,7 @@ export async function gitReset(repoId: number, commitHash: string): Promise<GitS
|
||||
}
|
||||
|
||||
export async function gitRenameBranch(repoId: number, request: RenameBranchRequest): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/branches/rename`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/branches/rename`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -124,7 +190,7 @@ export async function gitDeleteBranch(
|
||||
repoId: number,
|
||||
request: DeleteBranchRequest
|
||||
): Promise<DeleteBranchResult & { status: GitStatusResponse }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/branches`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/branches`, deleteBranchResponseSchema, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -132,11 +198,11 @@ export async function gitDeleteBranch(
|
||||
}
|
||||
|
||||
async function fetchGitStashes(repoId: number): Promise<{ stashes: GitStashEntry[] }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash`, gitStashesResponseSchema)
|
||||
}
|
||||
|
||||
export async function gitStashPush(repoId: number, request: StashPushRequest): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -144,7 +210,7 @@ export async function gitStashPush(repoId: number, request: StashPushRequest): P
|
||||
}
|
||||
|
||||
export async function gitStashApply(repoId: number, index: number, request: StashApplyRequest): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash/${index}/apply`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash/${index}/apply`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -152,7 +218,7 @@ export async function gitStashApply(repoId: number, index: number, request: Stas
|
||||
}
|
||||
|
||||
export async function gitStashDrop(repoId: number, index: number, request: StashDropRequest): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash/${index}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/stash/${index}`, gitStatusResponseSchema, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -160,13 +226,13 @@ export async function gitStashDrop(repoId: number, index: number, request: Stash
|
||||
}
|
||||
|
||||
export async function gitContinueOperation(repoId: number): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/operation/continue`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/operation/continue`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function gitAbortOperation(repoId: number): Promise<GitStatusResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/operation/abort`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/operation/abort`, gitStatusResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
@@ -175,7 +241,7 @@ export async function gitIntegrateBranch(
|
||||
repoId: number,
|
||||
request: IntegrateBranchRequest
|
||||
): Promise<IntegrateBranchResult & { targetStatus: GitStatusResponse }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/integrate`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/git/integrate`, integrateBranchResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -257,29 +323,35 @@ function parseGitErrorMessage(message: string): string {
|
||||
return message
|
||||
}
|
||||
|
||||
export function getApiErrorMessage(error: unknown): string {
|
||||
if (error instanceof FetchError) {
|
||||
if (error.code === 'AUTH_FAILED') {
|
||||
const gitErrorBodySchema = z.object({
|
||||
message: z.string().optional(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
|
||||
export function getApiErrorMessage(cause: unknown): string {
|
||||
if (cause instanceof FetchError) {
|
||||
if (cause.code === 'AUTH_FAILED') {
|
||||
return 'Git authentication failed. Check your credentials in Settings.'
|
||||
}
|
||||
if (error.code === 'CONFLICT') {
|
||||
if (cause.code === 'CONFLICT') {
|
||||
return 'Merge conflict detected. Resolve conflicts before continuing.'
|
||||
}
|
||||
if (error.code === 'NOT_FOUND') {
|
||||
if (cause.code === 'NOT_FOUND') {
|
||||
return 'Repository or file not found.'
|
||||
}
|
||||
if (error.statusCode === 401) return 'Git authentication failed. Check your credentials in Settings.'
|
||||
if (error.statusCode === 409) return 'Merge conflict detected. Resolve conflicts before continuing.'
|
||||
if (error.statusCode === 404) return 'Repository or file not found.'
|
||||
return parseGitErrorMessage(error.message)
|
||||
if (cause.statusCode === 401) return 'Git authentication failed. Check your credentials in Settings.'
|
||||
if (cause.statusCode === 409) return 'Merge conflict detected. Resolve conflicts before continuing.'
|
||||
if (cause.statusCode === 404) return 'Repository or file not found.'
|
||||
return parseGitErrorMessage(cause.message)
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return parseGitErrorMessage(error.message)
|
||||
if (cause instanceof Error) {
|
||||
return parseGitErrorMessage(cause.message)
|
||||
}
|
||||
if (typeof error === 'string') {
|
||||
return parseGitErrorMessage(error)
|
||||
const stringCause = z.string().safeParse(cause)
|
||||
if (stringCause.success) {
|
||||
return parseGitErrorMessage(stringCause.data)
|
||||
}
|
||||
const err = error as { status?: number; message?: string; error?: string }
|
||||
const message = err?.message || err?.error || String(error) || 'An error occurred'
|
||||
return parseGitErrorMessage(message)
|
||||
const body = gitErrorBodySchema.safeParse(cause)
|
||||
const message = (body.success ? body.data.message ?? body.data.error : undefined) ?? String(cause)
|
||||
return parseGitErrorMessage(message || 'An error occurred')
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import type {
|
||||
ManagerLogLevel,
|
||||
ManagerLogSource,
|
||||
ManagerLogsResponse,
|
||||
import {
|
||||
ManagerLogsResponseSchema,
|
||||
type ManagerLogLevel,
|
||||
type ManagerLogSource,
|
||||
type ManagerLogsResponse,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
@@ -15,7 +16,7 @@ export interface GetManagerLogsQuery {
|
||||
|
||||
export const logsApi = {
|
||||
getManagerLogs: (query: GetManagerLogsQuery = {}): Promise<ManagerLogsResponse> => {
|
||||
return fetchWrapper<ManagerLogsResponse>(`${API_BASE_URL}/api/logs`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/logs`, ManagerLogsResponseSchema, {
|
||||
params: { ...query },
|
||||
})
|
||||
},
|
||||
|
||||
+24
-12
@@ -1,3 +1,4 @@
|
||||
import { z } from 'zod'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { callOpenCode } from './opencodeApi'
|
||||
@@ -10,16 +11,21 @@ import {
|
||||
|
||||
export type { McpServerConfig, McpStatus } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export interface McpAuthStartResponse {
|
||||
authorizationUrl: string
|
||||
flowId: string
|
||||
}
|
||||
const mcpAuthStartResponseSchema = z.object({
|
||||
authorizationUrl: z.string(),
|
||||
flowId: z.string(),
|
||||
})
|
||||
|
||||
type McpOAuthFlowStatus =
|
||||
| { status: 'pending' }
|
||||
| { status: 'completed'; serverName: string }
|
||||
| { status: 'failed'; error: string }
|
||||
| { status: 'unknown' }
|
||||
export type McpAuthStartResponse = z.infer<typeof mcpAuthStartResponseSchema>
|
||||
|
||||
const mcpOAuthFlowStatusSchema = z.discriminatedUnion('status', [
|
||||
z.object({ status: z.literal('pending') }),
|
||||
z.object({ status: z.literal('completed'), serverName: z.string() }),
|
||||
z.object({ status: z.literal('failed'), error: z.string() }),
|
||||
z.object({ status: z.literal('unknown') }),
|
||||
])
|
||||
|
||||
type McpOAuthFlowStatus = z.infer<typeof mcpOAuthFlowStatusSchema>
|
||||
|
||||
export const mcpApi = {
|
||||
async getStatus(directory?: string, serverId?: string): Promise<McpStatusMap> {
|
||||
@@ -52,7 +58,7 @@ export const mcpApi = {
|
||||
},
|
||||
|
||||
async startAuth(name: string, directory?: string): Promise<McpAuthStartResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/mcp-oauth-proxy/start`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/mcp-oauth-proxy/start`, mcpAuthStartResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ serverName: name, directory }),
|
||||
@@ -61,14 +67,20 @@ export const mcpApi = {
|
||||
|
||||
async checkFlowStatus(flowId: string): Promise<McpOAuthFlowStatus> {
|
||||
try {
|
||||
return await fetchWrapper(`${API_BASE_URL}/api/mcp-oauth-proxy/status/${encodeURIComponent(flowId)}`)
|
||||
return await fetchWrapper(
|
||||
`${API_BASE_URL}/api/mcp-oauth-proxy/status/${encodeURIComponent(flowId)}`,
|
||||
mcpOAuthFlowStatusSchema,
|
||||
)
|
||||
} catch {
|
||||
return { status: 'unknown' }
|
||||
}
|
||||
},
|
||||
|
||||
async removeAuth(name: string, directory?: string): Promise<{ success: true }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/mcp-oauth-proxy/credentials/${encodeURIComponent(name)}`, {
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/mcp-oauth-proxy/credentials/${encodeURIComponent(name)}`,
|
||||
z.object({ success: z.literal(true) }),
|
||||
{
|
||||
method: 'DELETE',
|
||||
params: directory ? { directory } : undefined,
|
||||
})
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { z } from 'zod'
|
||||
import { MultiRunSchema } from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
FuseMultiRunRequest,
|
||||
LaunchMultiRunRequest,
|
||||
@@ -7,6 +9,9 @@ import type {
|
||||
MultiRunTarget,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
const multiRunsResponseSchema = z.object({ runs: z.array(MultiRunSchema) })
|
||||
const multiRunResponseSchema = z.object({ run: MultiRunSchema })
|
||||
|
||||
function targetParams(target: MultiRunTarget): Record<string, string | number> {
|
||||
return target.kind === 'repo'
|
||||
? { repoId: target.repoId }
|
||||
@@ -14,14 +19,14 @@ function targetParams(target: MultiRunTarget): Record<string, string | number> {
|
||||
}
|
||||
|
||||
export async function listMultiRuns(target: MultiRunTarget): Promise<MultiRun[]> {
|
||||
const res = await fetchWrapper<{ runs: MultiRun[] }>(`${API_BASE_URL}/api/multi-runs`, {
|
||||
const res = await fetchWrapper(`${API_BASE_URL}/api/multi-runs`, multiRunsResponseSchema, {
|
||||
params: targetParams(target),
|
||||
})
|
||||
return res.runs
|
||||
}
|
||||
|
||||
export async function launchMultiRun(request: LaunchMultiRunRequest): Promise<MultiRun> {
|
||||
const res = await fetchWrapper<{ run: MultiRun }>(`${API_BASE_URL}/api/multi-runs`, {
|
||||
const res = await fetchWrapper(`${API_BASE_URL}/api/multi-runs`, multiRunResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -30,8 +35,9 @@ export async function launchMultiRun(request: LaunchMultiRunRequest): Promise<Mu
|
||||
}
|
||||
|
||||
export async function fuseMultiRun(runId: number, request: FuseMultiRunRequest): Promise<MultiRun> {
|
||||
const res = await fetchWrapper<{ run: MultiRun }>(
|
||||
const res = await fetchWrapper(
|
||||
`${API_BASE_URL}/api/multi-runs/${encodeURIComponent(runId)}/fusions`,
|
||||
multiRunResponseSchema,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -42,8 +48,9 @@ export async function fuseMultiRun(runId: number, request: FuseMultiRunRequest):
|
||||
}
|
||||
|
||||
export async function discardMultiRunEntry(runId: number, entryId: number): Promise<MultiRun> {
|
||||
const res = await fetchWrapper<{ run: MultiRun }>(
|
||||
const res = await fetchWrapper(
|
||||
`${API_BASE_URL}/api/multi-runs/${encodeURIComponent(runId)}/entries/${encodeURIComponent(entryId)}/discard`,
|
||||
multiRunResponseSchema,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
return res.run
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import type { PushSubscriptionRecord } from "@opencode-manager/shared/types";
|
||||
import { z } from "zod";
|
||||
import { API_BASE_URL } from "@/config";
|
||||
import { PushSubscriptionRecordSchema } from "@opencode-manager/shared/schemas";
|
||||
import type { PushSubscriptionRecord } from "@opencode-manager/shared/types";
|
||||
import { fetchWrapper } from "./fetchWrapper";
|
||||
|
||||
const vapidPublicKeyResponseSchema = z.object({ publicKey: z.string() });
|
||||
const subscriptionResponseSchema = z.object({ subscription: PushSubscriptionRecordSchema });
|
||||
const successResponseSchema = z.object({ success: z.boolean() });
|
||||
const subscriptionsResponseSchema = z.object({ subscriptions: z.array(PushSubscriptionRecordSchema) });
|
||||
const testNotificationResponseSchema = z.object({ success: z.boolean(), devicesNotified: z.number() });
|
||||
|
||||
export const notificationsApi = {
|
||||
getVapidPublicKey: async (): Promise<{ publicKey: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/vapid-public-key`);
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/vapid-public-key`, vapidPublicKeyResponseSchema);
|
||||
},
|
||||
|
||||
subscribe: async (
|
||||
@@ -12,7 +20,7 @@ export const notificationsApi = {
|
||||
deviceName?: string,
|
||||
userId = 'default'
|
||||
): Promise<{ subscription: PushSubscriptionRecord }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscribe`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscribe`, subscriptionResponseSchema, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -25,7 +33,7 @@ export const notificationsApi = {
|
||||
},
|
||||
|
||||
unsubscribe: async (endpoint: string, userId = 'default'): Promise<{ success: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscribe`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscribe`, successResponseSchema, {
|
||||
method: "DELETE",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ endpoint }),
|
||||
@@ -36,7 +44,7 @@ export const notificationsApi = {
|
||||
getSubscriptions: async (userId = 'default'): Promise<{
|
||||
subscriptions: PushSubscriptionRecord[];
|
||||
}> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscriptions`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/subscriptions`, subscriptionsResponseSchema, {
|
||||
params: { userId },
|
||||
});
|
||||
},
|
||||
@@ -47,6 +55,7 @@ export const notificationsApi = {
|
||||
): Promise<{ success: boolean }> => {
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/notifications/subscriptions/${id}`,
|
||||
successResponseSchema,
|
||||
{ method: "DELETE", params: { userId } }
|
||||
);
|
||||
},
|
||||
@@ -55,7 +64,7 @@ export const notificationsApi = {
|
||||
success: boolean;
|
||||
devicesNotified: number;
|
||||
}> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/test`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/notifications/test`, testNotificationResponseSchema, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
params: { userId },
|
||||
|
||||
+102
-4
@@ -1,5 +1,7 @@
|
||||
import { API_BASE_URL } from "@/config"
|
||||
import { z } from "zod"
|
||||
import type { FormAnswer, IntegrationInfo, IntegrationMethod } from "@opencode-manager/shared/opencode"
|
||||
import { OAuthAttemptStatusSchema, OAuthAuthorizeResponseSchema } from "@opencode-manager/shared/schemas"
|
||||
import type { OAuthAttemptStatus, OAuthAuthorizeResponse } from "@opencode-manager/shared/schemas"
|
||||
import { fetchWrapper, fetchWrapperVoid } from "./fetchWrapper"
|
||||
import { callOpenCode } from "./opencodeApi"
|
||||
@@ -18,16 +20,111 @@ export type { OAuthAuthorizeResponse } from "@opencode-manager/shared/schemas"
|
||||
|
||||
type ProviderAuthMethods = Record<string, IntegrationMethod[]>
|
||||
|
||||
const formWhenSchema = z.object({
|
||||
key: z.string(),
|
||||
op: z.enum(['eq', 'neq']),
|
||||
value: z.union([z.string(), z.number(), z.boolean()]),
|
||||
})
|
||||
|
||||
const formOptionSchema = z.object({
|
||||
value: z.string(),
|
||||
label: z.string(),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
|
||||
const formFieldBase = {
|
||||
key: z.string(),
|
||||
title: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
required: z.boolean().optional(),
|
||||
hidden: z.boolean().optional(),
|
||||
when: z.array(formWhenSchema).optional(),
|
||||
}
|
||||
|
||||
const formStringFieldSchema = z.object({
|
||||
...formFieldBase,
|
||||
type: z.literal('string'),
|
||||
format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),
|
||||
minLength: z.number().optional(),
|
||||
maxLength: z.number().optional(),
|
||||
pattern: z.string().optional(),
|
||||
placeholder: z.string().optional(),
|
||||
default: z.string().optional(),
|
||||
options: z.array(formOptionSchema).optional(),
|
||||
custom: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const formNumberFieldSchema = z.object({
|
||||
...formFieldBase,
|
||||
type: z.literal('number'),
|
||||
minimum: z.union([z.number(), z.literal('Infinity'), z.literal('-Infinity'), z.literal('NaN')]).optional(),
|
||||
maximum: z.union([z.number(), z.literal('Infinity'), z.literal('-Infinity'), z.literal('NaN')]).optional(),
|
||||
default: z.union([z.number(), z.literal('Infinity'), z.literal('-Infinity'), z.literal('NaN')]).optional(),
|
||||
})
|
||||
|
||||
const formIntegerFieldSchema = z.object({
|
||||
...formFieldBase,
|
||||
type: z.literal('integer'),
|
||||
minimum: z.union([z.number(), z.literal('Infinity'), z.literal('-Infinity'), z.literal('NaN')]).optional(),
|
||||
maximum: z.union([z.number(), z.literal('Infinity'), z.literal('-Infinity'), z.literal('NaN')]).optional(),
|
||||
default: z.union([z.number(), z.literal('Infinity'), z.literal('-Infinity'), z.literal('NaN')]).optional(),
|
||||
})
|
||||
|
||||
const formBooleanFieldSchema = z.object({
|
||||
...formFieldBase,
|
||||
type: z.literal('boolean'),
|
||||
default: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const formMultiselectFieldSchema = z.object({
|
||||
...formFieldBase,
|
||||
type: z.literal('multiselect'),
|
||||
options: z.array(formOptionSchema),
|
||||
minItems: z.number().optional(),
|
||||
maxItems: z.number().optional(),
|
||||
custom: z.boolean().optional(),
|
||||
default: z.array(z.string()).optional(),
|
||||
})
|
||||
|
||||
const formExternalFieldSchema = z.object({
|
||||
key: z.string(),
|
||||
type: z.literal('external'),
|
||||
url: z.string(),
|
||||
title: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
|
||||
const formFieldSchema = z.discriminatedUnion('type', [
|
||||
formStringFieldSchema,
|
||||
formNumberFieldSchema,
|
||||
formIntegerFieldSchema,
|
||||
formBooleanFieldSchema,
|
||||
formMultiselectFieldSchema,
|
||||
formExternalFieldSchema,
|
||||
])
|
||||
|
||||
const formFieldsSchema = z.tuple([formFieldSchema]).rest(formFieldSchema)
|
||||
|
||||
const integrationMethodSchema = z.discriminatedUnion('type', [
|
||||
z.object({ id: z.string(), type: z.literal('oauth'), label: z.string(), form: formFieldsSchema.optional() }),
|
||||
z.object({ id: z.string(), type: z.literal('command'), label: z.string(), command: z.array(z.string()) }),
|
||||
z.object({ type: z.literal('key'), label: z.string().optional(), form: formFieldsSchema.optional() }),
|
||||
z.object({ id: z.string(), type: z.literal('external'), label: z.string(), form: formFieldsSchema.optional() }),
|
||||
z.object({ type: z.literal('env'), names: z.array(z.string()) }),
|
||||
])
|
||||
|
||||
const providerAuthMethodsSchema = z.record(z.string(), z.array(integrationMethodSchema))
|
||||
|
||||
export const oauthApi = {
|
||||
authorize: async (providerId: string, methodID: string, answer?: FormAnswer): Promise<OAuthAuthorizeResponse> =>
|
||||
fetchWrapper<OAuthAuthorizeResponse>(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, {
|
||||
fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/authorize`, OAuthAuthorizeResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ methodID, answer }),
|
||||
}),
|
||||
|
||||
getStatus: async (providerId: string, attemptID: string): Promise<OAuthAttemptStatus> =>
|
||||
fetchWrapper<OAuthAttemptStatus>(`${API_BASE_URL}/api/oauth/${providerId}/oauth/${attemptID}`),
|
||||
fetchWrapper(`${API_BASE_URL}/api/oauth/${providerId}/oauth/${attemptID}`, OAuthAttemptStatusSchema),
|
||||
|
||||
callback: async (providerId: string, attemptID: string, code?: string): Promise<void> =>
|
||||
fetchWrapperVoid(`${API_BASE_URL}/api/oauth/${providerId}/oauth/callback`, {
|
||||
@@ -42,8 +139,9 @@ export const oauthApi = {
|
||||
}),
|
||||
|
||||
getAuthMethods: async (): Promise<ProviderAuthMethods> => {
|
||||
const { providers } = await fetchWrapper<{ providers: ProviderAuthMethods }>(
|
||||
`${API_BASE_URL}/api/oauth/auth-methods`
|
||||
const { providers } = await fetchWrapper(
|
||||
`${API_BASE_URL}/api/oauth/auth-methods`,
|
||||
z.object({ providers: providerAuthMethodsSchema }),
|
||||
)
|
||||
return providers
|
||||
},
|
||||
|
||||
+319
-399
File diff suppressed because it is too large.
Load diff
@@ -40,38 +40,15 @@ export type OpenCodeLocationInfo = Awaited<ReturnType<OpenCodeApi['location']['g
|
||||
|
||||
export type OpenCodeProject = Awaited<ReturnType<OpenCodeApi['project']['list']>>[number]
|
||||
|
||||
/** A project paired with the timestamp that represents its most recent activity. */
|
||||
export interface RemoteProjectActivity {
|
||||
project: OpenCodeProject
|
||||
activityAt: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Orders projects from the most to the least recently updated.
|
||||
*
|
||||
* A project's own update time covers metadata edits and registration, not work, so this is the
|
||||
* ordering used when no session evidence is available.
|
||||
*
|
||||
* @param projects Projects to order.
|
||||
* @returns A new array with the projects sorted by update time; the input is left untouched.
|
||||
*/
|
||||
export function sortProjectsByUpdatedAt(projects: OpenCodeProject[]): OpenCodeProject[] {
|
||||
return [...projects].sort((a, b) => b.time.updated - a.time.updated)
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives each project's activity time from the newest session of the server that belongs to it and
|
||||
* orders projects by that time.
|
||||
*
|
||||
* Session update times record work; a project's own update time only records metadata edits and
|
||||
* registration, so projects without a session in the given page fall back to it and sort after the
|
||||
* session-backed ones. `time.active` is deliberately unused: OpenCode stamps it on every location
|
||||
* boot, including boots caused by other clients and idle evictions.
|
||||
*
|
||||
* @param projects Projects of one server.
|
||||
* @param sessions Sessions of that server, as returned by a first session page.
|
||||
* @returns The projects with their activity time, most recently active first.
|
||||
*/
|
||||
export function rankProjectsBySessionActivity(
|
||||
projects: OpenCodeProject[],
|
||||
sessions: SessionInfo[],
|
||||
@@ -102,24 +79,10 @@ export function rankProjectsBySessionActivity(
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the display name of a project, falling back to the name of its directory.
|
||||
*
|
||||
* @param project Project whose name is resolved.
|
||||
* @returns The trimmed project name, or the last segment of its canonical directory.
|
||||
*/
|
||||
export function remoteProjectName(project: OpenCodeProject): string {
|
||||
return project.name?.trim() || getDirectoryName(project.canonical)
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the project that owns a directory, matching its canonical directory and anything nested
|
||||
* inside it. Nested projects share a canonical prefix, so the deepest match owns the directory.
|
||||
*
|
||||
* @param projects Projects of the server that owns the directory.
|
||||
* @param directory Directory whose owning project is resolved.
|
||||
* @returns The owning project, or undefined when the directory belongs to none of them.
|
||||
*/
|
||||
export function findRemoteProjectForDirectory(
|
||||
projects: OpenCodeProject[],
|
||||
directory: string,
|
||||
@@ -184,17 +147,13 @@ type PromptFields = Pick<SendPromptInput, 'text' | 'files' | 'agents' | 'skills'
|
||||
function buildPromptFields(input: PromptFields) {
|
||||
return {
|
||||
text: input.text,
|
||||
...(input.files ? { files: input.files } : {}),
|
||||
...(input.agents ? { agents: input.agents } : {}),
|
||||
...(input.skills ? { skills: input.skills } : {}),
|
||||
...(input.delivery ? { delivery: input.delivery } : {}),
|
||||
files: input.files,
|
||||
agents: input.agents,
|
||||
skills: input.skills,
|
||||
delivery: input.delivery,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches one page of sessions for the given list options and normalizes the
|
||||
* server cursor so the end of the list is `undefined` rather than null.
|
||||
*/
|
||||
export async function listSessionPage(input: SessionPageInput, serverId?: string): Promise<SessionPage> {
|
||||
const { data, cursor } = await callOpenCode((api) => api.session.list(input), serverId)
|
||||
return { items: data, nextCursor: cursor.next ?? undefined }
|
||||
@@ -212,14 +171,6 @@ export async function getSession(sessionID: string, serverId?: string): Promise<
|
||||
return callOpenCode((api) => api.session.get({ sessionID }), serverId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a session goal through the OpenCode goal RPC.
|
||||
*
|
||||
* @param sessionID The session whose goal is read.
|
||||
* @param directory Directory of the session's project, once it is known.
|
||||
* @param serverId Server that owns the session, when it is not the local one.
|
||||
* @returns The goal, or an unsupported result when the server has no goal RPC.
|
||||
*/
|
||||
export async function getSessionGoal(
|
||||
sessionID: string,
|
||||
directory: string | undefined,
|
||||
@@ -233,9 +184,9 @@ export async function createSession(input: CreateSessionInput, serverId?: string
|
||||
return callOpenCode(
|
||||
(api) =>
|
||||
api.session.create({
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(input.agent !== undefined ? { agent: input.agent } : {}),
|
||||
...(model ? { model } : {}),
|
||||
title: input.title,
|
||||
agent: input.agent,
|
||||
model,
|
||||
location: { directory: input.directory },
|
||||
}),
|
||||
serverId,
|
||||
@@ -255,7 +206,7 @@ export async function forkSession(sessionID: string, before?: string, serverId?:
|
||||
(api) =>
|
||||
api.session.fork({
|
||||
sessionID,
|
||||
...(before ? { before } : {}),
|
||||
before,
|
||||
}),
|
||||
serverId,
|
||||
)
|
||||
@@ -267,7 +218,7 @@ export async function addSessionContext(sessionID: string, text: string, serverI
|
||||
|
||||
async function createSessionThen(
|
||||
input: CreateSessionInput,
|
||||
step: (session: SessionInfo) => Promise<unknown>,
|
||||
step: (session: SessionInfo) => Promise<void>,
|
||||
serverId?: string,
|
||||
): Promise<SessionInfo> {
|
||||
const session = await createSession(input, serverId)
|
||||
@@ -295,7 +246,9 @@ export async function createSessionWithPrompt(
|
||||
): Promise<SessionInfo> {
|
||||
return createSessionThen(
|
||||
input,
|
||||
(session) => sendPrompt({ sessionID: session.id, text }, serverId),
|
||||
async (session) => {
|
||||
await sendPrompt({ sessionID: session.id, text }, serverId)
|
||||
},
|
||||
serverId,
|
||||
)
|
||||
}
|
||||
@@ -308,7 +261,6 @@ export async function switchSessionAgent(sessionID: string, agent: string, serve
|
||||
await callOpenCode((api) => api.session.switchAgent({ sessionID, agent }), serverId)
|
||||
}
|
||||
|
||||
/** Sends a session prompt with client metadata derived from the current viewport. */
|
||||
export async function sendPrompt(input: SendPromptInput, serverId?: string): Promise<SessionInboxUser> {
|
||||
return callOpenCode(
|
||||
(api) =>
|
||||
@@ -365,15 +317,6 @@ export async function backgroundSession(sessionID: string, serverId?: string): P
|
||||
await callOpenCode((api) => api.session.background({ sessionID }), serverId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores one instruction entry on a session, which the model is told about at
|
||||
* the next step boundary.
|
||||
*
|
||||
* @param sessionID The session that receives the instruction.
|
||||
* @param key Stable key of the instruction entry.
|
||||
* @param text Instruction text stored under the key.
|
||||
* @param serverId Server that owns the session, when it is not the local one.
|
||||
*/
|
||||
export async function putSessionInstruction(
|
||||
sessionID: string,
|
||||
key: string,
|
||||
@@ -386,13 +329,6 @@ export async function putSessionInstruction(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one instruction entry from a session.
|
||||
*
|
||||
* @param sessionID The session that holds the instruction.
|
||||
* @param key Stable key of the instruction entry.
|
||||
* @param serverId Server that owns the session, when it is not the local one.
|
||||
*/
|
||||
export async function removeSessionInstruction(
|
||||
sessionID: string,
|
||||
key: string,
|
||||
@@ -404,13 +340,6 @@ export async function removeSessionInstruction(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the keys of the instruction entries a session holds.
|
||||
*
|
||||
* @param sessionID The session whose instruction keys are read.
|
||||
* @param serverId Server that owns the session, when it is not the local one.
|
||||
* @returns The stored instruction keys, in the order the server reports them.
|
||||
*/
|
||||
export async function listSessionInstructionKeys(
|
||||
sessionID: string,
|
||||
serverId?: string,
|
||||
@@ -523,10 +452,6 @@ export async function listPendingPermissions(
|
||||
return data
|
||||
}
|
||||
|
||||
/**
|
||||
* Replies to a pending permission request with the user's decision, sending the
|
||||
* optional message only when one is supplied.
|
||||
*/
|
||||
export async function replyPermission(
|
||||
sessionID: string,
|
||||
requestID: string,
|
||||
@@ -540,7 +465,7 @@ export async function replyPermission(
|
||||
sessionID,
|
||||
requestID,
|
||||
decision,
|
||||
...(message ? { message } : {}),
|
||||
message,
|
||||
}),
|
||||
serverId,
|
||||
)
|
||||
@@ -578,8 +503,9 @@ export async function listSessionMessages(
|
||||
(api) =>
|
||||
api.message.list({
|
||||
sessionID,
|
||||
...(input.limit === undefined ? {} : { limit: input.limit }),
|
||||
...(input.cursor === undefined ? { order: 'desc' as const } : { cursor: input.cursor }),
|
||||
limit: input.limit,
|
||||
cursor: input.cursor,
|
||||
order: input.cursor === undefined ? 'desc' : undefined,
|
||||
}),
|
||||
serverId,
|
||||
)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { z } from 'zod'
|
||||
import { ClientError, createOpenCodeApi, openCodeErrorStatus, type OpenCodeApi } from '@opencode-manager/shared/opencode'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
@@ -5,7 +6,8 @@ import { API_BASE_URL, OPENCODE_API_ENDPOINT } from '@/config'
|
||||
|
||||
const openCodeApis = new Map<string, OpenCodeApi>()
|
||||
|
||||
/** Base URL of the OpenCode API for a server: the direct local endpoint or the remote proxy. */
|
||||
const clientErrorStatusSchema = z.object({ status: z.number().optional() })
|
||||
|
||||
export function openCodeApiBaseUrl(serverId: string = LOCAL_OPENCODE_SERVER_ID): string {
|
||||
return serverId === LOCAL_OPENCODE_SERVER_ID
|
||||
? OPENCODE_API_ENDPOINT
|
||||
@@ -24,19 +26,19 @@ export function getOpenCodeApi(serverId: string = LOCAL_OPENCODE_SERVER_ID): Ope
|
||||
return api
|
||||
}
|
||||
|
||||
function toFetchError(error: unknown): FetchError {
|
||||
if (error instanceof FetchError) {
|
||||
return error
|
||||
function toFetchError(cause: unknown): FetchError {
|
||||
if (cause instanceof FetchError) {
|
||||
return cause
|
||||
}
|
||||
|
||||
if (error instanceof ClientError) {
|
||||
const status = (error.cause as { status?: number } | undefined)?.status
|
||||
return new FetchError(error.message, status, error.reason)
|
||||
if (cause instanceof ClientError) {
|
||||
const parsedStatus = clientErrorStatusSchema.safeParse(cause.cause)
|
||||
return new FetchError(cause.message, parsedStatus.success ? parsedStatus.data.status : undefined, cause.reason)
|
||||
}
|
||||
|
||||
const status = openCodeErrorStatus(error)
|
||||
if (error instanceof Error) {
|
||||
return new FetchError(error.message, status ?? 0, error.name)
|
||||
const status = openCodeErrorStatus(cause)
|
||||
if (cause instanceof Error) {
|
||||
return new FetchError(cause.message, status ?? 0, cause.name)
|
||||
}
|
||||
|
||||
return new FetchError('Request failed', status ?? 0)
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { OpenCodeServerTestResult } from '@opencode-manager/shared/schemas'
|
||||
import { makeOpenCodeServer } from '@/test/fixtures/api'
|
||||
import { createFetchFake, type FetchRoute } from '@/test/fetchFake'
|
||||
import {
|
||||
createOpenCodeServer,
|
||||
deleteOpenCodeServer,
|
||||
@@ -8,43 +11,34 @@ import {
|
||||
updateOpenCodeServer,
|
||||
} from './opencodeServers'
|
||||
|
||||
const jsonResponse = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
const server = {
|
||||
const server = makeOpenCodeServer({
|
||||
id: 'srv_1',
|
||||
name: 'Kitchen',
|
||||
baseUrl: 'https://kitchen.example.com',
|
||||
username: 'opencode',
|
||||
enabled: true,
|
||||
hasPassword: true,
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
})
|
||||
|
||||
const testResult: OpenCodeServerTestResult = {
|
||||
ok: true,
|
||||
version: '2.0.15',
|
||||
versionSupported: true,
|
||||
error: null,
|
||||
}
|
||||
|
||||
const testResult = { ok: true, version: '2.0.15', versionSupported: true, error: null }
|
||||
function installRoutes(routes: FetchRoute[]): ReturnType<typeof createFetchFake> {
|
||||
const fetchFake = createFetchFake(routes)
|
||||
fetchFake.install()
|
||||
return fetchFake
|
||||
}
|
||||
|
||||
describe('opencodeServers', () => {
|
||||
const fetchMock = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('lists servers from the { servers } envelope', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ servers: [server] }))
|
||||
const fetchFake = installRoutes([
|
||||
{ method: 'GET', path: '/api/opencode-servers', respond: () => ({ json: { servers: [server] } }) },
|
||||
])
|
||||
|
||||
await expect(listOpenCodeServers()).resolves.toEqual([server])
|
||||
expect(fetchMock.mock.calls[0][0]).toEqual(expect.stringContaining('/api/opencode-servers'))
|
||||
expect(fetchMock.mock.calls[0][1].method).toBeUndefined()
|
||||
expect(fetchFake.lastRequest('GET', '/api/opencode-servers')?.path).toBe('/api/opencode-servers')
|
||||
})
|
||||
|
||||
it('creates a server and returns the test result', async () => {
|
||||
@@ -55,74 +49,83 @@ describe('opencodeServers', () => {
|
||||
password: 'secret',
|
||||
enabled: true,
|
||||
}
|
||||
fetchMock.mockResolvedValue(jsonResponse({ server, test: testResult }, 201))
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/opencode-servers',
|
||||
respond: () => ({ status: 201, json: { server, test: testResult } }),
|
||||
},
|
||||
])
|
||||
|
||||
await expect(createOpenCodeServer(input)).resolves.toEqual({ server, test: testResult })
|
||||
|
||||
const [url, options] = fetchMock.mock.calls[0]
|
||||
expect(url).toEqual(expect.stringContaining('/api/opencode-servers'))
|
||||
expect(options.method).toBe('POST')
|
||||
expect(options.headers['Content-Type']).toBe('application/json')
|
||||
expect(JSON.parse(options.body)).toEqual(input)
|
||||
expect(fetchFake.lastRequest('POST', '/api/opencode-servers')?.body).toEqual(input)
|
||||
})
|
||||
|
||||
it('unwraps the { server } envelope on PATCH', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ server: { ...server, name: 'Office' } }))
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'PATCH',
|
||||
path: '/api/opencode-servers/srv_1',
|
||||
respond: () => ({ json: { server: { ...server, name: 'Office' } } }),
|
||||
},
|
||||
])
|
||||
|
||||
await expect(updateOpenCodeServer('srv_1', { name: 'Office' })).resolves.toEqual({
|
||||
...server,
|
||||
name: 'Office',
|
||||
})
|
||||
|
||||
const [url, options] = fetchMock.mock.calls[0]
|
||||
expect(url).toEqual(expect.stringContaining('/api/opencode-servers/srv_1'))
|
||||
expect(options.method).toBe('PATCH')
|
||||
expect(JSON.parse(options.body)).toEqual({ name: 'Office' })
|
||||
expect(fetchFake.lastRequest('PATCH', '/api/opencode-servers/srv_1')?.body).toEqual({ name: 'Office' })
|
||||
})
|
||||
|
||||
it('clears a password by sending null', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ server: { ...server, hasPassword: false } }))
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'PATCH',
|
||||
path: '/api/opencode-servers/srv_1',
|
||||
respond: () => ({ json: { server: { ...server, hasPassword: false } } }),
|
||||
},
|
||||
])
|
||||
|
||||
await updateOpenCodeServer('srv_1', { password: null })
|
||||
|
||||
const [, options] = fetchMock.mock.calls[0]
|
||||
expect(JSON.parse(options.body)).toEqual({ password: null })
|
||||
expect(fetchFake.lastRequest('PATCH', '/api/opencode-servers/srv_1')?.body).toEqual({ password: null })
|
||||
})
|
||||
|
||||
it('deletes a server with DELETE and accepts the empty 204 response', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
const fetchFake = installRoutes([
|
||||
{ method: 'DELETE', path: '/api/opencode-servers/srv_1', respond: () => ({ status: 204 }) },
|
||||
])
|
||||
|
||||
await expect(deleteOpenCodeServer('srv_1')).resolves.toBeUndefined()
|
||||
|
||||
const [url, options] = fetchMock.mock.calls[0]
|
||||
expect(url).toEqual(expect.stringContaining('/api/opencode-servers/srv_1'))
|
||||
expect(options.method).toBe('DELETE')
|
||||
expect(fetchFake.findRequests('DELETE', '/api/opencode-servers/srv_1')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('tests unsaved values with POST /test', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(testResult))
|
||||
const input = { baseUrl: 'https://kitchen.example.com', username: 'opencode', password: 'secret' }
|
||||
const fetchFake = installRoutes([
|
||||
{ method: 'POST', path: '/api/opencode-servers/test', respond: () => ({ json: testResult }) },
|
||||
])
|
||||
|
||||
await expect(testOpenCodeServer(input)).resolves.toEqual(testResult)
|
||||
|
||||
const [url, options] = fetchMock.mock.calls[0]
|
||||
expect(url).toEqual(expect.stringContaining('/api/opencode-servers/test'))
|
||||
expect(options.method).toBe('POST')
|
||||
expect(JSON.parse(options.body)).toEqual(input)
|
||||
expect(fetchFake.lastRequest('POST', '/api/opencode-servers/test')?.body).toEqual(input)
|
||||
})
|
||||
|
||||
it('tests a saved server with POST /:id/test', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(testResult))
|
||||
const fetchFake = installRoutes([
|
||||
{ method: 'POST', path: '/api/opencode-servers/srv_1/test', respond: () => ({ json: testResult }) },
|
||||
])
|
||||
|
||||
await expect(testOpenCodeServerById('srv_1')).resolves.toEqual(testResult)
|
||||
|
||||
const [url, options] = fetchMock.mock.calls[0]
|
||||
expect(url).toEqual(expect.stringContaining('/api/opencode-servers/srv_1/test'))
|
||||
expect(options.method).toBe('POST')
|
||||
expect(fetchFake.findRequests('POST', '/api/opencode-servers/srv_1/test')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('surfaces backend error messages', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ error: 'Server unreachable' }, 502))
|
||||
installRoutes([
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/opencode-servers/srv_1/test',
|
||||
respond: () => ({ status: 502, json: { error: 'Server unreachable' } }),
|
||||
},
|
||||
])
|
||||
|
||||
await expect(testOpenCodeServerById('srv_1')).rejects.toThrow('Server unreachable')
|
||||
})
|
||||
|
||||
@@ -1,29 +1,43 @@
|
||||
import type {
|
||||
CreateOpenCodeServerRequest,
|
||||
OpenCodeServer,
|
||||
OpenCodeServerStatus,
|
||||
OpenCodeServerTestResult,
|
||||
TestOpenCodeServerRequest,
|
||||
UpdateOpenCodeServerRequest,
|
||||
import {
|
||||
OpenCodeServerSchema,
|
||||
OpenCodeServerStatusSchema,
|
||||
OpenCodeServerTestResultSchema,
|
||||
type CreateOpenCodeServerRequest,
|
||||
type OpenCodeServer,
|
||||
type OpenCodeServerStatus,
|
||||
type OpenCodeServerTestResult,
|
||||
type TestOpenCodeServerRequest,
|
||||
type UpdateOpenCodeServerRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { z } from 'zod'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
|
||||
const OPENCODE_SERVERS_URL = `${API_BASE_URL}/api/opencode-servers`
|
||||
|
||||
const serverListResponseSchema = z.object({ servers: z.array(OpenCodeServerSchema) })
|
||||
const serverStatusListResponseSchema = z.object({ statuses: z.array(OpenCodeServerStatusSchema) })
|
||||
const serverResponseSchema = z.object({ server: OpenCodeServerSchema })
|
||||
|
||||
export interface CreateOpenCodeServerResponse {
|
||||
server: OpenCodeServer
|
||||
test: OpenCodeServerTestResult
|
||||
}
|
||||
|
||||
const createServerResponseSchema: z.ZodType<CreateOpenCodeServerResponse> = z.object({
|
||||
server: OpenCodeServerSchema,
|
||||
test: OpenCodeServerTestResultSchema,
|
||||
})
|
||||
|
||||
export async function listOpenCodeServers(): Promise<OpenCodeServer[]> {
|
||||
const response = await fetchWrapper<{ servers: OpenCodeServer[] }>(OPENCODE_SERVERS_URL)
|
||||
const response = await fetchWrapper(OPENCODE_SERVERS_URL, serverListResponseSchema)
|
||||
return response.servers
|
||||
}
|
||||
|
||||
export async function listOpenCodeServerStatuses(): Promise<OpenCodeServerStatus[]> {
|
||||
const response = await fetchWrapper<{ statuses: OpenCodeServerStatus[] }>(
|
||||
const response = await fetchWrapper(
|
||||
`${OPENCODE_SERVERS_URL}/status`,
|
||||
serverStatusListResponseSchema,
|
||||
)
|
||||
return response.statuses
|
||||
}
|
||||
@@ -31,7 +45,7 @@ export async function listOpenCodeServerStatuses(): Promise<OpenCodeServerStatus
|
||||
export async function createOpenCodeServer(
|
||||
input: CreateOpenCodeServerRequest,
|
||||
): Promise<CreateOpenCodeServerResponse> {
|
||||
return fetchWrapper<CreateOpenCodeServerResponse>(OPENCODE_SERVERS_URL, {
|
||||
return fetchWrapper(OPENCODE_SERVERS_URL, createServerResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
@@ -42,8 +56,9 @@ export async function updateOpenCodeServer(
|
||||
id: string,
|
||||
input: UpdateOpenCodeServerRequest,
|
||||
): Promise<OpenCodeServer> {
|
||||
const response = await fetchWrapper<{ server: OpenCodeServer }>(
|
||||
const response = await fetchWrapper(
|
||||
`${OPENCODE_SERVERS_URL}/${encodeURIComponent(id)}`,
|
||||
serverResponseSchema,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -62,7 +77,7 @@ export async function deleteOpenCodeServer(id: string): Promise<void> {
|
||||
export async function testOpenCodeServer(
|
||||
input: TestOpenCodeServerRequest,
|
||||
): Promise<OpenCodeServerTestResult> {
|
||||
return fetchWrapper<OpenCodeServerTestResult>(`${OPENCODE_SERVERS_URL}/test`, {
|
||||
return fetchWrapper(`${OPENCODE_SERVERS_URL}/test`, OpenCodeServerTestResultSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
@@ -70,8 +85,9 @@ export async function testOpenCodeServer(
|
||||
}
|
||||
|
||||
export async function testOpenCodeServerById(id: string): Promise<OpenCodeServerTestResult> {
|
||||
return fetchWrapper<OpenCodeServerTestResult>(
|
||||
return fetchWrapper(
|
||||
`${OPENCODE_SERVERS_URL}/${encodeURIComponent(id)}/test`,
|
||||
OpenCodeServerTestResultSchema,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import {
|
||||
CreatePreviewSessionResponseSchema,
|
||||
PreviewPortsResponseSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { CreatePreviewSessionResponse, PreviewPortsResponse } from '@opencode-manager/shared/types'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
@@ -8,13 +12,13 @@ function previewPortsQueryKey(directory: string | undefined) {
|
||||
}
|
||||
|
||||
function listPreviewPorts(directory?: string): Promise<PreviewPortsResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/preview/ports`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/preview/ports`, PreviewPortsResponseSchema, {
|
||||
params: { directory },
|
||||
})
|
||||
}
|
||||
|
||||
export function createPreviewSession(port: number): Promise<CreatePreviewSessionResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/preview/sessions`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/preview/sessions`, CreatePreviewSessionResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ port }),
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
ProjectConfigResponseSchema,
|
||||
RunProjectActionResponseSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
MoveProjectItemRequest,
|
||||
ProjectAction,
|
||||
@@ -14,7 +18,7 @@ function projectConfigQueryKey(repoId: number, directory: string | undefined) {
|
||||
}
|
||||
|
||||
export function getProjectConfig(repoId: number, directory?: string): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config`, ProjectConfigResponseSchema, {
|
||||
params: { directory },
|
||||
})
|
||||
}
|
||||
@@ -24,7 +28,7 @@ function updateProjectActions(
|
||||
actions: ProjectAction[],
|
||||
directory?: string,
|
||||
): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/actions`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/actions`, ProjectConfigResponseSchema, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ actions }),
|
||||
@@ -37,7 +41,7 @@ function updateWorktreeSetup(
|
||||
commands: string[],
|
||||
directory?: string,
|
||||
): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/worktree-setup`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/worktree-setup`, ProjectConfigResponseSchema, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ commands }),
|
||||
@@ -46,7 +50,7 @@ function updateWorktreeSetup(
|
||||
}
|
||||
|
||||
function trustRepoConfig(repoId: number, request: TrustRepoConfigRequest): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/trust`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/trust`, ProjectConfigResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -54,7 +58,7 @@ function trustRepoConfig(repoId: number, request: TrustRepoConfigRequest): Promi
|
||||
}
|
||||
|
||||
function moveProjectItem(repoId: number, request: MoveProjectItemRequest): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/move`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/move`, ProjectConfigResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -68,6 +72,7 @@ function runProjectAction(
|
||||
): Promise<RunProjectActionResponse> {
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/repos/${repoId}/project-config/actions/${encodeURIComponent(actionId)}/run`,
|
||||
RunProjectActionResponseSchema,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { z } from 'zod'
|
||||
import { PromptTemplateSchema } from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
PromptTemplate,
|
||||
CreatePromptTemplateRequest,
|
||||
UpdatePromptTemplateRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
|
||||
const promptTemplatesResponseSchema = z.object({ templates: z.array(PromptTemplateSchema) })
|
||||
const promptTemplateResponseSchema = z.object({ template: PromptTemplateSchema })
|
||||
|
||||
export async function listPromptTemplates(): Promise<{ templates: PromptTemplate[] }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates`, promptTemplatesResponseSchema)
|
||||
}
|
||||
|
||||
export async function createPromptTemplate(data: CreatePromptTemplateRequest): Promise<{ template: PromptTemplate }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates`, promptTemplateResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
@@ -19,7 +24,7 @@ export async function createPromptTemplate(data: CreatePromptTemplateRequest): P
|
||||
}
|
||||
|
||||
export async function updatePromptTemplate(id: number, data: UpdatePromptTemplateRequest): Promise<{ template: PromptTemplate }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates/${id}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/prompt-templates/${id}`, promptTemplateResponseSchema, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
|
||||
+213
-230
@@ -1,4 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { ModelInfo } from '@opencode-manager/shared/opencode'
|
||||
import { createFetchFake, type FetchRoute } from '@/test/fetchFake'
|
||||
import { makeCatalogModel, makeCatalogProvider, type CatalogProviderInfo } from '@/test/fixtures/api'
|
||||
import {
|
||||
getOpenCodeConfiguredModel,
|
||||
getOpenCodeServerDefaultModel,
|
||||
@@ -8,104 +11,71 @@ import {
|
||||
providerModelRef,
|
||||
saveOpenCodeModelVariant,
|
||||
} from './providers'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
const { mockFetchWrapper, mockProviderList, mockModelList, mockModelDefault, mockConfigGet } = vi.hoisted(() => ({
|
||||
mockFetchWrapper: vi.fn(),
|
||||
mockProviderList: vi.fn(),
|
||||
mockModelList: vi.fn(),
|
||||
mockModelDefault: vi.fn(),
|
||||
mockConfigGet: vi.fn(),
|
||||
}))
|
||||
const providerRoute = '/api/opencode/api/provider'
|
||||
const modelRoute = '/api/opencode/api/model'
|
||||
const defaultModelRoute = '/api/opencode/api/model/default'
|
||||
const configRoute = '/api/opencode/api/config'
|
||||
|
||||
vi.mock('./fetchWrapper', () => ({
|
||||
fetchWrapper: mockFetchWrapper,
|
||||
}))
|
||||
function installRoutes(routes: FetchRoute[]): ReturnType<typeof createFetchFake> {
|
||||
const fetchFake = createFetchFake(routes)
|
||||
fetchFake.install()
|
||||
return fetchFake
|
||||
}
|
||||
|
||||
vi.mock('./opencodeApi', () => ({
|
||||
callOpenCode: (operation: (api: unknown) => Promise<unknown>) =>
|
||||
operation({
|
||||
provider: { list: mockProviderList },
|
||||
model: { list: mockModelList, default: mockModelDefault },
|
||||
config: { get: mockConfigGet },
|
||||
}),
|
||||
}))
|
||||
|
||||
function makeAnthropicModel(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'claude-sonnet-4',
|
||||
modelID: 'claude-sonnet-4-20250514',
|
||||
providerID: 'anthropic',
|
||||
name: 'Claude Sonnet 4',
|
||||
capabilities: { tools: true, input: ['text', 'image'], output: ['text'] },
|
||||
variants: [{ id: 'thinking', settings: { reasoning: 'high' } }],
|
||||
time: { released: Date.UTC(2025, 4, 22) },
|
||||
cost: [{ input: 3, output: 15, cache: { read: 0.3, write: 3.75 } }],
|
||||
status: 'active',
|
||||
enabled: true,
|
||||
limit: { context: 200000, output: 64000 },
|
||||
...overrides,
|
||||
}
|
||||
function catalogRoutes(providers: CatalogProviderInfo[], models: ModelInfo[]): FetchRoute[] {
|
||||
return [
|
||||
{
|
||||
method: 'GET',
|
||||
path: providerRoute,
|
||||
respond: () => ({ json: { location: { directory: '/repo' }, data: providers } }),
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: modelRoute,
|
||||
respond: () => ({ json: { location: { directory: '/repo' }, data: models } }),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
describe('getProviders', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockProviderList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
|
||||
mockModelList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
|
||||
})
|
||||
|
||||
it('maps V2 providers and models into the UI shape', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
{ id: 'anthropic', name: 'Anthropic', activation: 'enabled', package: '@opencode/ai/providers/anthropic' },
|
||||
],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
makeAnthropicModel(),
|
||||
{
|
||||
installRoutes(
|
||||
catalogRoutes(
|
||||
[makeCatalogProvider()],
|
||||
[makeCatalogModel(), makeCatalogModel({
|
||||
id: 'claude-legacy',
|
||||
modelID: 'claude-legacy',
|
||||
providerID: 'anthropic',
|
||||
name: 'Claude Legacy',
|
||||
capabilities: { tools: false, input: ['text'], output: ['text'] },
|
||||
variants: [],
|
||||
time: { released: 0 },
|
||||
cost: [],
|
||||
status: 'deprecated',
|
||||
enabled: true,
|
||||
limit: { context: 1, output: 1 },
|
||||
},
|
||||
],
|
||||
})
|
||||
})],
|
||||
),
|
||||
)
|
||||
|
||||
const result = await getProviders('/repo')
|
||||
|
||||
expect(result.providers).toHaveLength(1)
|
||||
expect(result.providers[0]).toMatchObject({ id: 'anthropic', name: 'Anthropic' })
|
||||
expect(result.providers[0].models).toHaveLength(1)
|
||||
expect(result.providers[0].models[0]).toMatchObject({
|
||||
id: 'claude-sonnet-4',
|
||||
modelID: 'claude-sonnet-4-20250514',
|
||||
name: 'Claude Sonnet 4',
|
||||
limit: { context: 200000, output: 64000 },
|
||||
released: Date.UTC(2025, 4, 22),
|
||||
free: false,
|
||||
})
|
||||
expect(result.providers[0].models).toEqual([
|
||||
{
|
||||
id: 'claude-sonnet-4',
|
||||
modelID: 'claude-sonnet-4-20250514',
|
||||
name: 'Claude Sonnet 4',
|
||||
limit: { context: 200000, output: 64000 },
|
||||
released: Date.UTC(2025, 4, 22),
|
||||
free: false,
|
||||
},
|
||||
])
|
||||
expect(result.models).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('flags zero-cost models as free', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [{ id: 'opencode', name: 'OpenCode', activation: 'enabled' }],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [makeAnthropicModel({ providerID: 'opencode', cost: [{ input: 0, output: 0 }] })],
|
||||
})
|
||||
installRoutes(
|
||||
catalogRoutes(
|
||||
[makeCatalogProvider({ id: 'opencode', name: 'OpenCode' })],
|
||||
[makeCatalogModel({ providerID: 'opencode', cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }] })],
|
||||
),
|
||||
)
|
||||
|
||||
const result = await getProviders('/repo')
|
||||
|
||||
@@ -113,21 +83,16 @@ describe('getProviders', () => {
|
||||
})
|
||||
|
||||
it('excludes disabled models and disabled providers from the picker', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' },
|
||||
{ id: 'disabled-provider', name: 'Disabled', activation: 'disabled' },
|
||||
],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
makeAnthropicModel(),
|
||||
makeAnthropicModel({ id: 'claude-disabled', modelID: 'claude-disabled', enabled: false }),
|
||||
makeAnthropicModel({ id: 'claude-off-provider', modelID: 'claude-off-provider', providerID: 'disabled-provider' }),
|
||||
],
|
||||
})
|
||||
installRoutes(
|
||||
catalogRoutes(
|
||||
[makeCatalogProvider(), makeCatalogProvider({ id: 'disabled-provider', name: 'Disabled', activation: 'disabled' })],
|
||||
[
|
||||
makeCatalogModel(),
|
||||
makeCatalogModel({ id: 'claude-disabled', modelID: 'claude-disabled', enabled: false }),
|
||||
makeCatalogModel({ id: 'claude-off-provider', modelID: 'claude-off-provider', providerID: 'disabled-provider' }),
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
const result = await getProviders('/repo')
|
||||
|
||||
@@ -136,153 +101,171 @@ describe('getProviders', () => {
|
||||
})
|
||||
|
||||
it('sorts providers and models in the TUI order', async () => {
|
||||
mockProviderList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
{ id: 'zeta', name: 'Zeta', activation: 'enabled' },
|
||||
{ id: 'opencode', name: 'OpenCode', activation: 'enabled' },
|
||||
{ id: 'alpha', name: 'Alpha', activation: 'enabled' },
|
||||
{ id: 'opencode-go', name: 'OpenCode Go', activation: 'enabled' },
|
||||
],
|
||||
})
|
||||
mockModelList.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: [
|
||||
makeAnthropicModel({ id: 'paid-new', modelID: 'paid-new', providerID: 'opencode', time: { released: 300 }, cost: [{ input: 1, output: 1 }] }),
|
||||
makeAnthropicModel({ id: 'free', modelID: 'free', providerID: 'opencode', time: { released: 100 }, cost: [{ input: 0, output: 0 }] }),
|
||||
makeAnthropicModel({ id: 'paid-old', modelID: 'paid-old', providerID: 'opencode', time: { released: 200 }, cost: [{ input: 1, output: 1 }] }),
|
||||
],
|
||||
})
|
||||
installRoutes(
|
||||
catalogRoutes(
|
||||
[
|
||||
makeCatalogProvider({ id: 'zeta', name: 'Zeta' }),
|
||||
makeCatalogProvider({ id: 'opencode', name: 'OpenCode' }),
|
||||
makeCatalogProvider({ id: 'alpha', name: 'Alpha' }),
|
||||
makeCatalogProvider({ id: 'opencode-go', name: 'OpenCode Go' }),
|
||||
],
|
||||
[
|
||||
makeCatalogModel({
|
||||
id: 'paid-new',
|
||||
modelID: 'paid-new',
|
||||
providerID: 'opencode',
|
||||
time: { released: 300 },
|
||||
cost: [{ input: 1, output: 1, cache: { read: 0, write: 0 } }],
|
||||
}),
|
||||
makeCatalogModel({
|
||||
id: 'free',
|
||||
modelID: 'free',
|
||||
providerID: 'opencode',
|
||||
time: { released: 100 },
|
||||
cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
|
||||
}),
|
||||
makeCatalogModel({
|
||||
id: 'paid-old',
|
||||
modelID: 'paid-old',
|
||||
providerID: 'opencode',
|
||||
time: { released: 200 },
|
||||
cost: [{ input: 1, output: 1, cache: { read: 0, write: 0 } }],
|
||||
}),
|
||||
],
|
||||
),
|
||||
)
|
||||
|
||||
const result = await getProviders('/repo')
|
||||
|
||||
expect(result.providers.map((provider) => provider.id)).toEqual([
|
||||
'opencode-go',
|
||||
'opencode',
|
||||
'alpha',
|
||||
'zeta',
|
||||
])
|
||||
expect(result.providers.map((provider) => provider.id)).toEqual(['opencode-go', 'opencode', 'alpha', 'zeta'])
|
||||
const opencode = result.providers.find((provider) => provider.id === 'opencode')
|
||||
expect(opencode?.models.map((model) => model.id)).toEqual(['free', 'paid-new', 'paid-old'])
|
||||
})
|
||||
|
||||
it('degrades to an empty result when the upstream call fails', async () => {
|
||||
mockProviderList.mockRejectedValue(new Error('upstream down'))
|
||||
it('requests the catalog for the directory', async () => {
|
||||
const fetchFake = installRoutes(catalogRoutes([makeCatalogProvider()], [makeCatalogModel()]))
|
||||
|
||||
await expect(getProviders('/repo')).resolves.toEqual({
|
||||
providers: [],
|
||||
models: [],
|
||||
})
|
||||
await getProviders('/repo')
|
||||
|
||||
expect(fetchFake.lastRequest('GET', providerRoute)?.searchParams.get('location[directory]')).toBe('/repo')
|
||||
expect(fetchFake.lastRequest('GET', modelRoute)?.searchParams.get('location[directory]')).toBe('/repo')
|
||||
})
|
||||
|
||||
it('degrades to an empty result when the upstream call fails', async () => {
|
||||
installRoutes([
|
||||
{ method: 'GET', path: providerRoute, respond: () => ({ status: 500, json: { error: 'upstream down' } }) },
|
||||
{ method: 'GET', path: modelRoute, respond: () => ({ json: { location: { directory: '/repo' }, data: [] } }) },
|
||||
])
|
||||
|
||||
await expect(getProviders('/repo')).resolves.toEqual({ providers: [], models: [] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('getOpenCodeConfiguredModel', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
it.each([
|
||||
{
|
||||
title: 'keeps the variant of a string config model',
|
||||
entries: [{ type: 'document', info: { model: 'anthropic/claude-sonnet-4#thinking' } }],
|
||||
expected: 'anthropic/claude-sonnet-4#thinking',
|
||||
},
|
||||
{
|
||||
title: 'formats an object config model the same way',
|
||||
entries: [{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o', variant: 'high' } } }],
|
||||
expected: 'openai/gpt-4o#high',
|
||||
},
|
||||
{
|
||||
title: 'uses the last document that sets a model',
|
||||
entries: [
|
||||
{ type: 'document', info: { model: 'anthropic/claude-sonnet-4' } },
|
||||
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o' } } },
|
||||
{ type: 'document', info: {} },
|
||||
],
|
||||
expected: 'openai/gpt-4o',
|
||||
},
|
||||
{
|
||||
title: 'returns null when no document sets a model',
|
||||
entries: [{ type: 'document', info: {} }],
|
||||
expected: null,
|
||||
},
|
||||
])('$title', async ({ entries, expected }) => {
|
||||
installRoutes([{ method: 'GET', path: configRoute, respond: () => ({ json: entries }) }])
|
||||
|
||||
it('keeps the variant of a string config model', async () => {
|
||||
mockConfigGet.mockResolvedValue([{ type: 'document', info: { model: 'anthropic/claude-sonnet-4#thinking' } }])
|
||||
|
||||
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBe('anthropic/claude-sonnet-4#thinking')
|
||||
expect(mockConfigGet).toHaveBeenCalledWith({ location: { directory: '/repo' } })
|
||||
})
|
||||
|
||||
it('formats an object config model the same way', async () => {
|
||||
mockConfigGet.mockResolvedValue([
|
||||
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o', variant: 'high' } } },
|
||||
])
|
||||
|
||||
await expect(getOpenCodeConfiguredModel()).resolves.toBe('openai/gpt-4o#high')
|
||||
expect(mockConfigGet).toHaveBeenCalledWith(undefined)
|
||||
})
|
||||
|
||||
it('uses the last document that sets a model', async () => {
|
||||
mockConfigGet.mockResolvedValue([
|
||||
{ type: 'document', info: { model: 'anthropic/claude-sonnet-4' } },
|
||||
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o' } } },
|
||||
{ type: 'document', info: {} },
|
||||
])
|
||||
|
||||
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBe('openai/gpt-4o')
|
||||
})
|
||||
|
||||
it('returns null when no document sets a model', async () => {
|
||||
mockConfigGet.mockResolvedValue([{ type: 'document', info: {} }])
|
||||
|
||||
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBeNull()
|
||||
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBe(expected)
|
||||
})
|
||||
|
||||
it('returns null when the config read fails', async () => {
|
||||
mockConfigGet.mockRejectedValue(new Error('upstream down'))
|
||||
installRoutes([{ method: 'GET', path: configRoute, respond: () => ({ status: 500, json: { error: 'upstream down' } }) }])
|
||||
|
||||
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getOpenCodeServerDefaultModel', () => {
|
||||
const location = { location: { directory: '/repo' } }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockModelDefault.mockResolvedValue({
|
||||
location: { directory: '/repo' },
|
||||
data: makeAnthropicModel({ providerID: 'openai', id: 'gpt-5', modelID: 'gpt-5' }),
|
||||
})
|
||||
})
|
||||
const defaultModel = makeCatalogModel({ providerID: 'openai', id: 'gpt-5', modelID: 'gpt-5' })
|
||||
|
||||
it('returns the server default as a model ref', async () => {
|
||||
await expect(getOpenCodeServerDefaultModel('/repo')).resolves.toEqual({
|
||||
providerID: 'openai',
|
||||
id: 'gpt-5',
|
||||
})
|
||||
installRoutes([
|
||||
{
|
||||
method: 'GET',
|
||||
path: defaultModelRoute,
|
||||
respond: () => ({ json: { location: { directory: '/repo' }, data: defaultModel } }),
|
||||
},
|
||||
])
|
||||
|
||||
await expect(getOpenCodeServerDefaultModel('/repo')).resolves.toEqual({ providerID: 'openai', id: 'gpt-5' })
|
||||
})
|
||||
|
||||
it('returns null when the server reports no default model', async () => {
|
||||
mockModelDefault.mockResolvedValue({ location: { directory: '/repo' }, data: null })
|
||||
installRoutes([
|
||||
{
|
||||
method: 'GET',
|
||||
path: defaultModelRoute,
|
||||
respond: () => ({ json: { location: { directory: '/repo' }, data: null } }),
|
||||
},
|
||||
])
|
||||
|
||||
await expect(getOpenCodeServerDefaultModel('/repo')).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('passes the location to the default model call', async () => {
|
||||
await getOpenCodeServerDefaultModel('/repo')
|
||||
|
||||
expect(mockModelDefault).toHaveBeenCalledWith(location)
|
||||
})
|
||||
|
||||
it('returns null when the default model read fails', async () => {
|
||||
mockModelDefault.mockRejectedValue(new Error('upstream down'))
|
||||
installRoutes([
|
||||
{ method: 'GET', path: defaultModelRoute, respond: () => ({ status: 500, json: { error: 'upstream down' } }) },
|
||||
])
|
||||
|
||||
await expect(getOpenCodeServerDefaultModel('/repo')).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveOpenCodeModelVariant', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('posts the model and value and returns the state', async () => {
|
||||
const state = { recent: [], favorite: [], variant: { 'openai/gpt-5': 'high' } }
|
||||
mockFetchWrapper.mockResolvedValue(state)
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/providers/model-state',
|
||||
respond: () => ({ json: state }),
|
||||
},
|
||||
])
|
||||
|
||||
await expect(saveOpenCodeModelVariant({ providerID: 'openai', modelID: 'gpt-5' }, 'high')).resolves.toEqual(state)
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(`${API_BASE_URL}/api/providers/model-state`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ variant: { model: { providerID: 'openai', modelID: 'gpt-5' }, value: 'high' } }),
|
||||
expect(fetchFake.lastRequest('POST', '/api/providers/model-state')?.body).toEqual({
|
||||
variant: { model: { providerID: 'openai', modelID: 'gpt-5' }, value: 'high' },
|
||||
})
|
||||
})
|
||||
|
||||
it('sends null when the value is omitted', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ recent: [], favorite: [], variant: {} })
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/providers/model-state',
|
||||
respond: () => ({ json: { recent: [], favorite: [], variant: {} } }),
|
||||
},
|
||||
])
|
||||
|
||||
await saveOpenCodeModelVariant({ providerID: 'openai', modelID: 'gpt-5' })
|
||||
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(`${API_BASE_URL}/api/providers/model-state`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ variant: { model: { providerID: 'openai', modelID: 'gpt-5' }, value: null } }),
|
||||
expect(fetchFake.lastRequest('POST', '/api/providers/model-state')?.body).toEqual({
|
||||
variant: { model: { providerID: 'openai', modelID: 'gpt-5' }, value: null },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -300,57 +283,57 @@ describe('modelSelectionRef', () => {
|
||||
})
|
||||
|
||||
describe('providerCredentialsApi', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('reports credential status from the Manager response', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ hasCredentials: true })
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/providers/anthropic/credentials/status',
|
||||
respond: () => ({ json: { hasCredentials: true } }),
|
||||
},
|
||||
])
|
||||
|
||||
await expect(providerCredentialsApi.getStatus('anthropic')).resolves.toBe(true)
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(
|
||||
`${API_BASE_URL}/api/providers/anthropic/credentials/status`
|
||||
)
|
||||
expect(fetchFake.findRequests('GET', '/api/providers/anthropic/credentials/status')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('posts the api key to the provider credential route', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ success: true })
|
||||
|
||||
await providerCredentialsApi.set('anthropic', 'sk-ant-test')
|
||||
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(
|
||||
`${API_BASE_URL}/api/providers/anthropic/credentials`,
|
||||
it.each([
|
||||
{
|
||||
title: 'posts the api key to the provider credential route',
|
||||
providerId: 'anthropic',
|
||||
answer: undefined,
|
||||
expectedBody: { apiKey: 'sk-ant-test' },
|
||||
},
|
||||
{
|
||||
title: 'posts the key method form answer alongside the api key',
|
||||
providerId: 'azure',
|
||||
answer: { resourceName: 'my-models' },
|
||||
expectedBody: { apiKey: 'sk-ant-test', answer: { resourceName: 'my-models' } },
|
||||
},
|
||||
])('$title', async ({ providerId, answer, expectedBody }) => {
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ apiKey: 'sk-ant-test' }),
|
||||
}
|
||||
)
|
||||
})
|
||||
path: `/api/providers/${providerId}/credentials`,
|
||||
respond: () => ({ json: { success: true } }),
|
||||
},
|
||||
])
|
||||
|
||||
it('posts the key method form answer alongside the api key', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ success: true })
|
||||
await providerCredentialsApi.set(providerId, 'sk-ant-test', answer)
|
||||
|
||||
await providerCredentialsApi.set('azure', 'az-test', { resourceName: 'my-models' })
|
||||
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(
|
||||
`${API_BASE_URL}/api/providers/azure/credentials`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ apiKey: 'az-test', answer: { resourceName: 'my-models' } }),
|
||||
}
|
||||
)
|
||||
expect(fetchFake.lastRequest('POST', `/api/providers/${providerId}/credentials`)?.body).toMatchObject(expectedBody)
|
||||
})
|
||||
|
||||
it('deletes credentials through the provider credential route', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ success: true })
|
||||
const fetchFake = installRoutes([
|
||||
{
|
||||
method: 'DELETE',
|
||||
path: '/api/providers/anthropic/credentials',
|
||||
respond: () => ({ json: { success: true } }),
|
||||
},
|
||||
])
|
||||
|
||||
await providerCredentialsApi.delete('anthropic')
|
||||
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(
|
||||
`${API_BASE_URL}/api/providers/anthropic/credentials`,
|
||||
{ method: 'DELETE' }
|
||||
)
|
||||
expect(fetchFake.findRequests('DELETE', '/api/providers/anthropic/credentials')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,8 @@
|
||||
import { API_BASE_URL } from "@/config";
|
||||
import { z } from "zod";
|
||||
import { JsonValueSchema, type JsonValue } from "@opencode-manager/shared/utils";
|
||||
import { CredentialStatusResponseSchema } from "@opencode-manager/shared/schemas";
|
||||
import { decodeModelPreference, toModelPreference } from "@opencode-manager/shared/opencode";
|
||||
import { fetchWrapper } from "./fetchWrapper";
|
||||
import { callOpenCode } from "./opencodeApi";
|
||||
import {
|
||||
@@ -16,7 +20,6 @@ import {
|
||||
type ModelPreferenceModel,
|
||||
type ModelRef,
|
||||
} from "@opencode-manager/shared/opencode";
|
||||
import type { CredentialStatusResponse } from "@opencode-manager/shared/schemas";
|
||||
|
||||
export type Model = Pick<ModelInfo, 'id' | 'modelID' | 'name'> & {
|
||||
limit?: {
|
||||
@@ -126,49 +129,56 @@ export async function getOpenCodeServerDefaultModel(
|
||||
}
|
||||
}
|
||||
|
||||
const successResponseSchema = z.object({ success: z.literal(true) })
|
||||
|
||||
function modelStateFromDocument(document: JsonValue): OpenCodeModelState {
|
||||
return toModelPreference(decodeModelPreference(document))
|
||||
}
|
||||
|
||||
export async function saveOpenCodeModelVariant(
|
||||
model: ModelSelection,
|
||||
value?: string | null,
|
||||
): Promise<OpenCodeModelState> {
|
||||
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`, {
|
||||
const document = await fetchWrapper(`${API_BASE_URL}/api/providers/model-state`, JsonValueSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ variant: { model, value: value ?? null } }),
|
||||
});
|
||||
return modelStateFromDocument(document);
|
||||
}
|
||||
|
||||
export async function getOpenCodeModelState(): Promise<OpenCodeModelState> {
|
||||
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`);
|
||||
const document = await fetchWrapper(`${API_BASE_URL}/api/providers/model-state`, JsonValueSchema);
|
||||
return modelStateFromDocument(document);
|
||||
}
|
||||
|
||||
export async function addOpenCodeRecentModel(model: ModelSelection): Promise<OpenCodeModelState> {
|
||||
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`, {
|
||||
const document = await fetchWrapper(`${API_BASE_URL}/api/providers/model-state`, JsonValueSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ recent: model }),
|
||||
});
|
||||
return modelStateFromDocument(document);
|
||||
}
|
||||
|
||||
export async function removeOpenCodeRecentModel(model: ModelSelection): Promise<OpenCodeModelState> {
|
||||
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`, {
|
||||
const document = await fetchWrapper(`${API_BASE_URL}/api/providers/model-state`, JsonValueSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ removeRecent: model }),
|
||||
});
|
||||
return modelStateFromDocument(document);
|
||||
}
|
||||
|
||||
export async function toggleOpenCodeFavoriteModel(model: ModelSelection): Promise<OpenCodeModelState> {
|
||||
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`, {
|
||||
const document = await fetchWrapper(`${API_BASE_URL}/api/providers/model-state`, JsonValueSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ favorite: model }),
|
||||
});
|
||||
return modelStateFromDocument(document);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the model's display name, falling back to its ID when the catalog
|
||||
* provides no name.
|
||||
*/
|
||||
export function formatModelName(model: Model): string {
|
||||
return model.name || model.modelID;
|
||||
}
|
||||
@@ -187,14 +197,15 @@ export function formatProviderName(provider: Provider): string {
|
||||
|
||||
export const providerCredentialsApi = {
|
||||
getStatus: async (providerId: string): Promise<boolean> => {
|
||||
const { hasCredentials } = await fetchWrapper<CredentialStatusResponse>(
|
||||
`${API_BASE_URL}/api/providers/${providerId}/credentials/status`
|
||||
const { hasCredentials } = await fetchWrapper(
|
||||
`${API_BASE_URL}/api/providers/${providerId}/credentials/status`,
|
||||
CredentialStatusResponseSchema
|
||||
);
|
||||
return hasCredentials;
|
||||
},
|
||||
|
||||
set: async (providerId: string, apiKey: string, answer?: FormAnswer): Promise<void> => {
|
||||
await fetchWrapper(`${API_BASE_URL}/api/providers/${providerId}/credentials`, {
|
||||
await fetchWrapper(`${API_BASE_URL}/api/providers/${providerId}/credentials`, successResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ apiKey, answer }),
|
||||
@@ -202,7 +213,7 @@ export const providerCredentialsApi = {
|
||||
},
|
||||
|
||||
delete: async (providerId: string): Promise<void> => {
|
||||
await fetchWrapper(`${API_BASE_URL}/api/providers/${providerId}/credentials`, {
|
||||
await fetchWrapper(`${API_BASE_URL}/api/providers/${providerId}/credentials`, successResponseSchema, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
},
|
||||
|
||||
+75
-21
@@ -2,12 +2,66 @@ import type { Repo } from './types'
|
||||
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { saveFile } from '@/lib/download'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
AssistantModeStatusSchema,
|
||||
DeleteRepoResultSchema,
|
||||
DiscoverReposResponseSchema,
|
||||
RepoGitIdentitySchema,
|
||||
RepoSchema,
|
||||
WorktreeSetupResultSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { CreateRepoWorkspaceRequest, DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity, WorktreeSetupResult } from '@opencode-manager/shared/types'
|
||||
import type { RepoSibling } from '@opencode-manager/shared/utils'
|
||||
import { formatScheduleWorktreeLabel } from '@/lib/schedules/schedule-worktree'
|
||||
|
||||
export type { RepoSibling } from '@opencode-manager/shared/utils'
|
||||
|
||||
const repoSchemaBase = RepoSchema.extend({
|
||||
currentBranch: z.string().optional(),
|
||||
worktreeSetup: WorktreeSetupResultSchema.optional(),
|
||||
})
|
||||
|
||||
const repoSchema: z.ZodType<Repo> = repoSchemaBase
|
||||
|
||||
const repoListSchema = z.array(repoSchema)
|
||||
|
||||
const repoWorktreeScheduleSchema = z.object({
|
||||
repoId: z.number(),
|
||||
jobId: z.number(),
|
||||
runId: z.number().nullable(),
|
||||
inUse: z.boolean(),
|
||||
name: z.string(),
|
||||
})
|
||||
|
||||
const repoSiblingSchema: z.ZodType<RepoSibling> = repoSchemaBase.extend({
|
||||
currentBranch: z.string().optional(),
|
||||
worktreeSource: z.enum(['opencode', 'schedule', 'git']).optional(),
|
||||
schedule: repoWorktreeScheduleSchema.optional(),
|
||||
})
|
||||
|
||||
const repoSiblingListSchema = z.array(repoSiblingSchema)
|
||||
|
||||
const repoWorktreeSetupResponseSchema: z.ZodType<RepoWorktree & { worktreeSetup?: WorktreeSetupResult }> = z.object({
|
||||
directory: z.string(),
|
||||
worktreeSetup: WorktreeSetupResultSchema.optional(),
|
||||
})
|
||||
|
||||
const gitBranchSchema = z.object({
|
||||
name: z.string(),
|
||||
type: z.enum(['local', 'remote']),
|
||||
current: z.boolean(),
|
||||
upstream: z.string().optional(),
|
||||
ahead: z.number().optional(),
|
||||
behind: z.number().optional(),
|
||||
isWorktree: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const branchListResponseSchema: z.ZodType<{ branches: GitBranch[]; status: { ahead: number; behind: number } }> = z.object({
|
||||
branches: z.array(gitBranchSchema),
|
||||
status: z.object({ ahead: z.number(), behind: z.number() }),
|
||||
})
|
||||
|
||||
export interface CreateRepoOptions {
|
||||
repoUrl?: string
|
||||
localPath?: string
|
||||
@@ -19,7 +73,7 @@ export interface CreateRepoOptions {
|
||||
}
|
||||
|
||||
export async function createRepo(options: CreateRepoOptions = {}): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos`, repoSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(options),
|
||||
@@ -27,11 +81,11 @@ export async function createRepo(options: CreateRepoOptions = {}): Promise<Repo>
|
||||
}
|
||||
|
||||
export async function listRepos(): Promise<Repo[]> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos`, repoListSchema)
|
||||
}
|
||||
|
||||
export async function discoverRepos(rootPath: string, maxDepth?: number): Promise<DiscoverReposResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/discover`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/discover`, DiscoverReposResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ rootPath, maxDepth }),
|
||||
@@ -39,7 +93,7 @@ export async function discoverRepos(rootPath: string, maxDepth?: number): Promis
|
||||
}
|
||||
|
||||
export async function getRepo(id: number): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, repoSchema)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +114,7 @@ export interface RepoWorktree {
|
||||
}
|
||||
|
||||
export async function getRepoSiblings(id: number): Promise<RepoSibling[]> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/siblings`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/siblings`, repoSiblingListSchema)
|
||||
}
|
||||
|
||||
export async function deleteRepoWorkspace(repoId: number, directory: string): Promise<void> {
|
||||
@@ -72,7 +126,7 @@ export async function deleteRepoWorkspace(repoId: number, directory: string): Pr
|
||||
}
|
||||
|
||||
export async function createRepoWorkspace(repoId: number, request: CreateRepoWorkspaceRequest = {}): Promise<RepoWorktree & { worktreeSetup?: WorktreeSetupResult }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, repoWorktreeSetupResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -86,16 +140,16 @@ export interface DeleteRepoOptions {
|
||||
}
|
||||
|
||||
export async function deleteRepo(id: number, options?: DeleteRepoOptions): Promise<DeleteRepoResult> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, {
|
||||
method: 'DELETE',
|
||||
...(options
|
||||
? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(options) }
|
||||
: {}),
|
||||
})
|
||||
const request: RequestInit = { method: 'DELETE' }
|
||||
if (options) {
|
||||
request.headers = { 'Content-Type': 'application/json' }
|
||||
request.body = JSON.stringify(options)
|
||||
}
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, DeleteRepoResultSchema, request)
|
||||
}
|
||||
|
||||
export async function updateRepoGitCredential(id: number, credentialId?: string): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-credential`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-credential`, repoSchema, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ credentialId }),
|
||||
@@ -103,11 +157,11 @@ export async function updateRepoGitCredential(id: number, credentialId?: string)
|
||||
}
|
||||
|
||||
export async function getRepoGitIdentity(id: number): Promise<RepoGitIdentity> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-identity`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-identity`, RepoGitIdentitySchema)
|
||||
}
|
||||
|
||||
export async function updateRepoGitIdentity(id: number, identityId: string | null): Promise<RepoGitIdentity> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-identity`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-identity`, RepoGitIdentitySchema, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ identityId }),
|
||||
@@ -115,7 +169,7 @@ export async function updateRepoGitIdentity(id: number, identityId: string | nul
|
||||
}
|
||||
|
||||
export async function renameRepo(id: number, name: string | null): Promise<Repo> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`, repoSchema, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: name ?? '' }),
|
||||
@@ -133,7 +187,7 @@ export class GitAuthError extends Error {
|
||||
|
||||
export async function switchBranch(id: number, branch: string): Promise<Repo> {
|
||||
try {
|
||||
return await fetchWrapper(`${API_BASE_URL}/api/repos/${id}/branch/switch`, {
|
||||
return await fetchWrapper(`${API_BASE_URL}/api/repos/${id}/branch/switch`, repoSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ branch }),
|
||||
@@ -157,12 +211,12 @@ export interface GitBranch {
|
||||
}
|
||||
|
||||
export async function listBranches(id: number): Promise<{ branches: GitBranch[], status: { ahead: number, behind: number } }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git/branches`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git/branches`, branchListResponseSchema)
|
||||
}
|
||||
|
||||
export async function createBranch(id: number, branch: string): Promise<Repo> {
|
||||
try {
|
||||
return await fetchWrapper(`${API_BASE_URL}/api/repos/${id}/branch/create`, {
|
||||
return await fetchWrapper(`${API_BASE_URL}/api/repos/${id}/branch/create`, repoSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ branch }),
|
||||
@@ -212,7 +266,7 @@ export async function touchRepoActivity(id: number): Promise<void> {
|
||||
}
|
||||
|
||||
export async function getAssistantModeStatus(id: number): Promise<AssistantModeStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/assistant-mode`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/assistant-mode`, AssistantModeStatusSchema, {
|
||||
method: 'GET',
|
||||
})
|
||||
}
|
||||
@@ -221,7 +275,7 @@ export async function initializeAssistantMode(
|
||||
id: number,
|
||||
options?: AssistantModeInitRequest
|
||||
): Promise<AssistantModeStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/assistant-mode`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/assistant-mode`, AssistantModeStatusSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(options ?? {}),
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
ScheduleJobSchema,
|
||||
ScheduleRunSchema,
|
||||
ScheduleRunStatusSchema,
|
||||
ScheduleWorktreeSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type {
|
||||
@@ -36,6 +43,55 @@ export interface ScheduleRunWithContext extends ScheduleRun {
|
||||
serverName: string | null
|
||||
}
|
||||
|
||||
const scheduleRunSummarySchema = z.object({
|
||||
id: z.number(),
|
||||
status: ScheduleRunStatusSchema,
|
||||
startedAt: z.number(),
|
||||
finishedAt: z.number().nullable(),
|
||||
viewedAt: z.number().nullable(),
|
||||
preview: z.string().nullable(),
|
||||
})
|
||||
|
||||
const scheduleJobWithRepoSchema: z.ZodType<ScheduleJobWithRepo> = ScheduleJobSchema.extend({
|
||||
repoName: z.string(),
|
||||
repoPath: z.string(),
|
||||
repoUrl: z.string(),
|
||||
serverName: z.string().nullable(),
|
||||
lastRun: scheduleRunSummarySchema.nullable(),
|
||||
retainedWorktreeCount: z.number(),
|
||||
})
|
||||
|
||||
const scheduleJobWithRepoListSchema = z.array(scheduleJobWithRepoSchema)
|
||||
|
||||
const scheduleRunWithContextBaseSchema = ScheduleRunSchema.extend({
|
||||
jobName: z.string(),
|
||||
repoName: z.string(),
|
||||
repoPath: z.string(),
|
||||
serverName: z.string().nullable(),
|
||||
})
|
||||
|
||||
const scheduleRunWithContextSchema: z.ZodType<ScheduleRunWithContext> = scheduleRunWithContextBaseSchema
|
||||
|
||||
const unreadScheduleRunSchema = scheduleRunWithContextBaseSchema.extend({ preview: z.string().nullable() })
|
||||
|
||||
const unreadScheduleRunsResponseSchema: z.ZodType<UnreadScheduleRunsResponse> = z.object({
|
||||
runs: z.array(unreadScheduleRunSchema),
|
||||
total: z.number(),
|
||||
failed: z.number(),
|
||||
})
|
||||
|
||||
const scheduleJobsResponseSchema = z.object({ jobs: scheduleJobWithRepoListSchema })
|
||||
const scheduleJobResponseSchema = z.object({ job: ScheduleJobSchema })
|
||||
const scheduleRunResponseSchema = z.object({ run: ScheduleRunSchema })
|
||||
const scheduleRunWithContextListSchema = z.array(scheduleRunWithContextSchema)
|
||||
const scheduleRunsWithContextResponseSchema = z.object({ runs: scheduleRunWithContextListSchema })
|
||||
const scheduleRunsResponseSchema = z.object({ runs: z.array(ScheduleRunSchema) })
|
||||
const scheduleWorktreesResponseSchema = z.object({ worktrees: z.array(ScheduleWorktreeSchema) })
|
||||
const updatedFlagResponseSchema = z.object({ updated: z.boolean() })
|
||||
const updatedCountResponseSchema = z.object({ updated: z.number() })
|
||||
const clearedCountResponseSchema = z.object({ cleared: z.number() })
|
||||
const removedCountResponseSchema = z.object({ removed: z.number() })
|
||||
|
||||
export interface ScheduleServerTarget {
|
||||
serverId: string
|
||||
directory: string
|
||||
@@ -68,7 +124,7 @@ export interface ScheduleCount {
|
||||
}
|
||||
|
||||
export async function listAllSchedules(): Promise<{ jobs: ScheduleJobWithRepo[] }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all`, scheduleJobsResponseSchema)
|
||||
}
|
||||
|
||||
export async function listAllScheduleRuns(params: ListAllRunsParams = {}): Promise<{ runs: ScheduleRunWithContext[] }> {
|
||||
@@ -82,27 +138,27 @@ export async function listAllScheduleRuns(params: ListAllRunsParams = {}): Promi
|
||||
if (params.runId !== undefined) searchParams.set('runId', String(params.runId))
|
||||
if (params.search) searchParams.set('search', params.search)
|
||||
const qs = searchParams.toString()
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs${qs ? `?${qs}` : ''}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs${qs ? `?${qs}` : ''}`, scheduleRunsWithContextResponseSchema)
|
||||
}
|
||||
|
||||
export async function listUnreadScheduleRuns(limit: number = 20): Promise<UnreadScheduleRunsResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/unread?limit=${limit}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/unread?limit=${limit}`, unreadScheduleRunsResponseSchema)
|
||||
}
|
||||
|
||||
export async function markScheduleRunViewed(runId: number): Promise<{ updated: boolean }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/${runId}/viewed`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/${runId}/viewed`, updatedFlagResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function markAllScheduleRunsViewed(): Promise<{ updated: number }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/viewed`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/schedules/all/runs/viewed`, updatedCountResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function getScheduleCounts(): Promise<Map<number, ScheduleCount>> {
|
||||
const response = await fetchWrapper<{ jobs: ScheduleJobWithRepo[] }>(`${API_BASE_URL}/api/schedules/all`)
|
||||
const response = await fetchWrapper(`${API_BASE_URL}/api/schedules/all`, scheduleJobsResponseSchema)
|
||||
const jobs = response.jobs
|
||||
const counts = new Map<number, ScheduleCount>()
|
||||
|
||||
@@ -125,11 +181,11 @@ export async function getScheduleCounts(): Promise<Map<number, ScheduleCount>> {
|
||||
}
|
||||
|
||||
export async function getRepoSchedule(repoId: number, jobId: number): Promise<{ job: ScheduleJob }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`, scheduleJobResponseSchema)
|
||||
}
|
||||
|
||||
export async function createRepoSchedule(repoId: number, data: CreateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules`, scheduleJobResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
@@ -137,7 +193,7 @@ export async function createRepoSchedule(repoId: number, data: CreateScheduleJob
|
||||
}
|
||||
|
||||
export async function updateRepoSchedule(repoId: number, jobId: number, data: UpdateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}`, scheduleJobResponseSchema, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
@@ -151,38 +207,38 @@ export async function deleteRepoSchedule(repoId: number, jobId: number): Promise
|
||||
}
|
||||
|
||||
export async function runRepoSchedule(repoId: number, jobId: number): Promise<{ run: ScheduleRun }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/run`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/run`, scheduleRunResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function listRepoScheduleRuns(repoId: number, jobId: number, limit: number = 20): Promise<{ runs: ScheduleRun[] }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs?limit=${limit}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs?limit=${limit}`, scheduleRunsResponseSchema)
|
||||
}
|
||||
|
||||
export async function getRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}`, scheduleRunResponseSchema)
|
||||
}
|
||||
|
||||
export async function cancelRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}/cancel`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}/cancel`, scheduleRunResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function clearRepoScheduleRuns(repoId: number, jobId: number, worktrees?: ScheduleRunWorktreesMode): Promise<{ cleared: number }> {
|
||||
const qs = worktrees ? `?worktrees=${worktrees}` : ''
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs${qs}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs${qs}`, clearedCountResponseSchema, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
export async function listScheduleWorktrees(repoId: number, jobId: number): Promise<{ worktrees: ScheduleWorktree[] }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`, scheduleWorktreesResponseSchema)
|
||||
}
|
||||
|
||||
export async function removeScheduleWorktrees(repoId: number, jobId: number, request: RemoveScheduleWorktreesRequest = {}): Promise<{ removed: number }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`, removedCountResponseSchema, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -201,11 +257,11 @@ function serverSchedulesPath(serverId: string): string {
|
||||
}
|
||||
|
||||
export async function getServerSchedule(serverId: string, jobId: number): Promise<{ job: ScheduleJob }> {
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}`)
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}`, scheduleJobResponseSchema)
|
||||
}
|
||||
|
||||
export async function createServerSchedule(serverId: string, data: CreateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
|
||||
return fetchWrapper(serverSchedulesPath(serverId), {
|
||||
return fetchWrapper(serverSchedulesPath(serverId), scheduleJobResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
@@ -213,7 +269,7 @@ export async function createServerSchedule(serverId: string, data: CreateSchedul
|
||||
}
|
||||
|
||||
export async function updateServerSchedule(serverId: string, jobId: number, data: UpdateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}`, {
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}`, scheduleJobResponseSchema, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
@@ -225,23 +281,23 @@ export async function deleteServerSchedule(serverId: string, jobId: number): Pro
|
||||
}
|
||||
|
||||
export async function runServerSchedule(serverId: string, jobId: number): Promise<{ run: ScheduleRun }> {
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/run`, { method: 'POST' })
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/run`, scheduleRunResponseSchema, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function listServerScheduleRuns(serverId: string, jobId: number, limit: number = 20): Promise<{ runs: ScheduleRun[] }> {
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs?limit=${limit}`)
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs?limit=${limit}`, scheduleRunsResponseSchema)
|
||||
}
|
||||
|
||||
export async function getServerScheduleRun(serverId: string, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs/${runId}`)
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs/${runId}`, scheduleRunResponseSchema)
|
||||
}
|
||||
|
||||
export async function cancelServerScheduleRun(serverId: string, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs/${runId}/cancel`, { method: 'POST' })
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs/${runId}/cancel`, scheduleRunResponseSchema, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function clearServerScheduleRuns(serverId: string, jobId: number): Promise<{ cleared: number }> {
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs`, { method: 'DELETE' })
|
||||
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs`, clearedCountResponseSchema, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export async function deleteServerScheduleRun(serverId: string, jobId: number, runId: number): Promise<void> {
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { SecretKind, SecretListResponse, SetSecretRequest } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
SecretListResponseSchema,
|
||||
type SecretKind,
|
||||
type SecretListResponse,
|
||||
type SetSecretRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
|
||||
export type SecretScope = { scope: 'global' } | { scope: 'repo'; repoId: number }
|
||||
|
||||
const KIND_SEGMENT: Record<SecretKind, string> = {
|
||||
const KIND_SEGMENT = {
|
||||
secret: 'secrets',
|
||||
variable: 'variables',
|
||||
}
|
||||
} satisfies Record<SecretKind, string>
|
||||
|
||||
function secretsPath(scope: SecretScope, kind: SecretKind): string {
|
||||
const segment = KIND_SEGMENT[kind]
|
||||
@@ -17,7 +22,7 @@ function secretsPath(scope: SecretScope, kind: SecretKind): string {
|
||||
}
|
||||
|
||||
export async function listSecrets(scope: SecretScope, kind: SecretKind): Promise<SecretListResponse> {
|
||||
return fetchWrapper(secretsPath(scope, kind))
|
||||
return fetchWrapper(secretsPath(scope, kind), SecretListResponseSchema)
|
||||
}
|
||||
|
||||
export async function setSecret(
|
||||
@@ -41,6 +46,6 @@ export async function deleteSecret(
|
||||
): Promise<void> {
|
||||
return fetchWrapperVoid(`${secretsPath(scope, kind)}/${encodeURIComponent(name)}`, {
|
||||
method: 'DELETE',
|
||||
...(environment ? { params: { environment } } : {}),
|
||||
params: environment ? { environment } : undefined,
|
||||
})
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
SessionPermissionModeStateSchema,
|
||||
type SessionPermissionModeState,
|
||||
type SetSessionPermissionModeRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
@@ -10,8 +11,9 @@ export async function getSessionPermissionMode(
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<SessionPermissionModeState> {
|
||||
return fetchWrapper<SessionPermissionModeState>(
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/session-permission-modes/${encodeURIComponent(sessionId)}`,
|
||||
SessionPermissionModeStateSchema,
|
||||
{ params: { serverId } },
|
||||
)
|
||||
}
|
||||
@@ -21,8 +23,9 @@ export async function setSessionPermissionMode(
|
||||
input: SetSessionPermissionModeRequest,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<SessionPermissionModeState> {
|
||||
return fetchWrapper<SessionPermissionModeState>(
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/session-permission-modes/${encodeURIComponent(sessionId)}`,
|
||||
SessionPermissionModeStateSchema,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { SessionPin, ToggleSessionPinRequest } from '@opencode-manager/shared/schemas'
|
||||
import { z } from 'zod'
|
||||
import { SessionPinSchema, type SessionPin, type ToggleSessionPinRequest } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const sessionPinsResponseSchema = z.object({ pins: z.array(SessionPinSchema) })
|
||||
|
||||
export async function listSessionPins(): Promise<SessionPin[]> {
|
||||
const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`)
|
||||
const res = await fetchWrapper(`${API_BASE_URL}/api/session-pins`, sessionPinsResponseSchema)
|
||||
return res.pins
|
||||
}
|
||||
|
||||
export async function toggleSessionPin(input: ToggleSessionPinRequest): Promise<SessionPin[]> {
|
||||
const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`, {
|
||||
const res = await fetchWrapper(`${API_BASE_URL}/api/session-pins`, sessionPinsResponseSchema, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { SessionSandboxState, SetSessionSandboxRequest } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
SessionSandboxStateSchema,
|
||||
type SessionSandboxState,
|
||||
type SetSessionSandboxRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export async function getSessionSandbox(sessionId: string): Promise<SessionSandboxState> {
|
||||
return fetchWrapper<SessionSandboxState>(
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/session-sandbox/${encodeURIComponent(sessionId)}`,
|
||||
SessionSandboxStateSchema,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,8 +17,9 @@ export async function setSessionSandbox(
|
||||
sessionId: string,
|
||||
input: SetSessionSandboxRequest,
|
||||
): Promise<SessionSandboxState> {
|
||||
return fetchWrapper<SessionSandboxState>(
|
||||
return fetchWrapper(
|
||||
`${API_BASE_URL}/api/session-sandbox/${encodeURIComponent(sessionId)}`,
|
||||
SessionSandboxStateSchema,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -1,72 +1,78 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
import { parseJsonText } from '@opencode-manager/shared/utils'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { createFetchFake } from '@/test/fetchFake'
|
||||
import { settingsApi } from './settings'
|
||||
|
||||
const installedSkill = {
|
||||
skill: {
|
||||
name: 'teach',
|
||||
description: 'Teach',
|
||||
body: '# Teach',
|
||||
scope: 'global',
|
||||
location: 'skills/teach',
|
||||
},
|
||||
overwritten: false,
|
||||
}
|
||||
|
||||
const fileManifestSchema = z.array(
|
||||
z.object({ fieldName: z.string(), relativePath: z.string() }),
|
||||
)
|
||||
|
||||
const githubInstallRequest = {
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/teach',
|
||||
scope: 'global',
|
||||
} as const
|
||||
|
||||
describe('settingsApi', () => {
|
||||
const fetchMock = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('installSkillFromGithub', () => {
|
||||
it('posts JSON to skills install endpoint', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ skill: { name: 'teach' }, overwritten: false, sourceType: 'github', filesInstalled: ['SKILL.md'] }), { status: 200 }),
|
||||
)
|
||||
const fetchFake = createFetchFake([
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/settings/skills/install',
|
||||
respond: () => ({ json: { ...installedSkill, sourceType: 'github', filesInstalled: ['SKILL.md'] } }),
|
||||
},
|
||||
])
|
||||
fetchFake.install()
|
||||
|
||||
const result = await settingsApi.installSkillFromGithub({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/teach',
|
||||
scope: 'global',
|
||||
})
|
||||
const result = await settingsApi.installSkillFromGithub(githubInstallRequest)
|
||||
|
||||
expect(result.skill.name).toBe('teach')
|
||||
|
||||
const callUrl = fetchMock.mock.calls[0][0]
|
||||
expect(callUrl).toEqual(expect.stringContaining('/api/settings/skills/install'))
|
||||
|
||||
const callOptions = fetchMock.mock.calls[0][1]
|
||||
expect(callOptions.method).toBe('POST')
|
||||
expect(callOptions.headers['Content-Type']).toBe('application/json')
|
||||
|
||||
const body = JSON.parse(callOptions.body)
|
||||
expect(body.sourceType).toBe('github')
|
||||
const installRequest = fetchFake.lastRequest('POST', '/api/settings/skills/install')
|
||||
expect(installRequest?.headers['content-type']).toBe('application/json')
|
||||
expect(installRequest?.body).toMatchObject({ sourceType: 'github', scope: 'global' })
|
||||
})
|
||||
|
||||
it('surfaces 409 conflict as FetchError', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'Skill "teach" already exists in global scope' }), { status: 409 }),
|
||||
)
|
||||
const fetchFake = createFetchFake([
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/settings/skills/install',
|
||||
respond: () => ({ status: 409, json: { error: 'Skill "teach" already exists in global scope' } }),
|
||||
},
|
||||
])
|
||||
fetchFake.install()
|
||||
|
||||
await expect(
|
||||
settingsApi.installSkillFromGithub({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/teach',
|
||||
scope: 'global',
|
||||
}),
|
||||
).rejects.toThrow(FetchError)
|
||||
const request = settingsApi.installSkillFromGithub(githubInstallRequest)
|
||||
|
||||
await expect(
|
||||
settingsApi.installSkillFromGithub({
|
||||
sourceType: 'github',
|
||||
url: 'https://github.com/user/repo/tree/main/teach',
|
||||
scope: 'global',
|
||||
}),
|
||||
).rejects.toMatchObject({ statusCode: 409 })
|
||||
await expect(request).rejects.toBeInstanceOf(FetchError)
|
||||
await expect(request).rejects.toMatchObject({ statusCode: 409 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('installSkillFromUpload', () => {
|
||||
it('posts FormData manifest and files', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ skill: { name: 'teach' }, overwritten: false, sourceType: 'upload', filesInstalled: ['teach/SKILL.md'] }), { status: 200 }),
|
||||
)
|
||||
const fetchFake = createFetchFake([
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/settings/skills/install',
|
||||
respond: () => ({ json: { ...installedSkill, sourceType: 'upload', filesInstalled: ['teach/SKILL.md'] } }),
|
||||
},
|
||||
])
|
||||
fetchFake.install()
|
||||
|
||||
const file = new File(['# Teach Skill'], 'SKILL.md', { type: 'text/markdown' })
|
||||
Object.defineProperty(file, 'webkitRelativePath', { value: 'teach/SKILL.md' })
|
||||
@@ -74,22 +80,13 @@ describe('settingsApi', () => {
|
||||
const result = await settingsApi.installSkillFromUpload({ files: [file], scope: 'global' })
|
||||
|
||||
expect(result.sourceType).toBe('upload')
|
||||
|
||||
const callUrl = fetchMock.mock.calls[0][0]
|
||||
expect(callUrl).toEqual(expect.stringContaining('/api/settings/skills/install'))
|
||||
|
||||
const callOptions = fetchMock.mock.calls[0][1]
|
||||
expect(callOptions.method).toBe('POST')
|
||||
expect(callOptions.headers?.hasOwnProperty).toBeFalsy()
|
||||
|
||||
const formData = callOptions.body as FormData
|
||||
const formData = fetchFake.findFormData()
|
||||
if (!formData) throw new Error('no FormData request body was recorded')
|
||||
expect(formData.get('sourceType')).toBe('upload')
|
||||
expect(formData.get('file0')).toBe(file)
|
||||
|
||||
const manifest = JSON.parse(formData.get('fileManifest') as string)
|
||||
expect(manifest).toHaveLength(1)
|
||||
expect(manifest[0].fieldName).toBe('file0')
|
||||
expect(manifest[0].relativePath).toBe('teach/SKILL.md')
|
||||
const manifest = fileManifestSchema.parse(parseJsonText(z.string().parse(formData.get('fileManifest'))))
|
||||
expect(manifest).toEqual([{ fieldName: 'file0', relativePath: 'teach/SKILL.md' }])
|
||||
})
|
||||
})
|
||||
})
|
||||
+224
-46
@@ -17,11 +17,184 @@ import type {
|
||||
ManagedOpenCodeConfig,
|
||||
UpdateOpenCodeConfigPatchRequest,
|
||||
} from './types/settings'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
OpenCodeConfigFileSchema,
|
||||
RepoSchema,
|
||||
SettingsResponseSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { OpenCodeManagedConfigSectionsSchema } from '@opencode-manager/shared/opencode'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
|
||||
const DEFAULT_USER_ID = 'default'
|
||||
|
||||
type OpenCodeDiscoveryParams = {
|
||||
baseUrl: string
|
||||
apiKey?: string
|
||||
refresh?: string
|
||||
}
|
||||
|
||||
const settingsResponseSchema: z.ZodType<SettingsResponse> = SettingsResponseSchema.extend({
|
||||
restartRequired: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const openCodeConfigSaveResponseSchema: z.ZodType<OpenCodeConfigSaveResponse> = OpenCodeConfigFileSchema.extend({
|
||||
restartRequired: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const openCodeRestartResponseSchema: z.ZodType<OpenCodeRestartResponse> = z.object({
|
||||
success: z.boolean(),
|
||||
message: z.string(),
|
||||
})
|
||||
|
||||
const openCodeImportStatusBaseSchema = z.object({
|
||||
configSourcePath: z.string().nullable(),
|
||||
configSourcePaths: z.array(z.string()),
|
||||
stateSourcePath: z.string().nullable(),
|
||||
workspaceConfigPath: z.string(),
|
||||
workspaceConfigPathsToRemove: z.array(z.string()),
|
||||
workspaceStatePath: z.string(),
|
||||
workspaceStateExists: z.boolean(),
|
||||
})
|
||||
|
||||
const relinkedReposSchema = z.object({
|
||||
repos: z.array(RepoSchema),
|
||||
relinkedCount: z.number(),
|
||||
existingCount: z.number(),
|
||||
nonRepoPathCount: z.number(),
|
||||
duplicatePathCount: z.number(),
|
||||
errors: z.array(z.object({ path: z.string(), error: z.string() })),
|
||||
})
|
||||
|
||||
const openCodeImportStatusSchema: z.ZodType<OpenCodeImportStatus> = openCodeImportStatusBaseSchema
|
||||
|
||||
const syncOpenCodeImportResponseSchema: z.ZodType<SyncOpenCodeImportResponse> = openCodeImportStatusBaseSchema.extend({
|
||||
success: z.boolean(),
|
||||
message: z.string(),
|
||||
serverRestarted: z.boolean(),
|
||||
configImported: z.boolean(),
|
||||
stateImported: z.boolean(),
|
||||
relinkedRepos: relinkedReposSchema.optional(),
|
||||
})
|
||||
|
||||
const openCodeDirectoryFileInfoBaseSchema = z.object({
|
||||
kind: z.enum(['agents', 'commands']),
|
||||
name: z.string(),
|
||||
relativePath: z.string(),
|
||||
})
|
||||
|
||||
const openCodeDirectoryFileInfoSchema: z.ZodType<OpenCodeDirectoryFileInfo> = openCodeDirectoryFileInfoBaseSchema
|
||||
|
||||
const openCodeDirectoryFileContentSchema: z.ZodType<OpenCodeDirectoryFileInfo & { content: string }> = openCodeDirectoryFileInfoBaseSchema.extend({
|
||||
content: z.string(),
|
||||
})
|
||||
|
||||
const managedOpenCodeConfigSchema: z.ZodType<ManagedOpenCodeConfig> = z.object({
|
||||
info: OpenCodeManagedConfigSectionsSchema,
|
||||
})
|
||||
|
||||
const openCodeModelsResponseSchema = z.object({ models: z.array(z.string()), cached: z.boolean() })
|
||||
|
||||
const activeOpenCodeSessionsResponseSchema = z.object({
|
||||
count: z.number(),
|
||||
sessions: z.array(z.object({ sessionID: z.string(), directory: z.string() })),
|
||||
})
|
||||
|
||||
const openCodeVersionsResponseSchema = z.object({
|
||||
versions: z.array(
|
||||
z.object({
|
||||
version: z.string(),
|
||||
tag: z.string(),
|
||||
name: z.string(),
|
||||
publishedAt: z.string(),
|
||||
}),
|
||||
),
|
||||
currentVersion: z.string().nullable(),
|
||||
})
|
||||
|
||||
const installOpenCodeVersionResponseSchema = z.object({
|
||||
success: z.boolean(),
|
||||
message: z.string(),
|
||||
oldVersion: z.string().optional(),
|
||||
newVersion: z.string().optional(),
|
||||
recovered: z.boolean().optional(),
|
||||
recoveryMessage: z.string().optional(),
|
||||
})
|
||||
|
||||
const upgradeOpenCodeResponseSchema = z.object({
|
||||
success: z.boolean(),
|
||||
message: z.string(),
|
||||
oldVersion: z.string().optional(),
|
||||
newVersion: z.string().optional(),
|
||||
upgraded: z.boolean(),
|
||||
recovered: z.boolean().optional(),
|
||||
recoveryMessage: z.string().optional(),
|
||||
})
|
||||
|
||||
const sshTestResponseSchema = z.object({ success: z.boolean(), message: z.string() })
|
||||
|
||||
const agentsMdResponseSchema = z.object({ content: z.string() })
|
||||
|
||||
const versionInfoSchema: z.ZodType<VersionInfo> = z.object({
|
||||
currentVersion: z.string().nullable(),
|
||||
latestVersion: z.string().nullable(),
|
||||
updateAvailable: z.boolean(),
|
||||
releaseUrl: z.string().nullable(),
|
||||
releaseName: z.string().nullable(),
|
||||
})
|
||||
|
||||
const openCodeServerAuthStatusSchema: z.ZodType<OpenCodeServerAuthStatus> = z.object({
|
||||
isSet: z.boolean(),
|
||||
source: z.enum(['db', 'env', 'managed']),
|
||||
})
|
||||
|
||||
const managerTokenResponseSchema: z.ZodType<ManagerTokenResponse> = z.object({ token: z.string() })
|
||||
|
||||
const agentsMdUpdateResponseSchema = z.object({ success: z.boolean(), restartRequired: z.boolean().optional() })
|
||||
|
||||
const skillFileInfoBaseSchema = z.object({
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
body: z.string(),
|
||||
scope: z.enum(['global', 'project']),
|
||||
location: z.string(),
|
||||
repoId: z.number().optional(),
|
||||
repoName: z.string().optional(),
|
||||
})
|
||||
|
||||
const skillFileInfoSchema: z.ZodType<SkillFileInfo> = skillFileInfoBaseSchema
|
||||
|
||||
const skillFileInfoListSchema = z.array(skillFileInfoSchema)
|
||||
|
||||
const skillFileInfoResponseSchema = skillFileInfoBaseSchema.extend({ restartRequired: z.boolean().optional() })
|
||||
|
||||
const installSkillResponseSchema: z.ZodType<InstallSkillResponse & { restartRequired?: boolean }> = z.object({
|
||||
skill: skillFileInfoSchema,
|
||||
overwritten: z.boolean(),
|
||||
sourceType: z.enum(['github', 'upload']),
|
||||
filesInstalled: z.array(z.string()),
|
||||
restartRequired: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const successResponseSchema = z.object({ success: z.boolean() })
|
||||
|
||||
const skillDeleteResponseSchema = successResponseSchema.extend({ restartRequired: z.boolean().optional() })
|
||||
|
||||
const kindFilesInstalledResponseSchema = z.object({
|
||||
kind: z.enum(['agents', 'commands']),
|
||||
filesInstalled: z.array(z.string()),
|
||||
restartRequired: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const directoryFileInfoSchema = openCodeDirectoryFileInfoBaseSchema.extend({ restartRequired: z.boolean().optional() })
|
||||
|
||||
const directoryFileRefSchema = z.object({
|
||||
kind: z.enum(['agents', 'commands']),
|
||||
relativePath: z.string(),
|
||||
restartRequired: z.boolean().optional(),
|
||||
})
|
||||
|
||||
function appendFilesWithManifest(formData: FormData, files: File[]): void {
|
||||
const fileManifest: Array<{ fieldName: string; relativePath: string }> = []
|
||||
|
||||
@@ -37,7 +210,7 @@ function appendFilesWithManifest(formData: FormData, files: File[]): void {
|
||||
|
||||
export const settingsApi = {
|
||||
getSettings: async (userId = DEFAULT_USER_ID): Promise<SettingsResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, settingsResponseSchema, {
|
||||
params: { userId },
|
||||
})
|
||||
},
|
||||
@@ -46,7 +219,7 @@ export const settingsApi = {
|
||||
updates: UpdateSettingsRequest,
|
||||
userId = DEFAULT_USER_ID
|
||||
): Promise<SettingsResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, settingsResponseSchema, {
|
||||
method: 'PATCH',
|
||||
params: { userId },
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -55,20 +228,20 @@ export const settingsApi = {
|
||||
},
|
||||
|
||||
resetSettings: async (userId = DEFAULT_USER_ID): Promise<SettingsResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings`, settingsResponseSchema, {
|
||||
method: 'DELETE',
|
||||
params: { userId },
|
||||
})
|
||||
},
|
||||
|
||||
getOpenCodeConfig: async (): Promise<OpenCodeConfigFile> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`, OpenCodeConfigFileSchema)
|
||||
},
|
||||
|
||||
updateOpenCodeConfig: async (
|
||||
request: UpdateOpenCodeConfigRequest
|
||||
): Promise<OpenCodeConfigSaveResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`, openCodeConfigSaveResponseSchema, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -76,13 +249,13 @@ export const settingsApi = {
|
||||
},
|
||||
|
||||
getManagedOpenCodeConfig: async (): Promise<ManagedOpenCodeConfig> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config/managed`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config/managed`, managedOpenCodeConfigSchema)
|
||||
},
|
||||
|
||||
patchOpenCodeConfig: async (
|
||||
request: UpdateOpenCodeConfigPatchRequest
|
||||
): Promise<OpenCodeConfigSaveResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config`, openCodeConfigSaveResponseSchema, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
@@ -94,31 +267,31 @@ export const settingsApi = {
|
||||
apiKey?: string,
|
||||
forceRefresh = false,
|
||||
): Promise<{ models: string[]; cached: boolean }> => {
|
||||
const params: Record<string, string> = { baseUrl }
|
||||
const params: OpenCodeDiscoveryParams = { baseUrl }
|
||||
if (apiKey) params.apiKey = apiKey
|
||||
if (forceRefresh) params.refresh = 'true'
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-discover-models`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-discover-models`, openCodeModelsResponseSchema, {
|
||||
params,
|
||||
})
|
||||
},
|
||||
|
||||
restartOpenCodeServer: async (): Promise<OpenCodeRestartResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-restart`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-restart`, openCodeRestartResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
},
|
||||
|
||||
getActiveOpenCodeSessions: async (): Promise<{ count: number; sessions: { sessionID: string; directory: string }[] }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-active-sessions`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-active-sessions`, activeOpenCodeSessionsResponseSchema)
|
||||
},
|
||||
|
||||
getOpenCodeImportStatus: async (): Promise<OpenCodeImportStatus> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-import/status`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-import/status`, openCodeImportStatusSchema)
|
||||
},
|
||||
|
||||
syncOpenCodeImport: async (overwriteState = false): Promise<SyncOpenCodeImportResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-import`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-import`, syncOpenCodeImportResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ overwriteState }),
|
||||
@@ -134,7 +307,7 @@ export const settingsApi = {
|
||||
}>
|
||||
currentVersion: string | null
|
||||
}> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-versions`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-versions`, openCodeVersionsResponseSchema)
|
||||
},
|
||||
|
||||
installOpenCodeVersion: async (version: string): Promise<{
|
||||
@@ -145,7 +318,7 @@ export const settingsApi = {
|
||||
recovered?: boolean
|
||||
recoveryMessage?: string
|
||||
}> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-install-version`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-install-version`, installOpenCodeVersionResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ version }),
|
||||
@@ -161,14 +334,14 @@ export const settingsApi = {
|
||||
recovered?: boolean
|
||||
recoveryMessage?: string
|
||||
}> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-upgrade`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-upgrade`, upgradeOpenCodeResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
},
|
||||
|
||||
testSSHConnection: async (host: string, sshPrivateKey: string, passphrase?: string): Promise<{ success: boolean; message: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/test-ssh`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/test-ssh`, sshTestResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ host, sshPrivateKey, passphrase }),
|
||||
@@ -176,15 +349,15 @@ export const settingsApi = {
|
||||
},
|
||||
|
||||
getAgentsMd: async (): Promise<{ content: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md`, agentsMdResponseSchema)
|
||||
},
|
||||
|
||||
getDefaultAgentsMd: async (): Promise<{ content: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md/default`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md/default`, agentsMdResponseSchema)
|
||||
},
|
||||
|
||||
updateAgentsMd: async (content: string): Promise<{ success: boolean; restartRequired?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md`, agentsMdUpdateResponseSchema, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content }),
|
||||
@@ -192,7 +365,7 @@ export const settingsApi = {
|
||||
},
|
||||
|
||||
getVersionInfo: async (): Promise<VersionInfo> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/health/version`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/health/version`, versionInfoSchema)
|
||||
},
|
||||
|
||||
listManagedSkills: async (repoId?: number, directory?: string): Promise<SkillFileInfo[]> => {
|
||||
@@ -200,43 +373,43 @@ export const settingsApi = {
|
||||
if (repoId) searchParams.set('repoId', String(repoId))
|
||||
if (directory) searchParams.set('directory', directory)
|
||||
const query = searchParams.toString() ? `?${searchParams.toString()}` : ''
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills${query}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills${query}`, skillFileInfoListSchema)
|
||||
},
|
||||
|
||||
getSkill: async (name: string, scope: SkillScope, repoId?: number): Promise<SkillFileInfo> => {
|
||||
const params = new URLSearchParams({ scope })
|
||||
if (repoId) params.set('repoId', String(repoId))
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`, skillFileInfoSchema)
|
||||
},
|
||||
|
||||
createSkill: async (data: CreateSkillRequest): Promise<SkillFileInfo> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills`, {
|
||||
createSkill: async (data: CreateSkillRequest): Promise<SkillFileInfo & { restartRequired?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills`, skillFileInfoResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
},
|
||||
|
||||
updateSkill: async (name: string, scope: SkillScope, data: UpdateSkillRequest, repoId?: number): Promise<SkillFileInfo> => {
|
||||
updateSkill: async (name: string, scope: SkillScope, data: UpdateSkillRequest, repoId?: number): Promise<SkillFileInfo & { restartRequired?: boolean }> => {
|
||||
const params = new URLSearchParams({ scope })
|
||||
if (repoId) params.set('repoId', String(repoId))
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`, skillFileInfoResponseSchema, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
},
|
||||
|
||||
deleteSkill: async (name: string, scope: SkillScope, repoId?: number): Promise<{ success: boolean }> => {
|
||||
deleteSkill: async (name: string, scope: SkillScope, repoId?: number): Promise<{ success: boolean; restartRequired?: boolean }> => {
|
||||
const params = new URLSearchParams({ scope })
|
||||
if (repoId) params.set('repoId', String(repoId))
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/${name}?${params}`, skillDeleteResponseSchema, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
},
|
||||
|
||||
installSkillFromGithub: async (data: InstallSkillFromGithubRequest): Promise<InstallSkillResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, {
|
||||
installSkillFromGithub: async (data: InstallSkillFromGithubRequest): Promise<InstallSkillResponse & { restartRequired?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, installSkillResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
@@ -248,7 +421,7 @@ export const settingsApi = {
|
||||
scope: SkillScope
|
||||
repoId?: number
|
||||
overwrite?: boolean
|
||||
}): Promise<InstallSkillResponse> => {
|
||||
}): Promise<InstallSkillResponse & { restartRequired?: boolean }> => {
|
||||
const formData = new FormData()
|
||||
formData.append('sourceType', 'upload')
|
||||
formData.append('scope', data.scope)
|
||||
@@ -257,7 +430,7 @@ export const settingsApi = {
|
||||
|
||||
appendFilesWithManifest(formData, data.files)
|
||||
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/skills/install`, installSkillResponseSchema, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
@@ -266,20 +439,20 @@ export const settingsApi = {
|
||||
installOpenCodeDirectoryFiles: async (data: {
|
||||
kind: 'agents' | 'commands'
|
||||
files: File[]
|
||||
}): Promise<{ kind: 'agents' | 'commands'; filesInstalled: string[] }> => {
|
||||
}): Promise<{ kind: 'agents' | 'commands'; filesInstalled: string[]; restartRequired?: boolean }> => {
|
||||
const formData = new FormData()
|
||||
formData.append('kind', data.kind)
|
||||
|
||||
appendFilesWithManifest(formData, data.files)
|
||||
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files/install`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files/install`, kindFilesInstalledResponseSchema, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
},
|
||||
|
||||
listOpenCodeDirectoryFiles: async (kind: 'agents' | 'commands'): Promise<OpenCodeDirectoryFileInfo[]> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, z.array(openCodeDirectoryFileInfoSchema), {
|
||||
params: { kind },
|
||||
})
|
||||
},
|
||||
@@ -288,7 +461,7 @@ export const settingsApi = {
|
||||
kind: 'agents' | 'commands',
|
||||
relativePath: string,
|
||||
): Promise<OpenCodeDirectoryFileInfo & { content: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files/content`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files/content`, openCodeDirectoryFileContentSchema, {
|
||||
params: { kind, relativePath },
|
||||
})
|
||||
},
|
||||
@@ -297,8 +470,8 @@ export const settingsApi = {
|
||||
kind: 'agents' | 'commands'
|
||||
relativePath: string
|
||||
content: string
|
||||
}): Promise<OpenCodeDirectoryFileInfo> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, {
|
||||
}): Promise<OpenCodeDirectoryFileInfo & { restartRequired?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, directoryFileInfoSchema, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
@@ -308,8 +481,8 @@ export const settingsApi = {
|
||||
deleteOpenCodeDirectoryFile: async (
|
||||
kind: 'agents' | 'commands',
|
||||
relativePath: string,
|
||||
): Promise<{ kind: 'agents' | 'commands'; relativePath: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, {
|
||||
): Promise<{ kind: 'agents' | 'commands'; relativePath: string; restartRequired?: boolean }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-directory-files`, directoryFileRefSchema, {
|
||||
method: 'DELETE',
|
||||
params: { kind, relativePath },
|
||||
})
|
||||
@@ -330,11 +503,11 @@ export interface OpenCodeServerAuthStatus {
|
||||
}
|
||||
|
||||
export async function getOpenCodeServerAuth(): Promise<OpenCodeServerAuthStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-server-auth`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-server-auth`, openCodeServerAuthStatusSchema)
|
||||
}
|
||||
|
||||
export async function updateOpenCodeServerAuth(password: string | null): Promise<OpenCodeServerAuthStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-server-auth`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-server-auth`, openCodeServerAuthStatusSchema, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
@@ -345,12 +518,17 @@ export interface ManagerTokenResponse {
|
||||
token: string
|
||||
}
|
||||
|
||||
const rotatedManagerTokenResponseSchema: z.ZodType<ManagerTokenResponse & { restartRequired?: boolean }> = z.object({
|
||||
token: z.string(),
|
||||
restartRequired: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export async function getManagerToken(): Promise<ManagerTokenResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/manager-token`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/manager-token`, managerTokenResponseSchema)
|
||||
}
|
||||
|
||||
export async function rotateManagerToken(): Promise<ManagerTokenResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/manager-token/rotate`, {
|
||||
export async function rotateManagerToken(): Promise<ManagerTokenResponse & { restartRequired?: boolean }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/manager-token/rotate`, rotatedManagerTokenResponseSchema, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
import { z } from 'zod'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
|
||||
interface SSHHostKeyResponse {
|
||||
success: boolean
|
||||
error?: string
|
||||
}
|
||||
const sshHostKeyResponseSchema = z.object({
|
||||
success: z.boolean(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
|
||||
type SSHHostKeyResponse = z.infer<typeof sshHostKeyResponseSchema>
|
||||
|
||||
export async function respondSSHHostKey(requestId: string, approved: boolean): Promise<SSHHostKeyResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/ssh/host-key/respond`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/ssh/host-key/respond`, sshHostKeyResponseSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId, response: approved ? 'accept' : 'reject' }),
|
||||
|
||||
+91
-192
@@ -1,220 +1,119 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createFetchFake, type FetchFake, type FetchRoute } from '@/test/fetchFake'
|
||||
import { sttApi } from './stt'
|
||||
import { FetchError } from './fetchWrapper'
|
||||
|
||||
describe('WAV extension selection logic', () => {
|
||||
const originalFetch = global.fetch
|
||||
const mockFetch = vi.fn()
|
||||
function installRoutes(routes: FetchRoute[]): FetchFake {
|
||||
const fetchFake = createFetchFake(routes)
|
||||
fetchFake.install()
|
||||
return fetchFake
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', mockFetch)
|
||||
function audioName(fetchFake: FetchFake): string {
|
||||
const audio = fetchFake.findFormData()?.get('audio')
|
||||
if (!(audio instanceof File)) throw new Error('no audio file was uploaded')
|
||||
return audio.name
|
||||
}
|
||||
|
||||
function abortableResponse(init: RequestInit | undefined): Promise<never> {
|
||||
const signal = init?.signal
|
||||
if (!signal) throw new Error('the request has no abort signal')
|
||||
return new Promise((_resolve, reject) => {
|
||||
const rejectOnAbort = () => {
|
||||
const error = new Error('The operation was aborted')
|
||||
error.name = 'AbortError'
|
||||
reject(error)
|
||||
}
|
||||
if (signal.aborted) {
|
||||
rejectOnAbort()
|
||||
return
|
||||
}
|
||||
signal.addEventListener('abort', rejectOnAbort, { once: true })
|
||||
})
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('sttApi.transcribe audio file naming', () => {
|
||||
const cases = [
|
||||
{ title: 'wav for audio/wav blob', type: 'audio/wav', extension: 'wav' },
|
||||
{ title: 'webm for audio/webm blob', type: 'audio/webm', extension: 'webm' },
|
||||
{ title: 'ogg for audio/ogg blob', type: 'audio/ogg', extension: 'ogg' },
|
||||
{ title: 'm4a for audio/mp4 blob', type: 'audio/mp4', extension: 'm4a' },
|
||||
{ title: 'webm for audio/webm;codecs=opus blob', type: 'audio/webm;codecs=opus', extension: 'webm' },
|
||||
{ title: 'wav for unknown types', type: 'audio/unknown', extension: 'wav' },
|
||||
{ title: 'wav over webm when both present', type: 'audio/wav;codecs=pcm', extension: 'wav' },
|
||||
]
|
||||
|
||||
it.each(cases)('uses $title', async ({ type, extension }) => {
|
||||
const fetchFake = installRoutes([
|
||||
{ method: 'POST', path: '/api/stt/transcribe', respond: () => ({ json: { text: 'test' } }) },
|
||||
])
|
||||
|
||||
await sttApi.transcribe(new Blob([], { type }), 'test-user')
|
||||
|
||||
expect(audioName(fetchFake)).toBe(`recording.${extension}`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sttApi.transcribe request shape', () => {
|
||||
it('includes the user id and sends the audio as multipart form data', async () => {
|
||||
const fetchFake = installRoutes([
|
||||
{ method: 'POST', path: '/api/stt/transcribe', respond: () => ({ json: { text: 'transcribed text' } }) },
|
||||
])
|
||||
|
||||
const result = await sttApi.transcribe(new Blob(['audio data'], { type: 'audio/wav' }), 'custom-user')
|
||||
|
||||
expect(result.text).toBe('transcribed text')
|
||||
expect(fetchFake.lastRequest('POST', '/api/stt/transcribe')?.searchParams.get('userId')).toBe('custom-user')
|
||||
expect(fetchFake.findFormData()?.get('audio')).toBeInstanceOf(File)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
global.fetch = originalFetch
|
||||
})
|
||||
|
||||
const createMockResponse = (ok = true, data = {}) => {
|
||||
return new Response(JSON.stringify(data), {
|
||||
status: ok ? 200 : 400,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
it('should return wav for audio/wav blob', async () => {
|
||||
const blob = new Blob([], { type: 'audio/wav' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'test-user')
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const formData = callArgs[1]?.body as FormData
|
||||
const audioFile = formData.get('audio') as File
|
||||
expect(audioFile.name).toBe('recording.wav')
|
||||
})
|
||||
|
||||
it('should return webm for audio/webm blob', async () => {
|
||||
const blob = new Blob([], { type: 'audio/webm' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'test-user')
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const formData = callArgs[1]?.body as FormData
|
||||
const audioFile = formData.get('audio') as File
|
||||
expect(audioFile.name).toBe('recording.webm')
|
||||
})
|
||||
|
||||
it('should return ogg for audio/ogg blob', async () => {
|
||||
const blob = new Blob([], { type: 'audio/ogg' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'test-user')
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const formData = callArgs[1]?.body as FormData
|
||||
const audioFile = formData.get('audio') as File
|
||||
expect(audioFile.name).toBe('recording.ogg')
|
||||
})
|
||||
|
||||
it('should return m4a for audio/mp4 blob', async () => {
|
||||
const blob = new Blob([], { type: 'audio/mp4' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'test-user')
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const formData = callArgs[1]?.body as FormData
|
||||
const audioFile = formData.get('audio') as File
|
||||
expect(audioFile.name).toBe('recording.m4a')
|
||||
})
|
||||
|
||||
it('should return webm for audio/webm;codecs=opus blob', async () => {
|
||||
const blob = new Blob([], { type: 'audio/webm;codecs=opus' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'test-user')
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const formData = callArgs[1]?.body as FormData
|
||||
const audioFile = formData.get('audio') as File
|
||||
expect(audioFile.name).toBe('recording.webm')
|
||||
})
|
||||
|
||||
it('should default to wav for unknown types', async () => {
|
||||
const blob = new Blob([], { type: 'audio/unknown' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'test-user')
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const formData = callArgs[1]?.body as FormData
|
||||
const audioFile = formData.get('audio') as File
|
||||
expect(audioFile.name).toBe('recording.wav')
|
||||
})
|
||||
|
||||
it('should prioritize wav over webm when both present', async () => {
|
||||
const blob = new Blob([], { type: 'audio/wav;codecs=pcm' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'test-user')
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const formData = callArgs[1]?.body as FormData
|
||||
const audioFile = formData.get('audio') as File
|
||||
expect(audioFile.name).toBe('recording.wav')
|
||||
})
|
||||
|
||||
it('should include userId in request URL', async () => {
|
||||
const blob = new Blob([], { type: 'audio/wav' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'custom-user')
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const url = callArgs[0] as string
|
||||
expect(url).toContain('userId=custom-user')
|
||||
})
|
||||
|
||||
it('should send FormData with audio file', async () => {
|
||||
const blob = new Blob(['audio data'], { type: 'audio/wav' })
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'transcribed text' }))
|
||||
|
||||
await sttApi.transcribe(blob, 'test-user')
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/api/stt/transcribe'),
|
||||
expect.objectContaining({
|
||||
it('surfaces the server transcription error message', async () => {
|
||||
installRoutes([
|
||||
{
|
||||
method: 'POST',
|
||||
body: expect.any(FormData),
|
||||
})
|
||||
)
|
||||
path: '/api/stt/transcribe',
|
||||
respond: () => ({ status: 400, json: { error: 'Audio too short' } }),
|
||||
},
|
||||
])
|
||||
|
||||
const callArgs = mockFetch.mock.calls[0]
|
||||
const formData = callArgs[1]?.body as FormData
|
||||
expect(formData.get('audio')).toBeInstanceOf(File)
|
||||
await expect(sttApi.transcribe(new Blob([], { type: 'audio/wav' }), 'test-user')).rejects.toMatchObject({
|
||||
message: 'Audio too short',
|
||||
statusCode: 400,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('sttApi.transcribe cancellation and timeout', () => {
|
||||
const originalFetch = global.fetch
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
global.fetch = originalFetch
|
||||
})
|
||||
|
||||
it('throws 499 CANCELED when caller aborts', async () => {
|
||||
const blob = new Blob([], { type: 'audio/webm;codecs=opus' })
|
||||
installRoutes([
|
||||
{ method: 'POST', path: '/api/stt/transcribe', respond: (_request, _params, init) => abortableResponse(init) },
|
||||
])
|
||||
const abortController = new AbortController()
|
||||
|
||||
const mockFetch = global.fetch as ReturnType<typeof vi.fn>
|
||||
mockFetch.mockImplementation((_url: string, options: RequestInit) => {
|
||||
const signal = options.signal as AbortSignal
|
||||
return new Promise((_resolve, reject) => {
|
||||
if (signal.aborted) {
|
||||
const err = new Error('The operation was aborted')
|
||||
err.name = 'AbortError'
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
signal.addEventListener('abort', () => {
|
||||
const err = new Error('The operation was aborted')
|
||||
err.name = 'AbortError'
|
||||
reject(err)
|
||||
}, { once: true })
|
||||
})
|
||||
})
|
||||
|
||||
const promise = sttApi.transcribe(blob, 'test-user', abortController.signal)
|
||||
const promise = sttApi.transcribe(new Blob([], { type: 'audio/webm;codecs=opus' }), 'test-user', abortController.signal)
|
||||
|
||||
abortController.abort()
|
||||
|
||||
await expect(promise).rejects.toThrow(FetchError)
|
||||
await expect(promise).rejects.toMatchObject({
|
||||
statusCode: 499,
|
||||
code: 'CANCELED',
|
||||
})
|
||||
await expect(promise).rejects.toBeInstanceOf(FetchError)
|
||||
await expect(promise).rejects.toMatchObject({ statusCode: 499, code: 'CANCELED' })
|
||||
})
|
||||
|
||||
it('throws 408 TIMEOUT when transcription times out', async () => {
|
||||
vi.useFakeTimers()
|
||||
installRoutes([
|
||||
{ method: 'POST', path: '/api/stt/transcribe', respond: (_request, _params, init) => abortableResponse(init) },
|
||||
])
|
||||
|
||||
const blob = new Blob([], { type: 'audio/webm;codecs=opus' })
|
||||
|
||||
const mockFetch = global.fetch as ReturnType<typeof vi.fn>
|
||||
mockFetch.mockImplementation((_url: string, options: RequestInit) => {
|
||||
const signal = options.signal as AbortSignal
|
||||
return new Promise((_resolve, reject) => {
|
||||
if (signal.aborted) {
|
||||
const err = new Error('The operation was aborted')
|
||||
err.name = 'AbortError'
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
signal.addEventListener('abort', () => {
|
||||
const err = new Error('The operation was aborted')
|
||||
err.name = 'AbortError'
|
||||
reject(err)
|
||||
}, { once: true })
|
||||
})
|
||||
})
|
||||
|
||||
const promise = sttApi.transcribe(blob, 'test-user')
|
||||
const promise = sttApi.transcribe(new Blob([], { type: 'audio/webm;codecs=opus' }), 'test-user')
|
||||
|
||||
vi.advanceTimersByTime(60000)
|
||||
|
||||
await expect(promise).rejects.toThrow(FetchError)
|
||||
await expect(promise).rejects.toMatchObject({
|
||||
statusCode: 408,
|
||||
code: 'TIMEOUT',
|
||||
})
|
||||
|
||||
vi.useRealTimers()
|
||||
await expect(promise).rejects.toBeInstanceOf(FetchError)
|
||||
await expect(promise).rejects.toMatchObject({ statusCode: 408, code: 'TIMEOUT' })
|
||||
})
|
||||
})
|
||||
+23
-22
@@ -1,36 +1,34 @@
|
||||
import { z } from 'zod'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
|
||||
export interface STTModelsResponse {
|
||||
models: string[]
|
||||
cached: boolean
|
||||
}
|
||||
const sttModelsResponseSchema = z.object({ models: z.array(z.string()), cached: z.boolean() })
|
||||
const sttStatusResponseSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
configured: z.boolean(),
|
||||
provider: z.enum(['external', 'builtin']),
|
||||
model: z.string(),
|
||||
})
|
||||
const sttTranscribeResponseSchema = z.object({ text: z.string() })
|
||||
const sttErrorResponseSchema = z.object({ error: z.string(), details: z.string().optional() })
|
||||
|
||||
export interface STTStatusResponse {
|
||||
enabled: boolean
|
||||
configured: boolean
|
||||
provider: 'external' | 'builtin'
|
||||
model: string
|
||||
}
|
||||
export type STTModelsResponse = z.infer<typeof sttModelsResponseSchema>
|
||||
|
||||
export interface STTTranscribeResponse {
|
||||
text: string
|
||||
}
|
||||
export type STTStatusResponse = z.infer<typeof sttStatusResponseSchema>
|
||||
|
||||
export interface STTErrorResponse {
|
||||
error: string
|
||||
details?: string
|
||||
}
|
||||
export type STTTranscribeResponse = z.infer<typeof sttTranscribeResponseSchema>
|
||||
|
||||
export type STTErrorResponse = z.infer<typeof sttErrorResponseSchema>
|
||||
|
||||
export const sttApi = {
|
||||
getModels: async (userId = 'default', forceRefresh = false): Promise<STTModelsResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/stt/models`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/stt/models`, sttModelsResponseSchema, {
|
||||
params: { userId, ...(forceRefresh && { refresh: 'true' }) },
|
||||
})
|
||||
},
|
||||
|
||||
getStatus: async (userId = 'default'): Promise<STTStatusResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/stt/status`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/stt/status`, sttStatusResponseSchema, {
|
||||
params: { userId },
|
||||
})
|
||||
},
|
||||
@@ -77,11 +75,14 @@ export const sttApi = {
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({ error: 'Transcription failed' }))
|
||||
throw new FetchError(data.error || 'Transcription failed', response.status)
|
||||
const parsedError = sttErrorResponseSchema.safeParse(await response.json().catch(() => null))
|
||||
throw new FetchError(
|
||||
(parsedError.success ? parsedError.data.error : undefined) || 'Transcription failed',
|
||||
response.status,
|
||||
)
|
||||
}
|
||||
|
||||
return response.json()
|
||||
return sttTranscribeResponseSchema.parse(await response.json())
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId)
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
|
||||
@@ -1,113 +1,126 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { TerminalInfo } from '@opencode-manager/shared/types'
|
||||
import { createFetchFake, type FetchRoute } from '@/test/fetchFake'
|
||||
import { renderHookWithProviders } from '@/test/render'
|
||||
import { resizeTerminal, useCreateTerminal, useRemoveTerminal, useTerminals } from './terminals'
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
const hookProviders = { auth: false, theme: false, toaster: false } as const
|
||||
|
||||
function jsonResponse(body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), { status: 200 })
|
||||
const terminal: TerminalInfo = {
|
||||
id: 'pty-1',
|
||||
title: 'Terminal',
|
||||
kind: 'shell',
|
||||
cwd: '/home/me/app',
|
||||
status: 'running',
|
||||
}
|
||||
|
||||
function createWrapper(queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })) {
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function lastRequestUrl(): string {
|
||||
return String(fetchMock.mock.calls.at(-1)?.[0])
|
||||
}
|
||||
const listCases = [
|
||||
{
|
||||
title: 'lists repo terminals through the repo route',
|
||||
target: { kind: 'repo', repoId: 1 },
|
||||
collectionPath: '/api/repos/1/terminals',
|
||||
},
|
||||
{
|
||||
title: 'lists linked server terminals through the server route',
|
||||
target: { kind: 'server', serverId: 'srv_kitchen' },
|
||||
collectionPath: '/api/opencode-servers/srv_kitchen/terminals',
|
||||
},
|
||||
] as const
|
||||
|
||||
describe('terminal api targets', () => {
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('lists repo terminals through the repo route', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ terminals: [] }))
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useTerminals({ kind: 'repo', repoId: 1 }, '/repo', { enabled: true }),
|
||||
{ wrapper: createWrapper() },
|
||||
it.each(listCases)('$title', async ({ target, collectionPath }) => {
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useTerminals(target, '/home/me/app', { enabled: true }),
|
||||
{
|
||||
...hookProviders,
|
||||
fetchRoutes: [
|
||||
{ method: 'GET', path: collectionPath, respond: () => ({ json: { terminals: [terminal] } }) },
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
const url = new URL(lastRequestUrl())
|
||||
expect(url.pathname).toBe('/api/repos/1/terminals')
|
||||
expect(url.searchParams.get('directory')).toBe('/repo')
|
||||
})
|
||||
|
||||
it('lists linked server terminals through the server route', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ terminals: [] }))
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useTerminals({ kind: 'server', serverId: 'srv_kitchen' }, '/home/me/app', { enabled: true }),
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
const url = new URL(lastRequestUrl())
|
||||
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals')
|
||||
expect(url.searchParams.get('directory')).toBe('/home/me/app')
|
||||
await waitFor(() => expect(result.current.data).toEqual([terminal]))
|
||||
expect(fetchFake.lastRequest('GET', collectionPath)?.searchParams.get('directory')).toBe('/home/me/app')
|
||||
})
|
||||
|
||||
it('scopes the query key to the linked server', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ terminals: [] }))
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
|
||||
const { result } = renderHook(
|
||||
const { result, queryClient, fetchFake } = renderHookWithProviders(
|
||||
() => useTerminals({ kind: 'server', serverId: 'srv_kitchen' }, '/home/me/app', { enabled: true }),
|
||||
{ wrapper: createWrapper(queryClient) },
|
||||
{
|
||||
...hookProviders,
|
||||
fetchRoutes: [
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/opencode-servers/srv_kitchen/terminals',
|
||||
respond: () => ({ json: { terminals: [] } }),
|
||||
},
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
expect(
|
||||
queryClient.getQueryCache().findAll({ queryKey: ['terminals', 'srv_kitchen'] }),
|
||||
).toHaveLength(1)
|
||||
expect(queryClient.getQueryCache().findAll({ queryKey: ['terminals', 'srv_kitchen'] })).toHaveLength(1)
|
||||
expect(fetchFake.findRequests('GET', '/api/opencode-servers/srv_kitchen/terminals')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('creates a linked server terminal through the server route', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse({ id: 'pty-1', title: 'Terminal', kind: 'shell', cwd: '/home/me/app', status: 'running' }),
|
||||
)
|
||||
|
||||
const { result } = renderHook(
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useCreateTerminal({ kind: 'server', serverId: 'srv_kitchen' }),
|
||||
{ wrapper: createWrapper() },
|
||||
{
|
||||
...hookProviders,
|
||||
fetchRoutes: [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/opencode-servers/srv_kitchen/terminals',
|
||||
respond: () => ({ json: terminal }),
|
||||
},
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
await act(() => result.current.mutateAsync({ directory: '/home/me/app' }))
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({ directory: '/home/me/app' })
|
||||
})
|
||||
|
||||
const url = new URL(lastRequestUrl())
|
||||
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals')
|
||||
expect(fetchMock.mock.calls.at(-1)?.[1]?.method).toBe('POST')
|
||||
expect(fetchFake.lastRequest('POST', '/api/opencode-servers/srv_kitchen/terminals')?.body).toEqual({
|
||||
directory: '/home/me/app',
|
||||
})
|
||||
})
|
||||
|
||||
it('removes a linked server terminal with the directory', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
|
||||
|
||||
const { result } = renderHook(
|
||||
const { result, fetchFake } = renderHookWithProviders(
|
||||
() => useRemoveTerminal({ kind: 'server', serverId: 'srv_kitchen' }),
|
||||
{ wrapper: createWrapper() },
|
||||
{
|
||||
...hookProviders,
|
||||
fetchRoutes: [
|
||||
{
|
||||
method: 'DELETE',
|
||||
path: '/api/opencode-servers/srv_kitchen/terminals/pty%201',
|
||||
respond: () => ({ status: 204 }),
|
||||
},
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
await act(() => result.current.mutateAsync({ ptyID: 'pty 1', directory: '/home/me/app' }))
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync({ ptyID: 'pty 1', directory: '/home/me/app' })
|
||||
})
|
||||
|
||||
const url = new URL(lastRequestUrl())
|
||||
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals/pty%201')
|
||||
expect(url.searchParams.get('directory')).toBe('/home/me/app')
|
||||
expect(fetchMock.mock.calls.at(-1)?.[1]?.method).toBe('DELETE')
|
||||
const removeRequest = fetchFake.lastRequest('DELETE', '/api/opencode-servers/srv_kitchen/terminals/pty%201')
|
||||
expect(removeRequest?.searchParams.get('directory')).toBe('/home/me/app')
|
||||
})
|
||||
|
||||
it('resizes a linked server terminal', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse({ success: true }))
|
||||
const routes: FetchRoute[] = [
|
||||
{
|
||||
method: 'PATCH',
|
||||
path: '/api/opencode-servers/srv_kitchen/terminals/pty-1',
|
||||
respond: () => ({ json: { success: true } }),
|
||||
},
|
||||
]
|
||||
const fetchFake = createFetchFake(routes)
|
||||
fetchFake.install()
|
||||
|
||||
await resizeTerminal({ kind: 'server', serverId: 'srv_kitchen' }, 'pty-1', {
|
||||
directory: '/home/me/app',
|
||||
@@ -115,8 +128,10 @@ describe('terminal api targets', () => {
|
||||
rows: 24,
|
||||
})
|
||||
|
||||
const url = new URL(lastRequestUrl())
|
||||
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals/pty-1')
|
||||
expect(fetchMock.mock.calls.at(-1)?.[1]?.method).toBe('PATCH')
|
||||
expect(fetchFake.lastRequest('PATCH', '/api/opencode-servers/srv_kitchen/terminals/pty-1')?.body).toEqual({
|
||||
directory: '/home/me/app',
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { z } from 'zod'
|
||||
import { TerminalInfoSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { CreateTerminalRequest, ResizeTerminalRequest, TerminalInfo } from '@opencode-manager/shared/types'
|
||||
|
||||
const terminalListResponseSchema = z.object({ terminals: z.array(TerminalInfoSchema) })
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { terminalCollectionPath, terminalItemPath, terminalTargetScope, type TerminalTarget } from '@/lib/terminal-target'
|
||||
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
@@ -13,15 +17,16 @@ function terminalsScopeQueryKey(target: TerminalTarget) {
|
||||
}
|
||||
|
||||
async function listTerminals(target: TerminalTarget, directory?: string): Promise<TerminalInfo[]> {
|
||||
const data = await fetchWrapper<{ terminals: TerminalInfo[] }>(
|
||||
const data = await fetchWrapper(
|
||||
`${API_BASE_URL}${terminalCollectionPath(target)}`,
|
||||
terminalListResponseSchema,
|
||||
{ params: { directory } },
|
||||
)
|
||||
return data.terminals
|
||||
}
|
||||
|
||||
async function createTerminal(target: TerminalTarget, body: CreateTerminalRequest): Promise<TerminalInfo> {
|
||||
return fetchWrapper<TerminalInfo>(`${API_BASE_URL}${terminalCollectionPath(target)}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}${terminalCollectionPath(target)}`, TerminalInfoSchema, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
|
||||
+24
-26
@@ -1,53 +1,51 @@
|
||||
import { z } from 'zod'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, fetchWrapperBlob } from './fetchWrapper'
|
||||
|
||||
export interface TTSModelsResponse {
|
||||
models: string[]
|
||||
cached: boolean
|
||||
}
|
||||
const ttsModelsResponseSchema = z.object({ models: z.array(z.string()), cached: z.boolean() })
|
||||
const ttsVoicesResponseSchema = z.object({ voices: z.array(z.string()), cached: z.boolean() })
|
||||
const ttsClearCacheResponseSchema = z.object({ cleared: z.number() })
|
||||
const ttsStatusResponseSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
configured: z.boolean(),
|
||||
cache: z.object({
|
||||
count: z.number(),
|
||||
sizeBytes: z.number(),
|
||||
sizeMB: z.number(),
|
||||
maxSizeMB: z.number(),
|
||||
ttlHours: z.number(),
|
||||
}),
|
||||
})
|
||||
|
||||
export interface TTSVoicesResponse {
|
||||
voices: string[]
|
||||
cached: boolean
|
||||
}
|
||||
export type TTSModelsResponse = z.infer<typeof ttsModelsResponseSchema>
|
||||
|
||||
export interface TTSClearCacheResponse {
|
||||
cleared: number
|
||||
}
|
||||
export type TTSVoicesResponse = z.infer<typeof ttsVoicesResponseSchema>
|
||||
|
||||
export interface TTSStatusResponse {
|
||||
enabled: boolean
|
||||
configured: boolean
|
||||
cache: {
|
||||
count: number
|
||||
sizeBytes: number
|
||||
sizeMB: number
|
||||
maxSizeMB: number
|
||||
ttlHours: number
|
||||
}
|
||||
}
|
||||
export type TTSClearCacheResponse = z.infer<typeof ttsClearCacheResponseSchema>
|
||||
|
||||
export type TTSStatusResponse = z.infer<typeof ttsStatusResponseSchema>
|
||||
|
||||
export const ttsApi = {
|
||||
getModels: async (userId = 'default', forceRefresh = false): Promise<TTSModelsResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/tts/models`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/tts/models`, ttsModelsResponseSchema, {
|
||||
params: { userId, ...(forceRefresh && { refresh: 'true' }) },
|
||||
})
|
||||
},
|
||||
|
||||
getVoices: async (userId = 'default', forceRefresh = false): Promise<TTSVoicesResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/tts/voices`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/tts/voices`, ttsVoicesResponseSchema, {
|
||||
params: { userId, ...(forceRefresh && { refresh: 'true' }) },
|
||||
})
|
||||
},
|
||||
|
||||
getStatus: async (userId = 'default'): Promise<TTSStatusResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/tts/status`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/tts/status`, ttsStatusResponseSchema, {
|
||||
params: { userId },
|
||||
})
|
||||
},
|
||||
|
||||
clearCache: async (): Promise<TTSClearCacheResponse> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/tts/cache`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/tts/cache`, ttsClearCacheResponseSchema, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
},
|
||||
|
||||
@@ -25,14 +25,14 @@ import {
|
||||
type InstallSkillResponse,
|
||||
type SettingsResponse as SharedSettingsResponse,
|
||||
} from '@opencode-manager/shared'
|
||||
import type { OpenCodeConfigInfo } from '@opencode-manager/shared/opencode'
|
||||
import type {
|
||||
OpenCodeAgentConfig,
|
||||
OpenCodeManagedConfigSections,
|
||||
OpenCodeCommandConfig,
|
||||
OpenCodeProviderConfig,
|
||||
OpenCodeProviderModelConfig,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
import type { NotificationPreferences, Repo } from '@opencode-manager/shared/types'
|
||||
import { saveFile } from '@/lib/download'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigFile, OpenCodeConfigSourceFile, OpenCodeConfigSourceName, UpdateOpenCodeConfigRequest, UpdateOpenCodeConfigPatchRequest, SandboxPreferences, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
@@ -82,7 +82,7 @@ export interface SyncOpenCodeImportResponse extends OpenCodeImportStatus {
|
||||
configImported: boolean
|
||||
stateImported: boolean
|
||||
relinkedRepos?: {
|
||||
repos: Array<Record<string, unknown>>
|
||||
repos: Repo[]
|
||||
relinkedCount: number
|
||||
existingCount: number
|
||||
nonRepoPathCount: number
|
||||
@@ -98,37 +98,21 @@ export interface OpenCodeDirectoryFileInfo {
|
||||
}
|
||||
|
||||
export interface ManagedOpenCodeConfig {
|
||||
info: OpenCodeConfigInfo
|
||||
info: OpenCodeManagedConfigSections
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge-patch value for one agent: an explicit null clears the stored field,
|
||||
* while an omitted field stays untouched.
|
||||
*/
|
||||
export type OpenCodeAgentPatch = {
|
||||
[K in keyof OpenCodeAgentConfig]?: OpenCodeAgentConfig[K] | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge-patch value for one command: an explicit null clears the stored field,
|
||||
* while an omitted field stays untouched.
|
||||
*/
|
||||
export type OpenCodeCommandPatch = {
|
||||
[K in keyof OpenCodeCommandConfig]?: OpenCodeCommandConfig[K] | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge-patch value for one provider model: an explicit null clears the stored
|
||||
* field, while an omitted field stays untouched.
|
||||
*/
|
||||
export type OpenCodeProviderModelPatch = {
|
||||
[K in keyof OpenCodeProviderModelConfig]?: OpenCodeProviderModelConfig[K] | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge-patch value for one provider: an explicit null clears the stored field,
|
||||
* a null model entry removes that model, and omitted entries stay untouched.
|
||||
*/
|
||||
export type OpenCodeProviderPatch = {
|
||||
[K in keyof OpenCodeProviderConfig]?: K extends 'models'
|
||||
? Record<string, OpenCodeProviderModelPatch | null> | null
|
||||
|
||||
Reference in new issue
Block a user