Files
openchamber/packages/ui/src/stores/useMcpStore.ts
T
Bohdan Triapitsyn 79143bff4c feat: massive chat reliability + UX pass (web/desktop/mobile/vscode) (#593)
## Added Features
- Add VS Code save-as-image flow for assistant messages via webview bridge + native save dialog.
- Add hourly desktop update checks after startup.
- Add new tool output display mode: `Changes` (auto-expand edit/write/patch only; keep activity expanded; mode guidance text).
- Add GitHub PR attachment flow in chat input with PR picker + attached PR chip/details.
- Add mobile overlay presentation for GitHub Issue and PR pickers (shared with desktop picker content).

## Fixes
- Save-gate project icon updates until explicit Save; allow icon removal with same save-gated behavior.
- Restore clickable chat action buttons in sticky header mode (desktop + Firefox hit-target issue).
- Clamp sticky user messages to bounded chat height and allow internal scrolling.
- Prevent drawer context crash during iPad/tablet orientation switching.
- Improve text-selection action menu placement on narrow screens.
- Move assistant message time into clock tooltip; keep duration display clean.
- Hide `Link GitHub Issue` row in VS Code chat input area (GitHub flow is not yet ready there).
- Remove laggy close animation in text-selection popover; keep open motion/positioning behavior.
- Fetch branches when picker opens and cache empty; show loading state instead of false “No branches found”.
- Fix share-image export metadata rendering (theme background resolution, timestamp rendering, footer alignment).
- Scope MCP services status/toggles to active directory to avoid cross-project leakage.
- Improve long user-message clamp behavior (40% cap variant, hidden scrollbar, scroll shadows, expansion detection).
- Fix desktop `Check for Updates` menu handler; prevent duplicate checks; show clear success/error toasts.
- Stabilize long user-message scrolling behavior (follow-up hardening).
- Avoid premature web update failure on slower servers.
- Restore user message image previews + fullscreen gallery navigation payload.
- Repair desktop chat drag-and-drop image attachments when native drop coords are missing.
- Move GitHub issue linking entry into Add attachment menu.
- Align header context usage percentage visuals with context panel.
- Align `@` file search with active project in all runtimes.
- Route `@` file discovery through OpenCode SDK `find.files`; remove legacy `/api/fs/search` reliance.
- Make chat `@` mention behavior consistent with files-style behavior.
- Keep status-row todos in stable order after status changes; add compact status icons; replace noisy priority labels.

## Refactors / UX Consistency
- Simplify chat attachment model and remove project file picker path.
- Keep composer focused on `@` mention file flow.
- Use direct `Attach files` action in VS Code instead of attachment dropdown path.
- Unify issue/PR picker behavior between desktop and mobile overlays.
2026-03-04 01:41:01 +02:00

118 lines
4.2 KiB
TypeScript

import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import type { McpStatus } from '@opencode-ai/sdk/v2';
import { opencodeClient } from '@/lib/opencode/client';
import { useDirectoryStore } from '@/stores/useDirectoryStore';
export type McpStatusMap = Record<string, McpStatus>;
const EMPTY_STATUS: McpStatusMap = {};
type McpHealth = {
connected: number;
total: number;
hasFailed: boolean;
hasAuthRequired: boolean;
};
const normalizeDirectory = (directory: string | null | undefined): string | null => {
if (typeof directory !== 'string') return null;
const trimmed = directory.trim();
if (!trimmed) return null;
const normalized = trimmed.replace(/\\/g, '/');
return normalized.length > 1 ? normalized.replace(/\/+$/, '') : normalized;
};
const toKey = (directory: string | null | undefined): string => normalizeDirectory(directory) ?? '__global__';
const getMcpApiClient = (directory: string | null | undefined) => {
const normalized = normalizeDirectory(directory);
if (!normalized) {
return opencodeClient.getApiClient();
}
return opencodeClient.getScopedApiClient(normalized);
};
export const computeMcpHealth = (status: McpStatusMap | null | undefined): McpHealth => {
const entries = Object.entries(status ?? {});
const connected = entries.filter(([, s]) => s?.status === 'connected').length;
const total = entries.length;
const hasFailed = entries.some(([, s]) => s?.status === 'failed');
const hasAuthRequired = entries.some(([, s]) => s?.status === 'needs_auth' || s?.status === 'needs_client_registration');
return { connected, total, hasFailed, hasAuthRequired };
};
type RefreshOptions = {
directory?: string | null;
silent?: boolean;
};
interface McpStore {
byDirectory: Record<string, McpStatusMap>;
loadingKeys: Record<string, boolean>;
lastErrorKeys: Record<string, string | null>;
getStatusForDirectory: (directory?: string | null) => McpStatusMap;
refresh: (options?: RefreshOptions) => Promise<void>;
connect: (name: string, directory?: string | null) => Promise<void>;
disconnect: (name: string, directory?: string | null) => Promise<void>;
}
export const useMcpStore = create<McpStore>()(
devtools((set, get) => ({
byDirectory: {},
loadingKeys: {},
lastErrorKeys: {},
getStatusForDirectory: (directory) => {
const key = toKey(directory ?? useDirectoryStore.getState().currentDirectory);
return get().byDirectory[key] ?? EMPTY_STATUS;
},
refresh: async (options) => {
const directory = normalizeDirectory(options?.directory ?? useDirectoryStore.getState().currentDirectory);
const key = toKey(directory);
if (!options?.silent) {
set((state) => ({
loadingKeys: { ...state.loadingKeys, [key]: true },
lastErrorKeys: { ...state.lastErrorKeys, [key]: null },
}));
}
try {
const api = getMcpApiClient(directory);
const result = await api.mcp.status();
const data = (result.data ?? {}) as McpStatusMap;
set((state) => ({
byDirectory: { ...state.byDirectory, [key]: data },
loadingKeys: { ...state.loadingKeys, [key]: false },
lastErrorKeys: { ...state.lastErrorKeys, [key]: null },
}));
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to load MCP status';
set((state) => ({
loadingKeys: { ...state.loadingKeys, [key]: false },
lastErrorKeys: { ...state.lastErrorKeys, [key]: message },
}));
}
},
connect: async (name, directory) => {
const normalized = normalizeDirectory(directory ?? useDirectoryStore.getState().currentDirectory);
const api = getMcpApiClient(normalized);
await api.mcp.connect({ name }, { throwOnError: true });
await get().refresh({ directory: normalized, silent: true });
},
disconnect: async (name, directory) => {
const normalized = normalizeDirectory(directory ?? useDirectoryStore.getState().currentDirectory);
const api = getMcpApiClient(normalized);
await api.mcp.disconnect({ name }, { throwOnError: true });
await get().refresh({ directory: normalized, silent: true });
},
}))
);