mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-05-28 23:15:33 +08:00
* feat: add opencode support
* fix: stabilize opencode session startup
* fix: /models
* fix: improveUI for commands
* fix: format commands.js
* feat: load models through provider adapters
Provider model selection had outgrown a single hardcoded service.
The old service mixed shared caching with provider catalogs and CLI lookup details.
That made stale model lists more likely as providers changed on separate schedules.
Move model discovery behind each provider so lookup lives next to the integration.
The shared service now focuses on provider resolution, caching, persistence, and dedupe.
Return cache metadata and add bypassCache because model availability changes outside the app.
The UI and /models command can show freshness and let users force a provider refresh.
Surface model descriptions while keeping fallback catalogs for unavailable CLIs or SDKs.
* feat(models): resolve active session models through provider adapters
The model inventory command was showing a mix of catalog defaults and
composer-local state instead of the model that is actually active for a
real provider session. That made /models, /cost, and /status
misleading once a session had already started, especially for providers
whose effective runtime model can differ from the optimistic model value
held in the UI.
Introduce an explicit getCurrentActiveModel() contract on
IProviderModels so model resolution lives next to each provider's
catalog logic and uses the provider-native source of truth:
- Claude reads the init event from a resumed stream-json run
- Codex reads model from ~/.codex/config.toml
- Cursor reads lastUsedModel from the chat store.db
- OpenCode reads the persisted session model from opencode.db
- Gemini intentionally returns its default because the CLI does not
provide a reliable active-session lookup
Keep the returned shape intentionally minimal ({ model }). The goal is
to expose only what downstream command consumers need and avoid leaking
provider-specific metadata into a shared transport shape that would
create extra UI coupling and future cleanup cost.
Also make command behavior session-aware: when there is no concrete
session id, do not spawn provider processes or inspect provider session
storage just to answer /models, /cost, or /status. In a new-session
view the correct answer is simply the provider default, and doing more
work there adds latency and unnecessary side effects for no user value.
As part of this, centralize two supporting concerns:
- add a shared helper for building the default current-model result from
a provider catalog so fallbacks stay aligned with DEFAULT
- move leaf-directory validation into shared utils so Cursor session
readers and model lookup code enforce the same path-safety rule
Tests were expanded to cover both the new service delegation path and
the sessionless command behavior, while keeping cache-sensitive tests
isolated from persisted host cache state.
Why this change:
- command output should reflect the model actually driving a session
- new-session views should stay fast and side-effect free
- provider-specific active-model lookup should not be scattered across
routes or UI code
- fallback behavior should be explicit, consistent, and limited to the
provider default when no true active model can be resolved
* feat: support session-scoped model overrides
Model selection was acting like a provider-level preference.
That made resumed sessions drift back to a default or request-time model.
Users expect /models changes made inside a conversation to affect that session.
Store explicit session choices in app-owned ~/.cloudcli state.
This avoids editing provider transcripts or native provider config.
Resolve the effective model before launching each provider runtime.
Claude, Cursor, Codex, Gemini, and OpenCode now honor stored resume choices.
Expose a backend active-model change endpoint for existing sessions.
The models modal can now distinguish default changes from session overrides.
It also shows when a selected model will apply on the next response.
For Claude, stop probing active model state by resuming with a dummy prompt.
Read the indexed JSONL transcript from the end instead.
This preserves provider history while honoring /model stdout or model fields.
Add service tests for adapter delegation and resume-model precedence.
The tests keep cache state, override state, and requested fallback separate.
* feat: make command modal more compact
* fix: preserve opencode session creation events
OpenCode emits the real session id asynchronously on its first JSON output. The runner
registered that id from a helper that could not see the spawned process because
the process reference was scoped inside the model-resolution callback. That
ReferenceError was swallowed by the generic JSON parse fallback, so the client
never received session_created. Without that event, a new OpenCode chat stayed
on / and the assistant stream was not attached to the new session view.
Keep the process reference in the outer spawn scope so registration can update
the active-process map and websocket writer as soon as OpenCode announces the
session id. Split JSON parsing from event processing so malformed non-JSON
output can still stream as raw text, while registration or adapter failures are
surfaced as real errors instead of being hidden as assistant content.
Add a fake opencode executable regression test to lock in the expected lifecycle
ordering: session_created must be sent before live assistant messages, and the
same session id must carry through stream_end and complete.
* fix: clarify model refresh and onboarding providers
OpenCode is now a supported chat provider, but first-run onboarding still only offered
Claude, Cursor, Codex, and Gemini. That made OpenCode harder to discover and
forced users to finish setup before finding the provider in settings or chat.
Adding it to onboarding keeps first-run setup aligned with the providers the
application already supports elsewhere.
The model refresh control was also doing too much visual work. In the new chat
model picker, the previous Hard Refresh label looked like the dialog heading,
which made the primary task unclear. Users open that dialog to choose a model;
refreshing catalogs is only a secondary maintenance action for stale cached
provider model lists.
Rename and reposition the refresh affordance so the model picker reads as a
model picker first. The copy now explains why catalogs are cached, when a refresh
is useful, and that the refresh checks every provider. The /models modal gets the
same clarification so both model-selection surfaces describe the cache behavior
consistently.
* fix: format opencode model catalog labels
OpenCode returns provider-prefixed ids directly from the CLI. Passing those ids through as
labels made the model picker hard to scan: users saw values like
anthropic/claude-3-5-sonnet-20241022 or lowercased, hyphen-split text instead
of readable model names.
Keep the exact OpenCode id as the option value because that is what the CLI
expects, but derive a presentation label for the frontend. The formatter is
intentionally generic rather than a catalog of known providers. It handles common
identifier structure such as provider/model, hyphen-delimited words, v-prefixed
versions, adjacent numeric version tokens, and 8-digit date suffixes.
This keeps OpenCode usable as its model list expands across many upstream
providers without requiring code changes for every new provider or model family.
The description keeps the raw provider-prefixed id visible so users can still
confirm the precise model being selected.
* feat: add more fallback models for cursor
* docs: move model catalog out of shared
The model catalog is no longer a frontend/backend runtime contract.
Keeping it under shared made ownership misleading. It implied the catalog was
application code shared by runtime consumers, even though it now only supports
README links and public API documentation.
Move the catalog into public so it lives beside the docs surfaces that need it.
This gives the API docs a stable, served module and gives README readers a
linkable source without suggesting frontend or backend runtime dependency.
Render the API docs model list from the exported provider registry instead of a
hardcoded Claude/Cursor/Codex subset. That keeps Gemini and OpenCode visible and
makes future provider documentation changes flow through one docs-specific file.
Update README links, provider maintenance notes, and package files so published
artifacts include the standalone docs page and model catalog without relying on
the old shared path.
* fix: simplify empty-state model selector
Keep the provider empty state focused on the setup action users need there:
choosing a model.
The refresh control, cache timestamp, and refresh explanation made the dialog feel
like a cache-management surface.
That extra action is out of place in the empty state, where the goal is to start
a chat with the selected provider and model.
Remove the refresh-specific UI from ProviderSelectionEmptyState and drop the
now-unused refresh/cache props from the ChatMessagesPane pass-through.
Refresh behavior remains available in the dedicated command result flow.
519 lines
16 KiB
TypeScript
519 lines
16 KiB
TypeScript
import express, { type Request, type Response } from 'express';
|
|
|
|
import { providerAuthService } from '@/modules/providers/services/provider-auth.service.js';
|
|
import { providerMcpService } from '@/modules/providers/services/mcp.service.js';
|
|
import { providerModelsService } from '@/modules/providers/services/provider-models.service.js';
|
|
import { providerSkillsService } from '@/modules/providers/services/skills.service.js';
|
|
import { sessionConversationsSearchService } from '@/modules/providers/services/session-conversations-search.service.js';
|
|
import { sessionsService } from '@/modules/providers/services/sessions.service.js';
|
|
import type {
|
|
LLMProvider,
|
|
McpScope,
|
|
McpTransport,
|
|
ProviderChangeActiveModelInput,
|
|
UpsertProviderMcpServerInput,
|
|
} from '@/shared/types.js';
|
|
import { AppError, asyncHandler, createApiSuccessResponse } from '@/shared/utils.js';
|
|
|
|
const router = express.Router();
|
|
|
|
const readPathParam = (value: unknown, name: string): string => {
|
|
if (typeof value === 'string') {
|
|
return value;
|
|
}
|
|
|
|
if (Array.isArray(value) && typeof value[0] === 'string') {
|
|
return value[0];
|
|
}
|
|
|
|
throw new AppError(`${name} path parameter is invalid.`, {
|
|
code: 'INVALID_PATH_PARAMETER',
|
|
statusCode: 400,
|
|
});
|
|
};
|
|
|
|
const normalizeProviderParam = (value: unknown): string =>
|
|
readPathParam(value, 'provider').trim().toLowerCase();
|
|
|
|
const SESSION_ID_PATTERN = /^[a-zA-Z0-9._-]{1,120}$/;
|
|
|
|
const parseSessionId = (value: unknown): string => {
|
|
const sessionId = readPathParam(value, 'sessionId').trim();
|
|
if (!SESSION_ID_PATTERN.test(sessionId)) {
|
|
throw new AppError('Invalid sessionId.', {
|
|
code: 'INVALID_SESSION_ID',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
return sessionId;
|
|
};
|
|
|
|
const readOptionalQueryString = (value: unknown): string | undefined => {
|
|
if (typeof value !== 'string') {
|
|
return undefined;
|
|
}
|
|
|
|
const normalized = value.trim();
|
|
return normalized.length > 0 ? normalized : undefined;
|
|
};
|
|
|
|
const parseOptionalBooleanQuery = (value: unknown, name: string): boolean | undefined => {
|
|
if (value === undefined) {
|
|
return undefined;
|
|
}
|
|
|
|
const normalized = readOptionalQueryString(value);
|
|
if (!normalized) {
|
|
return undefined;
|
|
}
|
|
|
|
if (normalized === 'true') {
|
|
return true;
|
|
}
|
|
if (normalized === 'false') {
|
|
return false;
|
|
}
|
|
|
|
throw new AppError(`${name} must be "true" or "false".`, {
|
|
code: 'INVALID_QUERY_PARAMETER',
|
|
statusCode: 400,
|
|
});
|
|
};
|
|
|
|
const parseMcpScope = (value: unknown): McpScope | undefined => {
|
|
if (value === undefined) {
|
|
return undefined;
|
|
}
|
|
|
|
const normalized = readOptionalQueryString(value);
|
|
if (!normalized) {
|
|
return undefined;
|
|
}
|
|
|
|
if (normalized === 'user' || normalized === 'local' || normalized === 'project') {
|
|
return normalized;
|
|
}
|
|
|
|
throw new AppError(`Unsupported MCP scope "${normalized}".`, {
|
|
code: 'INVALID_MCP_SCOPE',
|
|
statusCode: 400,
|
|
});
|
|
};
|
|
|
|
const parseMcpTransport = (value: unknown): McpTransport => {
|
|
const normalized = readOptionalQueryString(value);
|
|
if (!normalized) {
|
|
throw new AppError('transport is required.', {
|
|
code: 'MCP_TRANSPORT_REQUIRED',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
if (normalized === 'stdio' || normalized === 'http' || normalized === 'sse') {
|
|
return normalized;
|
|
}
|
|
|
|
throw new AppError(`Unsupported MCP transport "${normalized}".`, {
|
|
code: 'INVALID_MCP_TRANSPORT',
|
|
statusCode: 400,
|
|
});
|
|
};
|
|
|
|
const parseMcpUpsertPayload = (payload: unknown): UpsertProviderMcpServerInput => {
|
|
if (!payload || typeof payload !== 'object') {
|
|
throw new AppError('Request body must be an object.', {
|
|
code: 'INVALID_REQUEST_BODY',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
const body = payload as Record<string, unknown>;
|
|
const name = readOptionalQueryString(body.name);
|
|
if (!name) {
|
|
throw new AppError('name is required.', {
|
|
code: 'MCP_NAME_REQUIRED',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
const transport = parseMcpTransport(body.transport);
|
|
const scope = parseMcpScope(body.scope);
|
|
const workspacePath = readOptionalQueryString(body.workspacePath);
|
|
|
|
return {
|
|
name,
|
|
transport,
|
|
scope,
|
|
workspacePath,
|
|
command: readOptionalQueryString(body.command),
|
|
args: Array.isArray(body.args) ? body.args.filter((entry): entry is string => typeof entry === 'string') : undefined,
|
|
env: typeof body.env === 'object' && body.env !== null
|
|
? Object.fromEntries(
|
|
Object.entries(body.env as Record<string, unknown>).filter(
|
|
(entry): entry is [string, string] => typeof entry[1] === 'string',
|
|
),
|
|
)
|
|
: undefined,
|
|
cwd: readOptionalQueryString(body.cwd),
|
|
url: readOptionalQueryString(body.url),
|
|
headers: typeof body.headers === 'object' && body.headers !== null
|
|
? Object.fromEntries(
|
|
Object.entries(body.headers as Record<string, unknown>).filter(
|
|
(entry): entry is [string, string] => typeof entry[1] === 'string',
|
|
),
|
|
)
|
|
: undefined,
|
|
envVars: Array.isArray(body.envVars)
|
|
? body.envVars.filter((entry): entry is string => typeof entry === 'string')
|
|
: undefined,
|
|
bearerTokenEnvVar: readOptionalQueryString(body.bearerTokenEnvVar),
|
|
envHttpHeaders: typeof body.envHttpHeaders === 'object' && body.envHttpHeaders !== null
|
|
? Object.fromEntries(
|
|
Object.entries(body.envHttpHeaders as Record<string, unknown>).filter(
|
|
(entry): entry is [string, string] => typeof entry[1] === 'string',
|
|
),
|
|
)
|
|
: undefined,
|
|
};
|
|
};
|
|
|
|
const parseProvider = (value: unknown): LLMProvider => {
|
|
const normalized = normalizeProviderParam(value);
|
|
if (
|
|
normalized === 'claude'
|
|
|| normalized === 'codex'
|
|
|| normalized === 'cursor'
|
|
|| normalized === 'gemini'
|
|
|| normalized === 'opencode'
|
|
) {
|
|
return normalized;
|
|
}
|
|
|
|
throw new AppError(`Unsupported provider "${normalized}".`, {
|
|
code: 'UNSUPPORTED_PROVIDER',
|
|
statusCode: 400,
|
|
});
|
|
};
|
|
|
|
const parseSessionRenameSummary = (payload: unknown): string => {
|
|
if (!payload || typeof payload !== 'object') {
|
|
throw new AppError('Request body must be an object.', {
|
|
code: 'INVALID_REQUEST_BODY',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
const body = payload as Record<string, unknown>;
|
|
const summary = typeof body.summary === 'string' ? body.summary.trim() : '';
|
|
if (!summary) {
|
|
throw new AppError('Summary is required.', {
|
|
code: 'INVALID_SESSION_SUMMARY',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
if (summary.length > 500) {
|
|
throw new AppError('Summary must not exceed 500 characters.', {
|
|
code: 'INVALID_SESSION_SUMMARY',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
return summary;
|
|
};
|
|
|
|
const parseSessionSearchQuery = (value: unknown): string => {
|
|
const query = readOptionalQueryString(value) ?? '';
|
|
if (query.length < 2) {
|
|
throw new AppError('Query must be at least 2 characters', {
|
|
code: 'INVALID_SEARCH_QUERY',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
return query;
|
|
};
|
|
|
|
const parseSessionSearchLimit = (value: unknown): number => {
|
|
const raw = readOptionalQueryString(value);
|
|
if (!raw) {
|
|
return 50;
|
|
}
|
|
|
|
const parsed = Number.parseInt(raw, 10);
|
|
if (Number.isNaN(parsed)) {
|
|
throw new AppError('limit must be a valid integer.', {
|
|
code: 'INVALID_QUERY_PARAMETER',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
return Math.max(1, Math.min(parsed, 100));
|
|
};
|
|
|
|
const parseChangeActiveModelPayload = (payload: unknown): ProviderChangeActiveModelInput => {
|
|
if (!payload || typeof payload !== 'object') {
|
|
throw new AppError('Request body must be an object.', {
|
|
code: 'INVALID_REQUEST_BODY',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
const body = payload as Record<string, unknown>;
|
|
const model = readOptionalQueryString(body.model);
|
|
if (!model) {
|
|
throw new AppError('model is required.', {
|
|
code: 'MODEL_REQUIRED',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
return {
|
|
sessionId: '',
|
|
model,
|
|
};
|
|
};
|
|
|
|
router.get(
|
|
'/:provider/auth/status',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const provider = parseProvider(req.params.provider);
|
|
const status = await providerAuthService.getProviderAuthStatus(provider);
|
|
res.json(createApiSuccessResponse(status));
|
|
}),
|
|
);
|
|
|
|
router.get(
|
|
'/:provider/models',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const provider = parseProvider(req.params.provider);
|
|
const bypassCache = parseOptionalBooleanQuery(req.query.bypassCache, 'bypassCache') ?? false;
|
|
const result = await providerModelsService.getProviderModels(provider, { bypassCache });
|
|
res.json(createApiSuccessResponse({ provider, models: result.models, cache: result.cache }));
|
|
}),
|
|
);
|
|
|
|
router.post(
|
|
'/:provider/sessions/:sessionId/active-model',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const provider = parseProvider(req.params.provider);
|
|
const sessionId = parseSessionId(req.params.sessionId);
|
|
const payload = parseChangeActiveModelPayload(req.body);
|
|
const result = await providerModelsService.changeActiveModel(provider, {
|
|
...payload,
|
|
sessionId,
|
|
});
|
|
res.json(createApiSuccessResponse(result));
|
|
}),
|
|
);
|
|
|
|
// ----------------- Skills routes -----------------
|
|
router.get(
|
|
'/:provider/skills',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const provider = parseProvider(req.params.provider);
|
|
const workspacePath = readOptionalQueryString(req.query.workspacePath);
|
|
const skills = await providerSkillsService.listProviderSkills(provider, { workspacePath });
|
|
res.json(createApiSuccessResponse({ provider, skills }));
|
|
}),
|
|
);
|
|
|
|
// ----------------- MCP routes -----------------
|
|
router.get(
|
|
'/:provider/mcp/servers',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const provider = parseProvider(req.params.provider);
|
|
const workspacePath = readOptionalQueryString(req.query.workspacePath);
|
|
const scope = parseMcpScope(req.query.scope);
|
|
|
|
if (scope) {
|
|
const servers = await providerMcpService.listProviderMcpServersForScope(provider, scope, { workspacePath });
|
|
res.json(createApiSuccessResponse({ provider, scope, servers }));
|
|
return;
|
|
}
|
|
|
|
const groupedServers = await providerMcpService.listProviderMcpServers(provider, { workspacePath });
|
|
res.json(createApiSuccessResponse({ provider, scopes: groupedServers }));
|
|
}),
|
|
);
|
|
|
|
router.post(
|
|
'/:provider/mcp/servers',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const provider = parseProvider(req.params.provider);
|
|
const payload = parseMcpUpsertPayload(req.body);
|
|
const server = await providerMcpService.upsertProviderMcpServer(provider, payload);
|
|
res.status(201).json(createApiSuccessResponse({ server }));
|
|
}),
|
|
);
|
|
|
|
router.delete(
|
|
'/:provider/mcp/servers/:name',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const provider = parseProvider(req.params.provider);
|
|
const scope = parseMcpScope(req.query.scope);
|
|
const workspacePath = readOptionalQueryString(req.query.workspacePath);
|
|
const result = await providerMcpService.removeProviderMcpServer(provider, {
|
|
name: readPathParam(req.params.name, 'name'),
|
|
scope,
|
|
workspacePath,
|
|
});
|
|
res.json(createApiSuccessResponse(result));
|
|
}),
|
|
);
|
|
|
|
router.post(
|
|
'/mcp/servers/global',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const payload = parseMcpUpsertPayload(req.body);
|
|
if (payload.scope === 'local') {
|
|
throw new AppError('Global MCP add supports only "user" or "project" scopes.', {
|
|
code: 'INVALID_GLOBAL_MCP_SCOPE',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
const results = await providerMcpService.addMcpServerToAllProviders({
|
|
...payload,
|
|
scope: payload.scope === 'user' ? 'user' : 'project',
|
|
});
|
|
res.status(201).json(createApiSuccessResponse({ results }));
|
|
}),
|
|
);
|
|
|
|
// ----------------- Session routes -----------------
|
|
router.get(
|
|
'/sessions/archived',
|
|
asyncHandler(async (_req: Request, res: Response) => {
|
|
const sessions = sessionsService.listArchivedSessions();
|
|
res.json(createApiSuccessResponse({ sessions }));
|
|
}),
|
|
);
|
|
|
|
router.delete(
|
|
'/sessions/:sessionId',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const sessionId = parseSessionId(req.params.sessionId);
|
|
const force = parseOptionalBooleanQuery(req.query.force, 'force') ?? false;
|
|
const deletedFromDisk = parseOptionalBooleanQuery(req.query.deletedFromDisk, 'deletedFromDisk') ?? force;
|
|
const result = await sessionsService.deleteOrArchiveSessionById(sessionId, {
|
|
force,
|
|
deletedFromDisk,
|
|
});
|
|
res.json(createApiSuccessResponse(result));
|
|
}),
|
|
);
|
|
|
|
router.post(
|
|
'/sessions/:sessionId/restore',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const sessionId = parseSessionId(req.params.sessionId);
|
|
const result = sessionsService.restoreSessionById(sessionId);
|
|
res.json(createApiSuccessResponse(result));
|
|
}),
|
|
);
|
|
|
|
router.put(
|
|
'/sessions/:sessionId',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const sessionId = parseSessionId(req.params.sessionId);
|
|
const summary = parseSessionRenameSummary(req.body);
|
|
const result = sessionsService.renameSessionById(sessionId, summary);
|
|
res.json(createApiSuccessResponse(result));
|
|
}),
|
|
);
|
|
|
|
router.get(
|
|
'/sessions/:sessionId/messages',
|
|
asyncHandler(async (req: Request, res: Response) => {
|
|
const sessionId = parseSessionId(req.params.sessionId);
|
|
const limitRaw = readOptionalQueryString(req.query.limit);
|
|
const offsetRaw = readOptionalQueryString(req.query.offset);
|
|
|
|
let limit: number | null = null;
|
|
if (limitRaw !== undefined) {
|
|
const parsedLimit = Number.parseInt(limitRaw, 10);
|
|
if (Number.isNaN(parsedLimit) || parsedLimit < 0) {
|
|
throw new AppError('limit must be a non-negative integer.', {
|
|
code: 'INVALID_QUERY_PARAMETER',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
limit = parsedLimit;
|
|
}
|
|
|
|
let offset = 0;
|
|
if (offsetRaw !== undefined) {
|
|
const parsedOffset = Number.parseInt(offsetRaw, 10);
|
|
if (Number.isNaN(parsedOffset) || parsedOffset < 0) {
|
|
throw new AppError('offset must be a non-negative integer.', {
|
|
code: 'INVALID_QUERY_PARAMETER',
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
offset = parsedOffset;
|
|
}
|
|
|
|
const result = await sessionsService.fetchHistory(sessionId, {
|
|
limit,
|
|
offset,
|
|
});
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
router.get('/search/sessions', asyncHandler(async (req: Request, res: Response) => {
|
|
const query = parseSessionSearchQuery(req.query.q);
|
|
const limit = parseSessionSearchLimit(req.query.limit);
|
|
|
|
res.writeHead(200, {
|
|
'Content-Type': 'text/event-stream',
|
|
'Cache-Control': 'no-cache',
|
|
Connection: 'keep-alive',
|
|
'X-Accel-Buffering': 'no',
|
|
});
|
|
|
|
let closed = false;
|
|
const abortController = new AbortController();
|
|
req.on('close', () => {
|
|
closed = true;
|
|
abortController.abort();
|
|
});
|
|
|
|
try {
|
|
await sessionConversationsSearchService.search({
|
|
query,
|
|
limit,
|
|
signal: abortController.signal,
|
|
onProgress: ({ projectResult, totalMatches, scannedProjects, totalProjects }) => {
|
|
if (closed) {
|
|
return;
|
|
}
|
|
|
|
if (projectResult) {
|
|
res.write(`event: result\ndata: ${JSON.stringify({ projectResult, totalMatches, scannedProjects, totalProjects })}\n\n`);
|
|
return;
|
|
}
|
|
|
|
res.write(`event: progress\ndata: ${JSON.stringify({ totalMatches, scannedProjects, totalProjects })}\n\n`);
|
|
},
|
|
});
|
|
|
|
if (!closed) {
|
|
res.write('event: done\ndata: {}\n\n');
|
|
}
|
|
} catch (error) {
|
|
console.error('Error searching conversations:', error);
|
|
if (!closed) {
|
|
res.write(`event: error\ndata: ${JSON.stringify({ error: 'Search failed' })}\n\n`);
|
|
}
|
|
} finally {
|
|
if (!closed) {
|
|
res.end();
|
|
}
|
|
}
|
|
}));
|
|
|
|
export default router;
|