fix(extension): harden review-flagged paths

A pass over the extension surface to address review feedback:

Safety / hardening:

- `graphPanel.ts`: validate `m.path` from the webview before opening
  files. Reject absolute paths and any path that escapes the workspace
  root (`..`, `/foo`, `C:/...`). Validate the line number is a positive
  integer before constructing a `Range`. Surface failures via the output
  channel rather than letting the rejection bubble up.
- `mcpProvider.ts`: defensively check that
  `vscode.lm.registerMcpServerDefinitionProvider` exists before calling
  it. The `engines.vscode: ^1.99.0` field already enforces this on
  install, but some VS Code-derived editors mis-report their engine
  version. The extension now degrades gracefully (sidebar, commands,
  status bar still work) instead of failing activation.
- `commands.ts` and `graphPanel.ts`: wrap `workbench.action.chat.open`
  in try/catch. Not every VS Code-compatible editor exposes that
  command; falling back to the output channel avoids unhandled
  rejections after the user clicked "Open chat".
- `extension.ts`: persist the first-run walkthrough flag only after the
  walkthrough command resolves successfully, so a transient failure
  doesn't silently skip the onboarding forever.

CI gates:

- `extension-ci.yml` and `extension-release.yml`: run `npm test` between
  typecheck and build, so manifest-level smoke regressions can't slip
  through to either the PR artefact or the marketplace publishes.

Settings copy:

- `socraticode.env` description: explicitly call out that the setting
  is for non-secret config only. Recommend OS environment variables /
  local `.env` files for API keys, since workspace settings can sync
  via Settings Sync and end up in committed `.vscode/settings.json`.

Quality of life:

- `sidebar.ts` `formatRelative`: clamp the computed seconds to zero so
  a file mtime slightly ahead of the local clock doesn't render
  "-5s ago".
- `walkthroughs/first-index.md`: corrected the embedding model name
  (`nomic-embed-text`, not `mxbai-embed-large`) to match the engine
  default in `src/constants.ts`.

Lint / docs:

- `extension/README.md`: hyphenate "Eclipse Theia-based editors".
- `DEVELOPER.md`: add `text` language hint to the directory-tree code
  fence (markdownlint MD040). Updated the inline comment for
  `settings.ts` to reflect its current shape.
- `README.md`: reflow the "extension vs plugin" callout into a single
  blockquote (markdownlint MD028).

Lint, typecheck, manifest tests and build all clean. Engine unit tests
unaffected (706/706 still pass).
This commit is contained in:
Giancarlo Erra
2026-05-04 00:41:51 +01:00
parent a27b8ceb67
commit 562a946053
12 changed files with 123 additions and 37 deletions
+4 -1
View File
@@ -17,7 +17,7 @@ permissions:
jobs:
lint-build-package:
name: Lint, typecheck, build, package
name: Lint, typecheck, test, build, package
runs-on: ubuntu-latest
defaults:
run:
@@ -40,6 +40,9 @@ jobs:
- name: Typecheck
run: npm run typecheck
- name: Test
run: npm test
- name: Build
run: npm run compile
+3
View File
@@ -36,6 +36,9 @@ jobs:
- name: Typecheck
run: npm run typecheck
- name: Test
run: npm test
- name: Build
run: npm run compile
+2 -2
View File
@@ -1417,7 +1417,7 @@ Source: [`extension/`](./extension)
### Layout
```
```text
extension/
├── package.json # extension manifest
├── tsconfig.json # TS strict, ES2022, Node 18 target
@@ -1434,7 +1434,7 @@ extension/
├── graphPanel.ts # webview panel for the interactive graph
├── statusBar.ts # status-bar item
├── commands.ts # command palette commands
├── settings.ts # typed config + SecretStorage
├── settings.ts # typed config accessors
├── output.ts # log/output channel
└── __tests__/ # node:test smoke tests for the manifest
```
+2 -2
View File
@@ -177,11 +177,11 @@ SocratiCode is available as a native plugin on multiple AI coding platforms. Plu
| OpenAI Codex | No public plugin directory yet — use the [MCP config](#quick-start) or see **Codex local install** below |
> **Extension vs plugin (what to install in VS Code / Cursor):**
>
> - The **extension** (Marketplace / Open VSX listing) is a regular VS Code-style extension. It auto-registers the MCP server in Copilot agent mode, Cline, Continue, Roo Code, plus adds a sidebar, status-bar item, interactive graph webview, walkthrough and palette commands. Best for most users.
> - The **plugins** (`/add-plugin` for Cursor, `Chat: Install Plugin From Source` for VS Code Copilot) bundle the MCP server **plus skills + agent instructions** that teach the AI to use SocratiCode tools effectively. Best when you want the agent to be opinionated about using SocratiCode.
> - You can install both. The extension only registers the MCP server once, so they don't conflict.
> **VS Code Copilot**: The chat plugins feature is in preview. Enable it with `chat.plugins.enabled: true` in your VS Code settings.
> - **VS Code Copilot note**: the chat plugins feature is in preview. Enable it with `chat.plugins.enabled: true` in your VS Code settings.
> **Codex local plugin install**: Clone the repo and register it in your personal plugin marketplace:
> ```bash
+1 -1
View File
@@ -126,7 +126,7 @@ VS Code 1.99+ extension API:
- VSCodium
- Gitpod
- code-server
- Eclipse Theia based editors
- Eclipse Theia-based editors
- Google Antigravity
- Particle Workbench
+1 -1
View File
@@ -153,7 +153,7 @@
"additionalProperties": {
"type": "string"
},
"description": "Environment variables forwarded to the engine. Use this to point at an external Qdrant (`QDRANT_MODE=external`, `QDRANT_URL`, `QDRANT_API_KEY`), select an embedding provider (`EMBEDDING_PROVIDER`, `OPENAI_API_KEY`, etc.), or any other engine setting documented in the engine README.",
"description": "Non-secret environment variables forwarded to the engine. Use this for non-sensitive engine config like external Qdrant URL (`QDRANT_MODE=external`, `QDRANT_URL`), embedding provider selection (`EMBEDDING_PROVIDER`), project IDs, branch-aware indexing, and so on. AVOID storing API keys or tokens here: workspace settings can be synced via VS Code Settings Sync and may end up in committed `.vscode/settings.json` files. For secrets, prefer OS environment variables, a local `.env` file outside settings, or a system keychain.",
"scope": "window"
},
"socraticode.statusBar": {
+28 -7
View File
@@ -38,12 +38,21 @@ export function registerCommands(
vscode.commands.registerCommand("socraticode.openWalkthrough", async () => {
// Use context.extension.id so this keeps working if the publisher
// namespace changes. Same pattern as the first-run trigger in
// extension.ts.
await vscode.commands.executeCommand(
"workbench.action.openWalkthrough",
`${context.extension.id}#socraticode.gettingStarted`,
false,
);
// extension.ts. Wrapped in try/catch because some VS Code forks
// do not expose `workbench.action.openWalkthrough` and the
// command would otherwise reject silently.
try {
await vscode.commands.executeCommand(
"workbench.action.openWalkthrough",
`${context.extension.id}#socraticode.gettingStarted`,
false,
);
} catch (err) {
log(`Failed to open walkthrough: ${(err as Error).message}`);
vscode.window.showWarningMessage(
"SocratiCode: this editor does not appear to support walkthroughs. See the marketplace listing for getting-started guidance.",
);
}
}),
);
@@ -71,7 +80,19 @@ async function indexCurrentWorkspaceCommand(): Promise<void> {
"Show output",
);
if (action === "Open chat") {
await vscode.commands.executeCommand("workbench.action.chat.open");
// `workbench.action.chat.open` is not guaranteed across every
// VS Code-compatible editor (some Theia-based forks omit it). Fall
// back to the output channel if the host doesn't expose the chat
// command, so the user always gets useful feedback.
try {
await vscode.commands.executeCommand("workbench.action.chat.open");
} catch (err) {
log(`Open chat failed: ${(err as Error).message}`);
output().show(true);
vscode.window.showInformationMessage(
"SocratiCode: this editor does not expose a chat command. Opened the SocratiCode output channel instead.",
);
}
} else if (action === "Show output") {
output().show(true);
}
+15 -7
View File
@@ -31,15 +31,23 @@ export async function activate(context: vscode.ExtensionContext): Promise<void>
registerCommands(context, sidebar);
// Show the walkthrough on first install. We use globalState rather than
// a setting so it's per-machine, not per-workspace.
// a setting so it's per-machine, not per-workspace. Persist the
// "shown" flag only AFTER the command resolves, so if the host fails
// to open the walkthrough (some VS Code forks don't expose
// `workbench.action.openWalkthrough`), the user is offered it again
// next session instead of silently skipping it forever.
const shown = context.globalState.get<boolean>(FIRST_RUN_KEY, false);
if (!shown) {
void context.globalState.update(FIRST_RUN_KEY, true);
void vscode.commands.executeCommand(
"workbench.action.openWalkthrough",
`${context.extension.id}#socraticode.gettingStarted`,
false,
);
try {
await vscode.commands.executeCommand(
"workbench.action.openWalkthrough",
`${context.extension.id}#socraticode.gettingStarted`,
false,
);
await context.globalState.update(FIRST_RUN_KEY, true);
} catch (err) {
log(`Failed to open first-run walkthrough: ${(err as Error).message}`);
}
}
log("SocratiCode extension activated");
+43 -11
View File
@@ -119,7 +119,17 @@ async function offerToGenerate(): Promise<void> {
await vscode.env.clipboard.writeText(prompt);
vscode.window.showInformationMessage("SocratiCode: prompt copied.");
} else if (action === "Open chat") {
await vscode.commands.executeCommand("workbench.action.chat.open");
// Not all VS Code-compatible editors expose `workbench.action.chat.open`
// (some Theia-based forks omit it). Fall back to a friendlier message
// rather than letting the rejection bubble up unhandled.
try {
await vscode.commands.executeCommand("workbench.action.chat.open");
} catch (err) {
log(`Open chat failed: ${(err as Error).message}`);
vscode.window.showInformationMessage(
"SocratiCode: this editor does not expose a chat command. Open your AI assistant manually and paste the copied prompt.",
);
}
}
}
@@ -178,15 +188,37 @@ function wrapHtml(html: string, webview: vscode.Webview): string {
function handleWebviewMessage(msg: unknown): void {
if (typeof msg !== "object" || msg === null) return;
const m = msg as { type?: string; path?: string; line?: number };
if (m.type === "openFile" && typeof m.path === "string") {
const ws = vscode.workspace.workspaceFolders?.[0];
if (!ws) {
vscode.window.showWarningMessage("SocratiCode: open a workspace to navigate from the graph.");
return;
}
const uri = vscode.Uri.joinPath(ws.uri, m.path);
const range =
typeof m.line === "number" ? new vscode.Range(m.line - 1, 0, m.line - 1, 0) : undefined;
vscode.window.showTextDocument(uri, range ? { selection: range } : {});
if (m.type !== "openFile" || typeof m.path !== "string") return;
const ws = vscode.workspace.workspaceFolders?.[0];
if (!ws) {
vscode.window.showWarningMessage("SocratiCode: open a workspace to navigate from the graph.");
return;
}
// The webview HTML is generated by us, but the boundary is still
// untrusted: anything that crosses `postMessage` could be tampered
// with. Reject absolute paths and any path that escapes the workspace
// root (`..`). Normalise via posix paths so the same validation works
// on Windows, macOS, and Linux.
const normalised = path.posix.normalize(m.path.replace(/\\/g, "/"));
const isAbsolute = normalised.startsWith("/") || /^[A-Za-z]:\//.test(normalised);
const escapesRoot =
normalised === ".." || normalised.startsWith("../") || normalised.includes("/../");
if (isAbsolute || escapesRoot || normalised === "." || normalised === "") {
log(`Graph panel: rejecting suspicious path from webview: ${m.path}`);
vscode.window.showWarningMessage("SocratiCode: invalid file path from graph.");
return;
}
const uri = vscode.Uri.joinPath(ws.uri, ...normalised.split("/"));
const lineIndex =
typeof m.line === "number" && Number.isInteger(m.line) && m.line > 0 ? m.line - 1 : undefined;
const selection =
lineIndex !== undefined ? new vscode.Range(lineIndex, 0, lineIndex, 0) : undefined;
void vscode.window
.showTextDocument(uri, selection ? { selection } : {})
.then(undefined, (err) =>
log(`Graph panel: failed to open ${normalised}: ${(err as Error).message}`),
);
}
+18 -1
View File
@@ -43,8 +43,25 @@ export class SocratiCodeMcpProvider implements vscode.McpServerDefinitionProvide
}
}
export function registerMcpProvider(context: vscode.ExtensionContext): SocratiCodeMcpProvider {
export function registerMcpProvider(
context: vscode.ExtensionContext,
): SocratiCodeMcpProvider | undefined {
const provider = new SocratiCodeMcpProvider();
// The `engines.vscode: ^1.99.0` field in package.json prevents
// installation on hosts without the MCP API, but some VS Code-derived
// editors lie about their reported version. Defensively check that
// the API surface exists before calling it, so activation degrades
// gracefully (sidebar / commands / status bar still work) instead of
// throwing a hard error that disables the entire extension.
if (typeof vscode.lm?.registerMcpServerDefinitionProvider !== "function") {
log(
"vscode.lm.registerMcpServerDefinitionProvider is unavailable in this host; " +
"skipping MCP server registration. Sidebar, commands and status bar still work.",
);
return undefined;
}
const disposable = vscode.lm.registerMcpServerDefinitionProvider("socraticode.mcp", provider);
context.subscriptions.push(disposable);
log("Registered SocratiCode MCP server provider");
+3 -1
View File
@@ -109,7 +109,9 @@ export function registerSidebar(context: vscode.ExtensionContext): ProjectsTreeP
}
function formatRelative(date: Date): string {
const seconds = Math.round((Date.now() - date.getTime()) / 1000);
// Clamp to zero so a file mtime slightly ahead of the local clock
// (NTP correction, container clock skew) doesn't render "-5s ago".
const seconds = Math.max(0, Math.round((Date.now() - date.getTime()) / 1000));
if (seconds < 60) return `${seconds}s ago`;
const minutes = Math.round(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
+3 -3
View File
@@ -7,9 +7,9 @@ Index the workspace:
Index current workspace** from the command palette.
The first index downloads the embedding model if it's not already cached
(roughly 700 MB for the default `mxbai-embed-large`), then walks the
workspace. Subsequent updates are incremental and triggered automatically
when files change.
(the default is `nomic-embed-text` via the local Docker Ollama, a few
hundred megabytes), then walks the workspace. Subsequent updates are
incremental and triggered automatically when files change.
## What gets indexed