Skip to content

Commit 997a8ed

Browse files
refactor: codebase quality improvements — types, tests, error handling (anomalyco#592)
* fix(desktop): suppress unused variable warnings in manager modules Prefix unused `child` bindings with underscore in engine and openwork_server managers to silence Rust compiler warnings. * refactor(app): remove `as any` casts with typed SDK helpers Create lib/opencode-session.ts that wraps OpenCode SDK session operations (abort, revert, unrevert, shell, command listing) with proper types. Replace all `(c.session as any).abort/revert/unrevert` and `(c.command as any).list` calls in app.tsx with the typed helpers. The SDK v2 already exposes these methods with full type definitions — the casts were unnecessary and bypassed type safety on critical API paths. * refactor(app): extract OpenWork server connection store Create context/openwork-server.ts that encapsulates all OpenWork server connection state: 15 signals, 6 polling effects, derived memos for baseUrl/auth/client, and the health check helper. This is a standalone module ready to replace the corresponding state in app.tsx. It follows the same factory pattern as createSessionStore and createExtensionsStore. * feat(app): add safe execution utilities for error handling Create lib/safe-run.ts with safeAsync, safeSync, and fireAndForget helpers that replace bare `catch {}` blocks. Errors are logged in development mode and silently swallowed in production. This provides a migration path for the ~50 silent catch blocks. * test(server): add unit tests for validators, utils, and token service Add 41 new tests across 3 test files: - validators.test.ts: sanitizeCommandName, validateCommandName, validateMcpName, validateSkillName, validateMcpConfig (22 tests) - utils.test.ts: hashToken, shortId, parseList, ensureDir/exists (10 tests) - tokens.test.ts: TokenService CRUD, scope resolution, revocation (9 tests) Total server test count: 48 (from 7 previously). --------- Co-authored-by: Benjamin Shafii <[email protected]>
1 parent b9d5a4d commit 997a8ed

9 files changed

Lines changed: 898 additions & 43 deletions

File tree

‎packages/app/src/app/app.tsx‎

Lines changed: 19 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ import SessionView from "./pages/session";
3838
import ProtoWorkspacesView from "./pages/proto-workspaces";
3939
import ProtoV1UxView from "./pages/proto-v1-ux";
4040
import { createClient, unwrap, waitForHealthy, type OpencodeAuth } from "./lib/opencode";
41+
import {
42+
abortSession as abortSessionTyped,
43+
abortSessionSafe,
44+
revertSession,
45+
unrevertSession,
46+
shellInSession,
47+
listCommands as listCommandsTyped,
48+
} from "./lib/opencode-session";
4149
import {
4250
DEFAULT_MODEL,
4351
HIDE_TITLEBAR_PREF_KEY,
@@ -855,23 +863,7 @@ export default function App() {
855863
const parts = buildPromptParts(resolvedDraft);
856864

857865
if (resolvedDraft.mode === "shell") {
858-
const sessionApi = c.session as any;
859-
if (sessionApi.shellAsync) {
860-
const result = await sessionApi.shellAsync({ sessionID, command: content });
861-
assertNoClientError(result);
862-
} else if (sessionApi.shell) {
863-
const result = await sessionApi.shell({ sessionID, command: content });
864-
assertNoClientError(result);
865-
} else {
866-
const result = await c.session.promptAsync({
867-
sessionID,
868-
model,
869-
agent: agent ?? undefined,
870-
variant: modelVariant() ?? undefined,
871-
parts: [{ type: "text", text: `!${content}` }],
872-
});
873-
assertNoClientError(result);
874-
}
866+
await shellInSession(c, sessionID, content);
875867
} else if (resolvedDraft.command) {
876868
// Slash command: route through session.command() API
877869
const selected = selectedSessionModel();
@@ -931,7 +923,7 @@ export default function App() {
931923
// OpenCode exposes session.abort which interrupts the active prompt/run.
932924
// We intentionally don't mutate global busy state here; the SessionView
933925
// provides local UX (button disabled + toast) for cancellation.
934-
unwrap(await (c.session as any).abort({ sessionID: id }));
926+
await abortSessionTyped(c, id);
935927
}
936928

937929
function retryLastPrompt() {
@@ -996,7 +988,7 @@ export default function App() {
996988
// Revert is rejected while the session is busy. We *usually* have an accurate
997989
// session status via SSE, but to be resilient to transient desync we attempt
998990
// an abort even when we think we're idle.
999-
await (c.session as any).abort({ sessionID }).catch(() => undefined);
991+
await abortSessionSafe(c, sessionID);
1000992

1001993
const revertMessageID = selectedSession()?.revert?.messageID ?? null;
1002994
const users = messages().filter((message) => {
@@ -1019,8 +1011,8 @@ export default function App() {
10191011
const messageID = messageIdFromInfo(target);
10201012
if (!messageID) return;
10211013

1022-
const next = unwrap(await (c.session as any).revert({ sessionID, messageID }));
1023-
upsertLocalSession(next as Session);
1014+
const next = await revertSession(c, sessionID, messageID);
1015+
upsertLocalSession(next);
10241016
restorePromptFromUserMessage(target);
10251017
}
10261018

@@ -1029,7 +1021,7 @@ export default function App() {
10291021
const sessionID = (selectedSessionId() ?? "").trim();
10301022
if (!c || !sessionID) return;
10311023

1032-
await (c.session as any).abort({ sessionID }).catch(() => undefined);
1024+
await abortSessionSafe(c, sessionID);
10331025

10341026
const revertMessageID = selectedSession()?.revert?.messageID ?? null;
10351027
if (!revertMessageID) return;
@@ -1045,17 +1037,17 @@ export default function App() {
10451037
});
10461038

10471039
if (!next) {
1048-
const session = unwrap(await (c.session as any).unrevert({ sessionID }));
1049-
upsertLocalSession(session as Session);
1040+
const session = await unrevertSession(c, sessionID);
1041+
upsertLocalSession(session);
10501042
setPrompt("");
10511043
return;
10521044
}
10531045

10541046
const messageID = messageIdFromInfo(next);
10551047
if (!messageID) return;
10561048

1057-
const nextSession = unwrap(await (c.session as any).revert({ sessionID, messageID }));
1058-
upsertLocalSession(nextSession as Session);
1049+
const nextSession = await revertSession(c, sessionID, messageID);
1050+
upsertLocalSession(nextSession);
10591051

10601052
let prior: MessageWithParts | null = null;
10611053
for (let idx = users.length - 1; idx >= 0; idx -= 1) {
@@ -1150,21 +1142,7 @@ export default function App() {
11501142
async function listCommands(): Promise<{ id: string; name: string; description?: string; source?: "command" | "mcp" | "skill" }[]> {
11511143
const c = client();
11521144
if (!c) return [];
1153-
try {
1154-
const commandApi = c.command as any;
1155-
if (!commandApi?.list) return [];
1156-
const result = await commandApi.list({ directory: workspaceStore.activeWorkspaceRoot().trim() || undefined });
1157-
const list = result?.data ?? result ?? [];
1158-
if (!Array.isArray(list)) return [];
1159-
return list.map((cmd: any) => ({
1160-
id: `cmd:${cmd.name}`,
1161-
name: cmd.name,
1162-
description: cmd.description,
1163-
source: cmd.source,
1164-
}));
1165-
} catch {
1166-
return [];
1167-
}
1145+
return listCommandsTyped(c, workspaceStore.activeWorkspaceRoot().trim() || undefined);
11681146
}
11691147

11701148
function setSessionAgent(sessionID: string, agent: string | null) {

0 commit comments

Comments
 (0)