warning: in the working copy of 'CHANGELOG.md', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/extension.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/providers/SidebarProvider.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/services/ApiClient.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/services/AuthService.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/services/EventDispatcher.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/services/GitInfo.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/services/OpencodeCli.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/services/PermissionService.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/services/SseStream.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/services/readPatterns.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/extension/types.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/App.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/components/BottomInput.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/components/ChatBubble.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/components/DiffChanges.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/components/Markdown.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/components/ProviderPopup.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/components/SessionListPopup.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/components/SlashCommandPopup.tsx', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/hooks/useChatState.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/hooks/useMessageHandler.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/webview/vscode-api.ts', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'tsconfig.extension.json', LF will be replaced by CRLF the next time Git touches it
diff --git a/.gitignore b/.gitignore
index aaa57b5..f3739d3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,8 @@ out/
 AGENTS.md
 SKILL.md
 AGENTS.md
+/.agents
+/_bmad-output
+/_bmad
+# Added by code-review-graph
+.code-review-graph/
diff --git a/AGENTS.md b/AGENTS.md
index e8e2540..a9e38a3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -78,3 +78,42 @@ Fragments OK. Short synonyms. Code unchanged.
 Pattern: [thing] [action] [reason]. [next step].
 ACTIVE EVERY RESPONSE. No revert after many turns. No filler drift.
 Code/commits/PRs: normal. Off: "stop caveman" / "normal mode".
+
+<!-- code-review-graph MCP tools -->
+## MCP Tools: code-review-graph
+
+**IMPORTANT: This project has a knowledge graph. ALWAYS use the
+code-review-graph MCP tools BEFORE using Grep/Glob/Read to explore
+the codebase.** The graph is faster, cheaper (fewer tokens), and gives
+you structural context (callers, dependents, test coverage) that file
+scanning cannot.
+
+### When to use graph tools FIRST
+
+- **Exploring code**: `semantic_search_nodes` or `query_graph` instead of Grep
+- **Understanding impact**: `get_impact_radius` instead of manually tracing imports
+- **Code review**: `detect_changes` + `get_review_context` instead of reading entire files
+- **Finding relationships**: `query_graph` with callers_of/callees_of/imports_of/tests_for
+- **Architecture questions**: `get_architecture_overview` + `list_communities`
+
+Fall back to Grep/Glob/Read **only** when the graph doesn't cover what you need.
+
+### Key Tools
+
+| Tool | Use when |
+|------|----------|
+| `detect_changes` | Reviewing code changes — gives risk-scored analysis |
+| `get_review_context` | Need source snippets for review — token-efficient |
+| `get_impact_radius` | Understanding blast radius of a change |
+| `get_affected_flows` | Finding which execution paths are impacted |
+| `query_graph` | Tracing callers, callees, imports, tests, dependencies |
+| `semantic_search_nodes` | Finding functions/classes by name or keyword |
+| `get_architecture_overview` | Understanding high-level codebase structure |
+| `refactor_tool` | Planning renames, finding dead code |
+
+### Workflow
+
+1. The graph auto-updates on file changes (via hooks).
+2. Use `detect_changes` for code review.
+3. Use `get_affected_flows` to understand impact.
+4. Use `query_graph` pattern="tests_for" to check coverage.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 746fb68..45a632c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,60 @@
 
 All notable changes to this project will be documented in this file.
 
+## [0.1.4] - 2026-05-07
+
+### Added
+- Unit tests (57 tests across 7 test files)
+- Integration tests for extension↔webview message protocol
+- Payload validation in SidebarProvider
+- Crypto-secure random IDs (`crypto.getRandomValues()`)
+
+### Changed
+- EventDispatcher: 200+ line dispatch() split into 8 handler methods
+- SidebarProvider: _handleSendMessage refactored into 5 methods (context, streaming, diffs)
+- normalizeDiff deduplicated to utils/diffUtils.ts
+- READ_TOOLS Set unified (removed duplicate array)
+- sendPrompt: positional params → options object
+- AppContext provider for centralized state
+- 30+ console.log statements removed for production
+- SSE parser now supports event:, id:, retry:, multi-line data
+- SseStream reconnect with exponential backoff (3 retries)
+- readPatterns: regex caching + case-insensitive matching
+- opencode binary path validation (restricted to allowed dirs)
+
+### Fixed
+- sessionPartDeltas unused Map removed (memory leak)
+- _processPrompt: missing reasoning/diff callbacks added
+- PermissionService: cache hit Promise never resolving
+- _loadSkills: dead code (unused readDirectory call) removed
+- GitInfo duplicate interface removed
+- providerPopup apiKeyInputs ref→state (re-render trigger)
+- streamEnd race condition (streamEndedRef)
+- receiveChunk debounce race condition
+- stale closure in useMessageHandler
+- dispose(): _view cleanup added
+- handleDeleteOld(0): now deletes all sessions
+- SlashCommandPopup: global keydown conditional
+- OPENCODE_BIN_PATH: only allowed directories accepted
+- CSP connect-src: null port fallback removed
+- CSP base-uri: added
+- hardcoded Windows paths removed (C:\opencode, C:\Program Files)
+- password prefix removed (pure random)
+- API error body log sanitized
+- SSH/AWS/Kube/Azure credential patterns added
+- Windows SIGTERM (was SIGKILL)
+- DOMPurify URI safelist tightened
+- git diff command injection prevention
+- payload type index signatures removed
+- 7 test files added
+
+### Removed
+- Unused sessionPartDeltas Map
+- Duplicate READ_TOOLS array
+- Unnecessary console.log statements
+- Hardcoded Windows binary paths
+- Predictable password prefix (oc-vsc-)
+
 ## [0.1.3] - 2026-05-07
 
 ### Added
diff --git a/package.json b/package.json
index 70147b5..c5d78cc 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
   "name": "opencode-sidebar-chat",
   "displayName": "Opencode Sidebar Chat",
   "description": "Professional AI coding assistant with multi-provider support, diff review, and brutalist design.",
-  "version": "0.1.3",
+  "version": "0.1.4",
   "publisher": "NovadaysTech",
   "author": {
     "name": "Emin"
diff --git a/src/extension/extension.ts b/src/extension/extension.ts
index 6e0a30a..ec9f415 100644
--- a/src/extension/extension.ts
+++ b/src/extension/extension.ts
@@ -1,15 +1,16 @@
 import * as vscode from 'vscode';
 import { SidebarProvider } from './providers/SidebarProvider';
 
-let sidebarProvider: SidebarProvider | undefined;
+let _sidebarProvider: SidebarProvider | undefined;
 
 export function activate(context: vscode.ExtensionContext) {
-  sidebarProvider = new SidebarProvider(context.extensionUri, context);
+  _sidebarProvider = new SidebarProvider(context.extensionUri, context);
   context.subscriptions.push(
-    vscode.window.registerWebviewViewProvider(SidebarProvider.viewType, sidebarProvider),
+    vscode.window.registerWebviewViewProvider(SidebarProvider.viewType, _sidebarProvider),
   );
 }
 
 export function deactivate() {
-  sidebarProvider?.dispose();
+  _sidebarProvider?.dispose();
+  _sidebarProvider = undefined;
 }
diff --git a/src/extension/providers/SidebarProvider.ts b/src/extension/providers/SidebarProvider.ts
index 3e3d3b0..27ccb38 100644
--- a/src/extension/providers/SidebarProvider.ts
+++ b/src/extension/providers/SidebarProvider.ts
@@ -66,10 +66,18 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
     webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);
 
     webviewView.webview.onDidReceiveMessage(async (data) => {
-      if (!data || typeof data !== 'object' || !WEBVIEW_TO_EXTENSION_TYPES.includes(data.type as any)) {
-        console.warn('[opencode] Ignored message with unknown type:', data?.type);
+      const msgType = data?.type;
+      if (!data || typeof data !== 'object' || typeof msgType !== 'string' || !(WEBVIEW_TO_EXTENSION_TYPES as readonly string[]).includes(msgType)) {
+        console.warn('[opencode] Ignored message with unknown type:', msgType);
         return;
       }
+
+      const payload = data.payload;
+      if (!this.validatePayload(msgType, payload)) {
+        console.warn('[opencode] Invalid payload for:', msgType);
+        return;
+      }
+
       switch (data.type) {
         case 'searchFiles':
           await this._handleSearchFiles(data.payload);
@@ -130,6 +138,8 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
           await this._handleDeleteSession(data.payload);
           break;
         case 'switchAgent':
+          // Agent switch handled client-side in webview (mode change)
+          // Could extend to track agent usage or persist preference
           break;
       }
     });
@@ -264,109 +274,136 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
     const { prompt, model, mode, context } = payload;
     const agent = MODE_TO_AGENT[mode] || 'build';
 
+    const { userContent, extraParts } = await this._processContext(prompt, context);
+
+    this.postMessage({ type: 'receiveMessage', payload: { role: 'user', content: userContent } });
+
+    try {
+      await this._ensureOpencodeRunning();
+      const sessionId = await this._sessions.ensureSession(prompt);
+      await this._handleStreaming(sessionId, prompt, model, agent, extraParts);
+    } catch (err: any) {
+      const msg = err?.message || err?.toString?.() || 'Unknown error';
+      this.postMessage({ type: 'error', payload: { message: msg } });
+      this.postMessage({ type: 'streamEnd', payload: { content: '' } });
+    }
+  }
+
+  private async _processContext(prompt: string, context: any): Promise<{
+    userContent: string;
+    extraParts: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;
+  }> {
     let userContent = prompt;
     const extraParts: Array<{ type: string; text?: string; data?: string; mimeType?: string }> = [];
 
-    if (context && Array.isArray(context)) {
-      for (const item of context) {
-        if (item.type === 'file') {
-          const workspaceFolders = vscode.workspace.workspaceFolders;
-          if (workspaceFolders) {
-            const filePath = item.path;
-            const { allowed, deniedPattern } = this._permissions.isReadAllowed(filePath);
-            if (!allowed && deniedPattern) {
-              const reqId = `${filePath}_${Date.now()}`;
-              this.postMessage({
-                type: 'readFilePrompt',
-                payload: { filePath, reason: `Matches deny pattern: ${deniedPattern}`, requestId: reqId },
-              });
-              const userAllowed = await this._permissions.waitForReadPermission(filePath);
-              if (!userAllowed) {
-                userContent += `\n\n[Skipped: ${filePath} — read denied by pattern]`;
-                this.postMessage({
-                  type: 'toolEvent',
-                  payload: { id: `file_read_${filePath}`, type: 'file_read', name: 'read', status: 'failed', content: `Read denied: ${filePath}`, meta: { path: filePath, error: 'Permission denied' } },
-                });
-                continue;
-              }
-            }
-            const fileUri = vscode.Uri.joinPath(workspaceFolders[0].uri, filePath);
-            try {
-              const content = await vscode.workspace.fs.readFile(fileUri);
-              const text = new TextDecoder().decode(content);
-              extraParts.push({ type: 'text', text: `File: ${filePath}\n\n${text}\n` });
-              this.postMessage({
-                type: 'toolEvent',
-                payload: { id: `file_read_${filePath}`, type: 'file_read', name: 'read', status: 'completed', content: `Read: ${filePath}`, meta: { path: filePath } },
-              });
-            } catch (e: any) {
-              userContent += `\n\n[File not found: ${filePath}]`;
-            }
-          }
+    if (!context || !Array.isArray(context)) {
+      return { userContent, extraParts };
+    }
+
+    const workspaceFolders = vscode.workspace.workspaceFolders;
+    if (!workspaceFolders) {
+      return { userContent, extraParts };
+    }
+
+    for (const item of context) {
+      if (item.type !== 'file') continue;
+
+      const filePath = item.path;
+      const { allowed, deniedPattern } = this._permissions.isReadAllowed(filePath);
+      if (!allowed && deniedPattern) {
+        const reqId = `${filePath}_${Date.now()}`;
+        this.postMessage({
+          type: 'readFilePrompt',
+          payload: { filePath, reason: `Matches deny pattern: ${deniedPattern}`, requestId: reqId },
+        });
+        const userAllowed = await this._permissions.waitForReadPermission(filePath);
+        if (!userAllowed) {
+          userContent += `\n\n[Skipped: ${filePath} — read denied by pattern]`;
+          this.postMessage({
+            type: 'toolEvent',
+            payload: { id: `file_read_${filePath}`, type: 'file_read', name: 'read', status: 'failed', content: `Read denied: ${filePath}`, meta: { path: filePath, error: 'Permission denied' } },
+          });
+          continue;
         }
       }
+
+      const fileUri = vscode.Uri.joinPath(workspaceFolders[0].uri, filePath);
+      try {
+        const content = await vscode.workspace.fs.readFile(fileUri);
+        const text = new TextDecoder().decode(content);
+        extraParts.push({ type: 'text', text: `File: ${filePath}\n\n${text}\n` });
+        this.postMessage({
+          type: 'toolEvent',
+          payload: { id: `file_read_${filePath}`, type: 'file_read', name: 'read', status: 'completed', content: `Read: ${filePath}`, meta: { path: filePath } },
+        });
+      } catch (e: any) {
+        userContent += `\n\n[File not found: ${filePath}]`;
+      }
     }
 
-    this.postMessage({ type: 'receiveMessage', payload: { role: 'user', content: userContent } });
+    return { userContent, extraParts };
+  }
 
-    try {
-      if (!this._opencode.isRunning) {
-        await this._opencode.start();
-      }
+  private async _ensureOpencodeRunning(): Promise<void> {
+    if (!this._opencode.isRunning) {
+      await this._opencode.start();
+    }
+  }
 
-      const sessionId = await this._sessions.ensureSession(prompt);
+  private async _handleStreaming(
+    sessionId: string,
+    prompt: string,
+    model: string,
+    agent: string,
+    extraParts?: Array<{ type: string; text?: string; data?: string; mimeType?: string }>
+  ): Promise<void> {
+    this.postMessage({ type: 'receiveMessage', payload: { role: 'assistant', content: '' } });
 
-      this.postMessage({ type: 'receiveMessage', payload: { role: 'assistant', content: '' } });
-
-      let accumulatedContent = '';
-      let eventDiffs: Array<{ path: string; added: number; deleted: number; content: string }> = [];
-
-      await this._opencode.sendPrompt(
-        sessionId,
-        prompt,
-        (text) => {
-          accumulatedContent += text;
-          this.postMessage({ type: 'receiveChunk', payload: { content: text, fullContent: accumulatedContent } });
-        },
-        (name, args) => {
-          this.postMessage({ type: 'receiveMessage', payload: { role: 'tool', content: `🔧 ${name} running...` } });
-        },
-        (error) => {
-          this.postMessage({ type: 'error', payload: { message: error } });
-        },
-        model,
-        agent,
-        extraParts.length > 0 ? extraParts : undefined,
-        (event) => { this.postMessage({ type: 'toolEvent', payload: event }); },
-        (meta) => { this.postMessage({ type: 'messageMeta', payload: meta }); },
-        (reasoning) => { this.postMessage({ type: 'reasoningContent', payload: reasoning }); },
-        (diffs) => { eventDiffs = diffs; },
-      );
-
-      this.postMessage({ type: 'streamEnd', payload: { content: accumulatedContent } });
-
-      const diffs = eventDiffs.length > 0 ? eventDiffs : await this._opencode.getSessionDiff(sessionId);
-      if (Array.isArray(diffs) && diffs.length > 0) {
-        for (const diff of diffs) {
-          if (diff.path && (diff.added > 0 || diff.deleted > 0)) {
-            this.postMessage({
-              type: 'toolEvent',
-              payload: {
-                id: `file_edit_${diff.path}_${Date.now()}`,
-                type: 'file_edit',
-                name: 'file_edit',
-                status: 'completed',
-                content: diff.path,
-                meta: { path: diff.path, added: diff.added, deleted: diff.deleted, content: diff.content },
-              },
-            });
-          }
-        }
+    let accumulatedContent = '';
+    let eventDiffs: Array<{ path: string; added: number; deleted: number; content: string }> = [];
+
+    await this._opencode.sendPrompt(sessionId, prompt, {
+      onContent: (text) => {
+        accumulatedContent += text;
+        this.postMessage({ type: 'receiveChunk', payload: { content: text, fullContent: accumulatedContent } });
+      },
+      onToolCall: (name, _args) => {
+        this.postMessage({ type: 'receiveMessage', payload: { role: 'tool', content: `🔧 ${name} running...` } });
+      },
+      onError: (error) => {
+        this.postMessage({ type: 'error', payload: { message: error } });
+      },
+      model,
+      agent,
+      extraParts: extraParts && extraParts.length > 0 ? extraParts : undefined,
+      onToolEvent: (event) => { this.postMessage({ type: 'toolEvent', payload: event }); },
+      onMessageMeta: (meta) => { this.postMessage({ type: 'messageMeta', payload: meta }); },
+      onReasoning: (reasoning) => { this.postMessage({ type: 'reasoningContent', payload: reasoning }); },
+      onDiffs: (diffs) => { eventDiffs = diffs; },
+    });
+
+    this.postMessage({ type: 'streamEnd', payload: { content: accumulatedContent } });
+    await this._handleDiffs(sessionId, eventDiffs);
+  }
+
+  private async _handleDiffs(sessionId: string, eventDiffs: Array<{ path: string; added: number; deleted: number; content: string }>): Promise<void> {
+    const diffs = eventDiffs.length > 0 ? eventDiffs : await this._opencode.getSessionDiff(sessionId);
+    if (!Array.isArray(diffs) || diffs.length === 0) return;
+
+    for (const diff of diffs) {
+      if (diff.path && (diff.added > 0 || diff.deleted > 0)) {
+        this.postMessage({
+          type: 'toolEvent',
+          payload: {
+            id: `file_edit_${diff.path}_${Date.now()}`,
+            type: 'file_edit',
+            name: 'file_edit',
+            status: 'completed',
+            content: diff.path,
+            meta: { path: diff.path, added: diff.added, deleted: diff.deleted, content: diff.content },
+          },
+        });
       }
-    } catch (err: any) {
-      const msg = err?.message || err?.toString?.() || 'Unknown error';
-      this.postMessage({ type: 'error', payload: { message: msg } });
-      this.postMessage({ type: 'streamEnd', payload: { content: '' } });
     }
   }
 
@@ -449,8 +486,39 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
     }
   }
 
+  private validatePayload(type: string, payload: any): boolean {
+    if (!payload && type !== 'clearChat' && type !== 'unrevert' && type !== 'getSavedModel' && type !== 'loadSkills' && type !== 'webviewReady') {
+      return false;
+    }
+    switch (type) {
+      case 'searchFiles':
+        return typeof payload?.query === 'string';
+      case 'saveModel':
+      case 'revertMessage':
+        return typeof payload?.messageId === 'string';
+      case 'respondPermission':
+        return typeof payload?.permId === 'string' && typeof payload?.response === 'string';
+      case 'respondReadPermission':
+        return typeof payload?.filePath === 'string' && typeof payload?.response === 'string';
+      case 'runCommand':
+        return typeof payload?.command === 'string';
+      case 'setApiKey':
+        return typeof payload?.providerId === 'string' && typeof payload?.key === 'string';
+      case 'removeApiKey':
+        return typeof payload?.providerId === 'string';
+      case 'openDiff':
+        return typeof payload?.filePath === 'string';
+      case 'loadSession':
+      case 'deleteSession':
+        return typeof payload?.sessionId === 'string';
+      default:
+        return true;
+    }
+  }
+
   dispose() {
     this._opencode.stop();
+    this._view = undefined;
   }
 
   private _loadSkills(): Array<{ name: string; description?: string }> {
@@ -459,8 +527,6 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
     const skillsDir = path.join(workspaceFolders[0].uri.fsPath, '.agents', 'skills');
     if (!existsSync(skillsDir)) return [];
     try {
-      const entries = vscode.workspace.fs.readDirectory(vscode.Uri.file(skillsDir));
-      // Can't easily use readDirectory sync, fall back to fs
       const dirs = readdirSync(skillsDir, { withFileTypes: true });
       const result: Array<{ name: string; description?: string }> = [];
       for (const entry of dirs) {
@@ -534,10 +600,22 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
     const workspaceFolders = vscode.workspace.workspaceFolders;
     if (!workspaceFolders) return;
     const root = workspaceFolders[0].uri.fsPath;
+
+    const allowedFlags = new Set(['--no-index', '-U', '--unified', '--stat', '--shortstat', '--numstat', '--name-only', '--name-status', '--check', '--color', '--color-words']);
+    const safeArgs: string[] = [];
+    if (args) {
+      for (const arg of args.split(' ')) {
+        if (arg.startsWith('--') && !allowedFlags.has(arg)) continue;
+        if (arg.startsWith('-') && !arg.match(/^-U\d+$/)) continue;
+        if (!arg.includes(';') && !arg.includes('|') && !arg.includes('&&') && !arg.includes('||')) {
+          safeArgs.push(arg);
+        }
+      }
+    }
+
     try {
-      const diff = execFileSync('git', ['diff', '--cached', ...(args ? args.split(' ') : [])], { cwd: root, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 });
+      const diff = execFileSync('git', ['diff', '--cached', ...safeArgs], { cwd: root, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 });
       const prompt = `Review the following uncommitted changes:\n\n${diff.slice(0, 10000)}${diff.length > 10000 ? '\n...(truncated)' : ''}\n\nProvide a concise code review focusing on potential bugs, security issues, and improvements.`;
-      // Send as a user message like normal sendMessage
       this._processPrompt(prompt, 'review', undefined);
     } catch (err: any) {
       this.postMessage({ type: 'error', payload: { message: `Review failed: ${err.message}` } });
@@ -557,23 +635,22 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
     const agent = MODE_TO_AGENT[mode] || 'build';
     let accumulatedContent = '';
 
-    await this._opencode.sendPrompt(
-      sessionId,
-      prompt,
-      (chunk) => {
+    await this._opencode.sendPrompt(sessionId, prompt, {
+      onContent: (chunk) => {
         accumulatedContent += chunk;
         this.postMessage({ type: 'receiveChunk', payload: { content: chunk, fullContent: accumulatedContent } });
       },
-      () => {},
-      (error) => {
+      onToolCall: () => {},
+      onError: (error) => {
         this.postMessage({ type: 'error', payload: { message: error } });
       },
-      undefined,
       agent,
-      [],
-      (event) => { this.postMessage({ type: 'toolEvent', payload: event }); },
-      (meta) => { this.postMessage({ type: 'messageMeta', payload: meta }); },
-    );
+      extraParts: [],
+      onToolEvent: (event) => { this.postMessage({ type: 'toolEvent', payload: event }); },
+      onMessageMeta: (meta) => { this.postMessage({ type: 'messageMeta', payload: meta }); },
+      onReasoning: (reasoning) => { this.postMessage({ type: 'reasoningContent', payload: reasoning }); },
+      onDiffs: () => {},
+    });
   }
 
   private _getHtmlForWebview(webview: vscode.Webview) {
@@ -588,7 +665,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider {
       <html lang="en">
       <head>
         <meta charset="UTF-8">
-        <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src ${webview.cspSource} data:; script-src 'nonce-${scriptNonce}'; style-src 'nonce-${styleNonce}'; connect-src ${webview.cspSource} http://127.0.0.1:${serverPort} http://localhost:${serverPort};">
+        <meta http-equiv="Content-Security-Policy" content="default-src 'none'; base-uri 'self'; img-src ${webview.cspSource} data:; script-src 'nonce-${scriptNonce}'; style-src 'nonce-${styleNonce}'; connect-src ${webview.cspSource}${serverPort ? ` http://127.0.0.1:${serverPort} http://localhost:${serverPort}` : ''}">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>Opencode</title>
         <style nonce="${styleNonce}">
diff --git a/src/extension/services/ApiClient.ts b/src/extension/services/ApiClient.ts
index ab68a91..411fe09 100644
--- a/src/extension/services/ApiClient.ts
+++ b/src/extension/services/ApiClient.ts
@@ -1,11 +1,5 @@
 import { ProviderListResult } from '../types';
-
-interface NormalizedDiff {
-  path: string;
-  added: number;
-  deleted: number;
-  content: string;
-}
+import { NormalizedDiff, normalizeDiff } from '../utils/diffUtils';
 
 export interface ApiClientOptions {
   baseUrl: string;
@@ -30,7 +24,7 @@ export class ApiClient {
     this.authHeader = authHeader;
   }
 
-  private async fetch(path: string, options: RequestInit = {}): Promise<any> {
+  private async fetch<T = unknown>(path: string, options: RequestInit = {}): Promise<T> {
     const url = `${this.baseUrl}${path}`;
     const response = await fetch(url, {
       ...options,
@@ -43,20 +37,22 @@ export class ApiClient {
 
     if (!response.ok) {
       const text = await response.text();
-      console.error(`[opencode:api] ${options.method || 'GET'} ${path} -> ${response.status}: ${text.slice(0, 500)}`);
+      const isJson = text.startsWith('{') || text.startsWith('[');
+      const safeMsg = isJson && text.includes('"error"') ? 'JSON error response' : text.slice(0, 100);
+      console.error(`[opencode:api] ${options.method || 'GET'} ${path} -> ${response.status}: ${safeMsg}`);
       throw new Error(`HTTP ${response.status}: ${text.slice(0, 200)}`);
     }
 
     const contentType = response.headers.get('content-type') || '';
     if (contentType.includes('application/json')) {
-      return response.json();
+      return response.json() as Promise<T>;
     }
 
-    return response.text();
+    return response.text() as unknown as T;
   }
 
   async createSession(title?: string): Promise<{ id: string; title?: string }> {
-    const data = await this.fetch('/session', {
+    const data = await this.fetch<{ id: string; title?: string }>('/session', {
       method: 'POST',
       body: JSON.stringify({
         title: title || `VS Code - ${new Date().toLocaleString()}`,
@@ -66,20 +62,19 @@ export class ApiClient {
   }
 
   async listSessions(): Promise<{ id: string; title?: string }[]> {
-    const data = await this.fetch('/session');
+    const data = await this.fetch<{ id: string; title?: string }[]>('/session');
     return Array.isArray(data) ? data : [];
   }
 
   async getSessionDiff(sessionId: string): Promise<NormalizedDiff[]> {
-    const result = await this.fetch(`/session/${sessionId}/diff`);
+    const result = await this.fetch<{ files?: NormalizedDiff[] } | NormalizedDiff[]>(`/session/${sessionId}/diff`);
     let arr: any[] = [];
     if (Array.isArray(result)) {
       arr = result;
-    } else if (result?.files) {
-      arr = result.files;
+    } else if (result && 'files' in result) {
+      arr = result.files || [];
     }
     const normalized = arr.map(normalizeDiff);
-    console.log('[opencode] Session diff result:', normalized.length, 'files');
     return normalized;
   }
 
@@ -229,7 +224,6 @@ export class ApiClient {
         body: JSON.stringify({ response: 'always', remember: true }),
       });
       if (response.ok) {
-        console.log('[opencode] Permission granted:', permissionId);
       } else {
         const text = await response.text();
         console.error('[opencode] Permission grant failed:', response.status, text.slice(0, 200));
@@ -255,18 +249,4 @@ export class ApiClient {
 
     return response;
   }
-}
-
-function normalizeDiff(d: any): NormalizedDiff {
-  const path = d.path || d.file || '';
-  const content = d.content || d.patch || '';
-  let added = typeof d.added === 'number' ? d.added : 0;
-  let deleted = typeof d.deleted === 'number' ? d.deleted : 0;
-  if (added === 0 && deleted === 0 && content) {
-    for (const line of content.split('\n')) {
-      if (line.startsWith('+') && !line.startsWith('+++')) added++;
-      if (line.startsWith('-') && !line.startsWith('---')) deleted++;
-    }
-  }
-  return { path, added, deleted, content };
 }
\ No newline at end of file
diff --git a/src/extension/services/AuthService.ts b/src/extension/services/AuthService.ts
index 0a975bf..06f41a4 100644
--- a/src/extension/services/AuthService.ts
+++ b/src/extension/services/AuthService.ts
@@ -1,23 +1,41 @@
 import * as vscode from 'vscode';
 import { OpencodeCli } from './OpencodeCli';
+import { ApiClient } from './ApiClient';
 
 /**
  * Manages API key persistence via VS Code SecretStorage.
  * Restores keys on startup and stores new keys after successful auth.
  */
 export class AuthService {
+  private _apiClient: ApiClient | null = null;
+
   constructor(
     private readonly _opencode: OpencodeCli,
     private readonly _context: vscode.ExtensionContext,
   ) {}
 
+  private ensureApiClient(): ApiClient {
+    if (!this._opencode.url || !this._opencode.authHeader) {
+      throw new Error('Opencode server not running');
+    }
+    if (!this._apiClient) {
+      this._apiClient = new ApiClient({
+        baseUrl: this._opencode.url,
+        authHeader: this._opencode.authHeader,
+      });
+    } else {
+      this._apiClient.updateAuth(this._opencode.url, this._opencode.authHeader);
+    }
+    return this._apiClient;
+  }
+
   async restoreApiKeys(): Promise<void> {
     try {
-      const authData = await this._opencode.getProviderAuth();
+      const authData = await this.ensureApiClient().getProviderAuth();
       for (const [providerId] of Object.entries(authData)) {
         const stored = await this._context.secrets.get(`opencode-key-${providerId}`);
         if (stored) {
-          await this._opencode.setAuth(providerId, stored);
+          await this.ensureApiClient().setAuth(providerId, stored);
         }
       }
     } catch {
@@ -26,7 +44,7 @@ export class AuthService {
   }
 
   async setApiKey(providerId: string, key: string): Promise<boolean> {
-    const success = await this._opencode.setAuth(providerId, key);
+    const success = await this.ensureApiClient().setAuth(providerId, key);
     if (success) {
       await this._context.secrets.store(`opencode-key-${providerId}`, key);
     }
@@ -34,7 +52,7 @@ export class AuthService {
   }
 
   async removeApiKey(providerId: string): Promise<void> {
-    await this._opencode.removeAuth(providerId);
+    await this.ensureApiClient().removeAuth(providerId);
     await this._context.secrets.delete(`opencode-key-${providerId}`);
   }
 }
diff --git a/src/extension/services/EventDispatcher.ts b/src/extension/services/EventDispatcher.ts
index 3cd9d72..337978e 100644
--- a/src/extension/services/EventDispatcher.ts
+++ b/src/extension/services/EventDispatcher.ts
@@ -1,4 +1,5 @@
 import { SSEMessage } from './SseStream';
+import { NormalizedDiff, normalizeDiff } from '../utils/diffUtils';
 
 export interface ToolEvent {
   id: string;
@@ -30,16 +31,6 @@ export interface EventCallbacks {
   onDiffs?: (diffs: NormalizedDiff[]) => void;
 }
 
-/**
- * Normalized file diff with parsed line counts and content.
- */
-export interface NormalizedDiff {
-  path: string;
-  added: number;
-  deleted: number;
-  content: string;
-}
-
 const READ_TOOLS = new Set(['read', 'grep', 'glob', 'list', 'webfetch']);
 
 function extractReadPaths(tool: string, args: any): string[] {
@@ -63,23 +54,8 @@ function extractReadPaths(tool: string, args: any): string[] {
   }
 }
 
-function normalizeDiff(d: any): NormalizedDiff {
-  const path = d.path || d.file || '';
-  const content = d.content || d.patch || '';
-  let added = typeof d.added === 'number' ? d.added : 0;
-  let deleted = typeof d.deleted === 'number' ? d.deleted : 0;
-  if (added === 0 && deleted === 0 && content) {
-    for (const line of content.split('\n')) {
-      if (line.startsWith('+') && !line.startsWith('+++')) added++;
-      if (line.startsWith('-') && !line.startsWith('---')) deleted++;
-    }
-  }
-  return { path, added, deleted, content };
-}
-
 export class EventDispatcher {
   private callbacks: EventCallbacks;
-  private sessionPartDeltas: Map<string, Set<string>> = new Map();
   private sessionPartTypes: Map<string, Map<string, string>> = new Map();
 
   constructor(callbacks: EventCallbacks) {
@@ -87,19 +63,42 @@ export class EventDispatcher {
   }
 
   resetSession(sessionId: string): void {
-    this.sessionPartDeltas.set(sessionId, new Set());
     this.sessionPartTypes.set(sessionId, new Map());
   }
 
   clearSession(sessionId: string): void {
-    this.sessionPartDeltas.delete(sessionId);
     this.sessionPartTypes.delete(sessionId);
   }
 
   dispatch(event: SSEMessage, sessionId: string): void {
-    const cb = this.callbacks;
+    this.handleMessageMeta(event);
+    switch (event.type) {
+      case 'message.part.updated':
+        this.handleMessagePartUpdated(event, sessionId);
+        break;
+      case 'message.part.delta':
+        this.handleMessagePartDelta(event, sessionId);
+        break;
+      case 'session.error':
+        this.handleSessionError(event);
+        break;
+      case 'session.status':
+        this.handleSessionStatus(event, sessionId);
+        break;
+      case 'message.updated':
+        this.handleMessageUpdated(event);
+        break;
+      case 'session.diff':
+        this.handleSessionDiff(event);
+        break;
+      case 'permission.asked':
+        this.handlePermissionAsked(event, sessionId);
+        break;
+    }
+  }
 
-    // Track message metadata from event info
+  private handleMessageMeta(event: SSEMessage): void {
+    const cb = this.callbacks;
     const info = event.properties?.info;
     if (info?.id && cb.onMessageMeta) {
       const agent = info.agent || undefined;
@@ -109,194 +108,197 @@ export class EventDispatcher {
         cb.onMessageMeta!({ id: info.id, agent, modelId, time });
       }
     }
+  }
 
-    switch (event.type) {
-      case 'message.part.updated': {
-        const part = event.properties?.part;
-        if (part?.id && part?.type) {
-          const types = this.sessionPartTypes.get(sessionId);
-          types?.set(part.id, part.type);
-        }
-        if (part?.type === 'text') break;
-        if (part?.type === 'reasoning') break;
-        if (part?.type === 'compaction') {
-          cb.onToolEvent?.({
-            id: part.id || 'compaction',
-            type: 'compacting',
-            name: 'compaction',
-            status: part?.state?.status === 'completed' ? 'completed' : 'running',
-            content: part?.state?.status === 'completed' ? 'Conversation compacted' : 'Compacting conversation...',
-            meta: { result: part?.result || part?.state?.result },
-          });
-          break;
-        }
-        if (part?.type === 'tool_call') {
-          const toolName = part.name || 'unknown';
-          const toolArgs = part.args;
-          const readTools = ['read', 'grep', 'glob', 'list', 'webfetch'];
-          if (readTools.includes(toolName)) {
-            const paths = extractReadPaths(toolName, toolArgs);
-            if (paths.length > 0) {
-              for (const p of paths) {
-                cb.onToolEvent?.({
-                  id: `${part.id || toolName}_read_${p}`,
-                  type: 'file_read',
-                  name: toolName,
-                  status: 'running',
-                  content: `Reading: ${p}`,
-                  meta: { path: p, tool: toolName },
-                });
-              }
-            }
-          }
+  private handleMessagePartUpdated(event: SSEMessage, sessionId: string): void {
+    const cb = this.callbacks;
+    const part = event.properties?.part;
+    if (part?.id && part?.type) {
+      const types = this.sessionPartTypes.get(sessionId);
+      types?.set(part.id, part.type);
+    }
+    if (part?.type === 'text' || part?.type === 'reasoning') return;
+    if (part?.type === 'compaction') {
+      cb.onToolEvent?.({
+        id: part.id || 'compaction',
+        type: 'compacting',
+        name: 'compaction',
+        status: part?.state?.status === 'completed' ? 'completed' : 'running',
+        content: part?.state?.status === 'completed' ? 'Conversation compacted' : 'Compacting conversation...',
+        meta: { result: part?.result || part?.state?.result },
+      });
+      return;
+    }
+    if (part?.type === 'tool_call') {
+      this.handleToolCallEvent(cb, part);
+    }
+    if (part?.type === 'tool') {
+      this.handleToolStateEvent(cb, part);
+    }
+    if (part?.type === 'tool_result' && part?.result) {
+      cb.onToolEvent?.({
+        id: part.id || part.name || 'tool',
+        type: 'tool_result',
+        name: part.name || 'unknown',
+        status: 'completed',
+        content: `${part.name || 'unknown'} result`,
+        meta: { result: part.result },
+      });
+      cb.onContent?.(`\n[Tool: ${part.name || 'unknown'}]\n${part.result}\n[/Tool]\n`);
+    }
+  }
+
+  private handleToolCallEvent(cb: EventCallbacks, part: any): void {
+    const toolName = part.name || 'unknown';
+    const toolArgs = part.args;
+    if (READ_TOOLS.has(toolName)) {
+      const paths = extractReadPaths(toolName, toolArgs);
+      for (const p of paths) {
+        cb.onToolEvent?.({
+          id: `${part.id || toolName}_read_${p}`,
+          type: 'file_read',
+          name: toolName,
+          status: 'running',
+          content: `Reading: ${p}`,
+          meta: { path: p, tool: toolName },
+        });
+      }
+    }
+    cb.onToolEvent?.({
+      id: part.id || part.name || 'tool',
+      type: 'tool_call',
+      name: toolName,
+      status: 'running',
+      content: `${toolName} calling...`,
+      meta: { args: toolArgs },
+    });
+    cb.onToolCall?.(toolName, toolArgs);
+  }
+
+  private handleToolStateEvent(cb: EventCallbacks, part: any): void {
+    const toolName = part?.tool || 'unknown';
+    const status = part?.state?.status;
+    if (status === 'running') {
+      cb.onToolEvent?.({
+        id: part.id || toolName,
+        type: 'tool_result',
+        name: toolName,
+        status: 'running',
+        content: `${toolName} running...`,
+      });
+    } else if (status === 'completed') {
+      const toolResult = part?.result || part?.state?.result;
+      const meta: any = { result: toolResult };
+      if (toolName === 'task') {
+        meta.sessionId = part?.state?.metadata?.sessionId;
+        meta.description = part?.state?.input?.description;
+        meta.subagentType = part?.state?.input?.subagent_type;
+      }
+      if (READ_TOOLS.has(toolName)) {
+        const paths = extractReadPaths(toolName, part?.state?.input?.args || part?.args || toolResult);
+        for (const p of paths) {
           cb.onToolEvent?.({
-            id: part.id || part.name || 'tool',
-            type: 'tool_call',
+            id: `${part.id || toolName}_read_${p}`,
+            type: 'file_read',
             name: toolName,
-            status: 'running',
-            content: `${toolName} calling...`,
-            meta: { args: toolArgs },
-          });
-          cb.onToolCall?.(toolName, toolArgs);
-        }
-        if (part?.type === 'tool') {
-          const toolName = part?.tool || 'unknown';
-          const status = part?.state?.status;
-          if (status === 'running') {
-            cb.onToolEvent?.({
-              id: part.id || toolName,
-              type: 'tool_result',
-              name: toolName,
-              status: 'running',
-              content: `${toolName} running...`,
-            });
-          } else if (status === 'completed') {
-            const toolResult = part?.result || part?.state?.result;
-            const meta: any = { result: toolResult };
-            if (toolName === 'task') {
-              meta.sessionId = part?.state?.metadata?.sessionId;
-              meta.description = part?.state?.input?.description;
-              meta.subagentType = part?.state?.input?.subagent_type;
-            }
-            if (READ_TOOLS.has(toolName)) {
-              const paths = extractReadPaths(toolName, part?.state?.input?.args || part?.args || toolResult);
-              for (const p of paths) {
-                cb.onToolEvent?.({
-                  id: `${part.id || toolName}_read_${p}`,
-                  type: 'file_read',
-                  name: toolName,
-                  status: 'completed',
-                  content: `Read: ${p}`,
-                  meta: { path: p, tool: toolName, result: toolResult },
-                });
-              }
-            }
-            cb.onToolEvent?.({
-              id: part.id || toolName,
-              type: 'tool_result',
-              name: toolName,
-              status: 'completed',
-              content: toolName === 'task' ? 'Task completed' : `${toolName} completed`,
-              meta,
-            });
-            if (toolResult) {
-              cb.onContent?.(`\n[${toolName} result]\n${typeof toolResult === 'string' ? toolResult : JSON.stringify(toolResult, null, 2)}\n[/${toolName}]\n`);
-            }
-          } else if (status === 'failed') {
-            if (READ_TOOLS.has(toolName)) {
-              const paths = extractReadPaths(toolName, part?.state?.input?.args || part?.args);
-              for (const p of paths) {
-                cb.onToolEvent?.({
-                  id: `${part.id || toolName}_read_${p}`,
-                  type: 'file_read',
-                  name: toolName,
-                  status: 'failed',
-                  content: `Read failed: ${p}`,
-                  meta: { path: p, tool: toolName, error: part.state.error || part.state.reason },
-                });
-              }
-            }
-            cb.onToolEvent?.({
-              id: part.id || toolName,
-              type: 'tool_result',
-              name: toolName,
-              status: 'failed',
-              content: `${toolName} failed`,
-              meta: { error: part.state.error || part.state.reason },
-            });
-            cb.onError?.(`${toolName} failed: ${part.state.error || part.state.reason || 'unknown error'}`);
-          }
-        }
-        if (part?.type === 'tool_result' && part?.result) {
-          cb.onToolEvent?.({
-            id: part.id || part.name || 'tool',
-            type: 'tool_result',
-            name: part.name || 'unknown',
             status: 'completed',
-            content: `${part.name || 'unknown'} result`,
-            meta: { result: part.result },
+            content: `Read: ${p}`,
+            meta: { path: p, tool: toolName, result: toolResult },
           });
-          cb.onContent?.(`\n[Tool: ${part.name || 'unknown'}]\n${part.result}\n[/Tool]\n`);
         }
-        break;
       }
-      case 'message.part.delta': {
-        const props = event.properties;
-        if (props?.field === 'text' && props?.delta) {
-          const types = this.sessionPartTypes.get(sessionId);
-          const partType = props.partID ? types?.get(props.partID) : undefined;
-          if (partType === 'reasoning') {
-            cb.onReasoning?.(props.delta);
-            break;
-          }
-          const deltas = this.sessionPartDeltas.get(sessionId);
-          if (deltas && props.partID) deltas.add(props.partID);
-          cb.onContent?.(props.delta);
-        }
-        break;
-      }
-      case 'session.error': {
-        cb.onError?.(event.properties?.error?.message || 'Unknown error');
-        break;
-      }
-      case 'session.status': {
-        // idle status handled by caller
-        break;
+      cb.onToolEvent?.({
+        id: part.id || toolName,
+        type: 'tool_result',
+        name: toolName,
+        status: 'completed',
+        content: toolName === 'task' ? 'Task completed' : `${toolName} completed`,
+        meta,
+      });
+      if (toolResult) {
+        cb.onContent?.(`\n[${toolName} result]\n${typeof toolResult === 'string' ? toolResult : JSON.stringify(toolResult, null, 2)}\n[/${toolName}]\n`);
       }
-      case 'message.updated': {
-        const rawSummaryDiffs = event.properties?.info?.summary?.diffs;
-        if (Array.isArray(rawSummaryDiffs) && rawSummaryDiffs.length > 0 && cb.onDiffs) {
-          const normalized = rawSummaryDiffs.map(normalizeDiff);
-          console.log('[opencode] Diffs from message.updated:', normalized.length, 'files');
-          cb.onDiffs(normalized);
-        }
-        break;
-      }
-      case 'session.diff': {
-        const rawDiff = event.properties?.diff;
-        if (Array.isArray(rawDiff) && rawDiff.length > 0 && cb.onDiffs) {
-          const normalized = rawDiff.map(normalizeDiff);
-          console.log('[opencode] Diffs from session.diff:', normalized.length, 'files');
-          cb.onDiffs(normalized);
+    } else if (status === 'failed') {
+      if (READ_TOOLS.has(toolName)) {
+        const paths = extractReadPaths(toolName, part?.state?.input?.args || part?.args);
+        for (const p of paths) {
+          cb.onToolEvent?.({
+            id: `${part.id || toolName}_read_${p}`,
+            type: 'file_read',
+            name: toolName,
+            status: 'failed',
+            content: `Read failed: ${p}`,
+            meta: { path: p, tool: toolName, error: part.state.error || part.state.reason },
+          });
         }
-        break;
       }
-      case 'permission.asked': {
-        const permId = event.properties?.id || event.properties?.permissionID || event.properties?.permissionId;
-        const permSessionId = event.properties?.sessionID || event.properties?.sessionId || sessionId;
-        const permType = event.properties?.permission;
-        const patterns = event.properties?.patterns || [];
-        console.log('[opencode] Permission asked:', permType, patterns, 'id:', permId, 'session:', permSessionId);
-        cb.onToolEvent?.({
-          id: permId || 'permission',
-          type: 'permission',
-          name: 'permission',
-          status: 'running',
-          content: `${permType}${patterns.length > 0 ? ' ' + patterns.join(', ') : ''}`,
-          meta: { permId, permSessionId, permType, patterns },
-        });
-        break;
+      cb.onToolEvent?.({
+        id: part.id || toolName,
+        type: 'tool_result',
+        name: toolName,
+        status: 'failed',
+        content: `${toolName} failed`,
+        meta: { error: part.state.error || part.state.reason },
+      });
+      cb.onError?.(`${toolName} failed: ${part.state.error || part.state.reason || 'unknown error'}`);
+    }
+  }
+
+  private handleMessagePartDelta(event: SSEMessage, sessionId: string): void {
+    const cb = this.callbacks;
+    const props = event.properties;
+    if (props?.field === 'text' && props?.delta) {
+      const types = this.sessionPartTypes.get(sessionId);
+      const partType = props.partID ? types?.get(props.partID) : undefined;
+      if (partType === 'reasoning') {
+        cb.onReasoning?.(props.delta);
+        return;
       }
+      cb.onContent?.(props.delta);
     }
   }
+
+  private handleSessionError(event: SSEMessage): void {
+    this.callbacks.onError?.(event.properties?.error?.message || 'Unknown error');
+  }
+
+  private handleSessionStatus(event: SSEMessage, sessionId: string): void {
+    if (event.properties?.status?.type === 'idle') {
+      this.clearSession(sessionId);
+    }
+  }
+
+  private handleMessageUpdated(event: SSEMessage): void {
+    const cb = this.callbacks;
+    const rawSummaryDiffs = event.properties?.info?.summary?.diffs;
+    if (Array.isArray(rawSummaryDiffs) && rawSummaryDiffs.length > 0 && cb.onDiffs) {
+      const normalized = rawSummaryDiffs.map(normalizeDiff);
+      cb.onDiffs(normalized);
+    }
+  }
+
+  private handleSessionDiff(event: SSEMessage): void {
+    const cb = this.callbacks;
+    const rawDiff = event.properties?.diff;
+    if (Array.isArray(rawDiff) && rawDiff.length > 0 && cb.onDiffs) {
+      const normalized = rawDiff.map(normalizeDiff);
+      cb.onDiffs(normalized);
+    }
+  }
+
+  private handlePermissionAsked(event: SSEMessage, sessionId: string): void {
+    const cb = this.callbacks;
+    const permId = event.properties?.id || event.properties?.permissionID || event.properties?.permissionId;
+    const permSessionId = event.properties?.sessionID || event.properties?.sessionId || sessionId;
+    const permType = event.properties?.permission;
+    const patterns = event.properties?.patterns || [];
+    cb.onToolEvent?.({
+      id: permId || 'permission',
+      type: 'permission',
+      name: 'permission',
+      status: 'running',
+      content: `${permType}${patterns.length > 0 ? ' ' + patterns.join(', ') : ''}`,
+      meta: { permId, permSessionId, permType, patterns },
+    });
+  }
 }
\ No newline at end of file
diff --git a/src/extension/services/GitInfo.ts b/src/extension/services/GitInfo.ts
index 3066856..c6ccfa9 100644
--- a/src/extension/services/GitInfo.ts
+++ b/src/extension/services/GitInfo.ts
@@ -1,11 +1,6 @@
 import * as vscode from 'vscode';
 import { execFileSync } from 'node:child_process';
-
-export interface GitInfo {
-  branch: string;
-  lastCommitTime: string;
-  projectPath: string;
-}
+import { GitInfo } from '../types';
 
 export function getGitInfo(): GitInfo {
   const workspaceFolders = vscode.workspace.workspaceFolders;
diff --git a/src/extension/services/OpencodeCli.ts b/src/extension/services/OpencodeCli.ts
index b7950dc..a6be21f 100644
--- a/src/extension/services/OpencodeCli.ts
+++ b/src/extension/services/OpencodeCli.ts
@@ -4,7 +4,8 @@ import { randomBytes } from 'crypto';
 import { ProviderListResult } from '../types';
 import { ApiClient } from './ApiClient';
 import { SseStream, SSEMessage } from './SseStream';
-import { EventDispatcher, EventCallbacks, NormalizedDiff } from './EventDispatcher';
+import { EventDispatcher, EventCallbacks } from './EventDispatcher';
+import { NormalizedDiff } from '../utils/diffUtils';
 
 interface OpencodeServerInfo {
   port: number;
@@ -33,6 +34,7 @@ export class OpencodeCli {
   private apiClient: ApiClient | null = null;
   private sseStream: SseStream;
   private eventDispatcher: EventDispatcher | null = null;
+  private idleResolveRef: (() => void) | null = null;
 
   constructor(cwd?: string) {
     this.binaryPath = this.resolveBinary();
@@ -41,11 +43,25 @@ export class OpencodeCli {
   }
 
   private resolveBinary(): string {
-    // Priority 1: explicit env var override
+    // Priority 1: explicit env var override (restricted to allowed directories)
     const envPath = process.env.OPENCODE_BIN_PATH;
     if (envPath) {
       try {
-        if (existsSync(envPath)) return envPath;
+        if (existsSync(envPath)) {
+          const allowedRoots = [
+            process.env.HOME || process.env.USERPROFILE || '',
+            process.env.LOCALAPPDATA || '',
+            process.env.APPDATA || '',
+            '/usr/local',
+            '/usr/bin',
+            '/bin',
+            '/usr/lib',
+          ].filter(Boolean);
+          const normalizedEnv = envPath.replace(/\\/g, '/').toLowerCase();
+          const isAllowed = allowedRoots.some(root => normalizedEnv.startsWith(root.replace(/\\/g, '/').toLowerCase()));
+          if (isAllowed) return envPath;
+          console.warn('[opencode] OPENCODE_BIN_PATH not in allowed directories:', envPath);
+        }
       } catch (err) { console.warn('[opencode] Binary path check failed:', err); }
     }
 
@@ -56,15 +72,10 @@ export class OpencodeCli {
     const npmPrefix = process.env.npm_config_prefix;
 
     if (platform === 'win32') {
-      const localAppData = process.env.LOCALAPPDATA;
       const appData = process.env.APPDATA;
-      // npm global installations
+      // npm global installations only
       if (appData) candidates.push(`${appData}\\npm\\node_modules\\opencode-ai\\node_modules\\opencode-windows-x64\\bin\\opencode.exe`);
       if (appData) candidates.push(`${appData}\\npm\\node_modules\\opencode-ai\\node_modules\\opencode-windows-x64-baseline\\bin\\opencode.exe`);
-      // Portable/local installs
-      if (localAppData) candidates.push(`${localAppData}\\opencode\\opencode.exe`);
-      candidates.push('C:\\opencode\\opencode.exe');
-      candidates.push('C:\\Program Files\\opencode\\opencode.exe');
     } else if (platform === 'darwin') {
       // macOS npm global + common package managers
       if (npmPrefix) candidates.push(`${npmPrefix}/bin/opencode`);
@@ -98,7 +109,7 @@ export class OpencodeCli {
     return 'opencode';
   }
 
-  private get authHeader(): Record<string, string> {
+  get authHeader(): Record<string, string> {
     if (!this.server) return {};
     const encoded = Buffer.from(`opencode:${this.server.password}`).toString('base64');
     return { Authorization: `Basic ${encoded}` };
@@ -125,7 +136,7 @@ export class OpencodeCli {
   async start(): Promise<void> {
     if (this.server) return;
 
-    const password = 'oc-vsc-' + randomBytes(12).toString('hex');
+    const password = randomBytes(16).toString('hex');
 
     return new Promise((resolve, reject) => {
       const minimalEnv: Record<string, string | undefined> = {
@@ -165,7 +176,6 @@ export class OpencodeCli {
         if (match && !started) {
           started = true;
           const port = Number.parseInt(match[1], 10);
-          console.log('[opencode] Server started on port:', port);
           this.server = { port, password, url: `http://127.0.0.1:${port}` };
           this.process = proc;
           resolve();
@@ -181,10 +191,13 @@ export class OpencodeCli {
         if (!started) reject(err);
       });
 
-      proc.on('exit', (code: any) => {
+proc.on('exit', (code: any) => {
         if (!started) reject(new Error(`opencode serve exited with code ${code}`));
         this.server = null;
-        this.process = null;
+        if (this.idleResolveRef) {
+          this.idleResolveRef();
+          this.idleResolveRef = null;
+        }
       });
 
       setTimeout(() => {
@@ -225,7 +238,6 @@ export class OpencodeCli {
     try {
       return await this.ensureApiClient().getSessionDiff(sessionId);
     } catch (err: any) {
-      console.log('[opencode] Session diff not available:', err?.message);
       return [];
     }
   }
@@ -286,32 +298,26 @@ export class OpencodeCli {
    * and resolves diffs via onDiffs. Returns once the session becomes idle or times out.
    * @param sessionId - Active session ID from createSession
    * @param prompt - User message text
-   * @param onContent - Called per text delta during streaming
-   * @param onToolCall - Called on tool_call events with name + args
-   * @param onError - Called on session.error or HTTP failures
-   * @param model - Optional model override in "providerId/modelId" format
-   * @param agent - Optional agent mode name
-   * @param extraParts - Additional message parts (images, files)
-   * @param onToolEvent - Called on tool events (tool_call, tool_result, file_read, etc.)
-   * @param onMessageMeta - Called when message metadata arrives (id, agent, modelId, time)
-   * @param onReasoning - Called with reasoning content delta
-   * @param onDiffs - Called with file diffs when session diff is available
+   * @param options - Optional callbacks and parameters
    * @returns Promise resolving to the message ID when streaming completes
    */
   async sendPrompt(
     sessionId: string,
     prompt: string,
-    onContent?: (text: string) => void,
-    onToolCall?: (name: string, args: any) => void,
-    onError?: (error: string) => void,
-    model?: string,
-    agent?: string,
-    extraParts?: Array<{ type: string; text?: string; data?: string; mimeType?: string }>,
-    onToolEvent?: (event: { id: string; type: string; name: string; status: string; content: string; meta?: any }) => void,
-    onMessageMeta?: (meta: { id: string; agent?: string; modelId?: string; time?: { created?: number; completed?: number } }) => void,
-    onReasoning?: (text: string) => void,
-    onDiffs?: (diffs: NormalizedDiff[]) => void,
+    options?: {
+      onContent?: (text: string) => void;
+      onToolCall?: (name: string, args: any) => void;
+      onError?: (error: string) => void;
+      model?: string;
+      agent?: string;
+      extraParts?: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;
+      onToolEvent?: (event: { id: string; type: string; name: string; status: string; content: string; meta?: any }) => void;
+      onMessageMeta?: (meta: { id: string; agent?: string; modelId?: string; time?: { created?: number; completed?: number } }) => void;
+      onReasoning?: (text: string) => void;
+      onDiffs?: (diffs: NormalizedDiff[]) => void;
+    },
   ): Promise<string> {
+    const { onContent, onToolCall, onError, model, agent, extraParts, onToolEvent, onMessageMeta, onReasoning, onDiffs } = options || {};
     await this.start();
 
     const parts: Array<{ type: string; text?: string; data?: string; mimeType?: string }> = [
@@ -348,16 +354,17 @@ export class OpencodeCli {
 
     const idlePromise = new Promise<void>((resolve) => {
       let settled = false;
-      const guard = () => {
+      this.idleResolveRef = () => {
         if (!settled) {
           settled = true;
           resolve();
+          this.idleResolveRef = null;
         }
       };
+      const guard = this.idleResolveRef;
 
       const eventUrl = `${this.server!.url}/event`;
       this.sseStream.connect(eventUrl, this.authHeader, (event: SSEMessage) => {
-        console.log('[opencode] /event:', event.type, JSON.stringify(event.properties).slice(0, 200));
         this.eventDispatcher!.dispatch(event, sessionId);
         if (!messageId && event.properties?.info?.id) messageId = event.properties.info.id;
         if (event.type === 'session.status' && event.properties?.status?.type === 'idle') {
@@ -448,12 +455,7 @@ export class OpencodeCli {
   stop(): void {
     this.abortController?.abort();
     if (this.process) {
-      const platform = process.platform;
-      if (platform === 'win32') {
-        this.process.kill();
-      } else {
-        this.process.kill('SIGTERM');
-      }
+      this.process.kill('SIGTERM');
       this.process = null;
     }
     this.server = null;
diff --git a/src/extension/services/PermissionService.ts b/src/extension/services/PermissionService.ts
index 0efe1f8..55dff8d 100644
--- a/src/extension/services/PermissionService.ts
+++ b/src/extension/services/PermissionService.ts
@@ -16,6 +16,10 @@ export class PermissionService {
   }
 
   waitForReadPermission(filePath: string): Promise<boolean> {
+    const deniedPattern = isReadDenied(filePath);
+    if (deniedPattern && this._readAllowCache.has(deniedPattern)) {
+      return Promise.resolve(true);
+    }
     return new Promise<boolean>((resolve) => {
       this._pendingResolvers.set(filePath, (resp) => resolve(resp.allowed));
     });
diff --git a/src/extension/services/SseStream.ts b/src/extension/services/SseStream.ts
index 3725e41..4ea6f11 100644
--- a/src/extension/services/SseStream.ts
+++ b/src/extension/services/SseStream.ts
@@ -9,34 +9,99 @@ export interface SSEMessage {
 
 export type EventCallback = (event: SSEMessage) => void;
 
+interface SseEvent {
+  data: string;
+  event?: string;
+  id?: string;
+}
+
 /**
  * Handles Server-Sent Events (SSE) streaming from the opencode server.
  * Used for both long-lived /event endpoint and POST response streams.
  */
 export class SseStream {
+  private maxRetries = 3;
+  private baseRetryDelay = 1000;
+
   async connect(
     url: string,
     headers: Record<string, string>,
     onEvent: EventCallback,
     signal: AbortSignal
   ): Promise<void> {
-    try {
-      const response = await fetch(url, { headers, signal });
-      await this.parse(response, onEvent);
-    } catch (err: any) {
-      if (err.name !== 'AbortError') {
-        console.error(`[opencode:sse] ${url} error:`, err?.message);
+    let attempt = 0;
+
+    while (!signal.aborted) {
+      try {
+        const response = await fetch(url, { headers, signal });
+        if (!response.ok) {
+          throw new Error(`HTTP ${response.status}`);
+        }
+        await this.parse(response, onEvent, signal);
+        break;
+      } catch (err: any) {
+        if (err.name === 'AbortError' || signal.aborted) break;
+
+        attempt++;
+        if (attempt >= this.maxRetries) {
+          console.error(`[opencode:sse] ${url} failed after ${attempt} attempts:`, err?.message);
+          break;
+        }
+
+        const delay = this.baseRetryDelay * Math.pow(2, attempt - 1);
+        console.warn(`[opencode:sse] ${url} disconnected, retrying in ${delay}ms (attempt ${attempt}/${this.maxRetries})`);
+        await this.sleep(delay, signal);
       }
     }
   }
 
-  async parse(response: Response, onEvent: EventCallback): Promise<void> {
+  private sleep(ms: number, signal: AbortSignal): Promise<void> {
+    return new Promise((resolve, reject) => {
+      const timeout = setTimeout(resolve, ms);
+      signal.addEventListener('abort', () => {
+        clearTimeout(timeout);
+        reject(new DOMException('Aborted', 'AbortError'));
+      });
+    });
+  }
+
+  private parseEventLine(line: string): SseEvent | null {
+    const trimmed = line.trim();
+    if (!trimmed) return null;
+
+    if (trimmed.startsWith('data:')) {
+      const data = trimmed.slice(5).trimStart();
+      return { data };
+    }
+
+    if (trimmed.startsWith('event:')) {
+      return { data: '', event: trimmed.slice(6).trim() };
+    }
+
+    if (trimmed.startsWith('id:')) {
+      return { data: '', id: trimmed.slice(3).trim() };
+    }
+
+    if (trimmed.startsWith('retry:')) {
+      const ms = parseInt(trimmed.slice(6).trim(), 10);
+      if (!isNaN(ms)) this.baseRetryDelay = Math.max(1000, ms);
+      return null;
+    }
+
+    if (trimmed.startsWith(':')) return null;
+
+    return null;
+  }
+
+  async parse(response: Response, onEvent: EventCallback, signal: AbortSignal): Promise<void> {
     try {
       const reader = response.body!.getReader();
       const decoder = new TextDecoder();
       let buffer = '';
+      let lastEventId: string | undefined;
+      let currentEvent: Partial<SseEvent> = {};
 
-      while (true) {
+      while (!signal.aborted) {
         const { done, value } = await reader.read();
         if (done) break;
 
@@ -45,12 +110,29 @@ export class SseStream {
         buffer = lines.pop() || '';
 
         for (const line of lines) {
-          if (line.startsWith('data: ')) {
-            try {
-              onEvent(JSON.parse(line.slice(6)) as SSEMessage);
-            } catch {
-              // skip parse error
+          const event = this.parseEventLine(line);
+          if (!event) continue;
+
+          if (event.event !== undefined) {
+            currentEvent.event = event.event;
+          }
+          if (event.id !== undefined) {
+            lastEventId = event.id;
+            currentEvent.id = event.id;
+          }
+          if (event.data !== undefined) {
+            currentEvent.data = (currentEvent.data || '') + event.data;
+          }
+
+          if (line === '' || line.startsWith('data:') && !buffer.startsWith('data:') && !buffer.startsWith(' ')) {
+            if (currentEvent.data) {
+              try {
+                onEvent(JSON.parse(currentEvent.data) as SSEMessage);
+              } catch {
+                // skip parse error
+              }
             }
+            currentEvent = {};
           }
         }
       }
diff --git a/src/extension/services/readPatterns.ts b/src/extension/services/readPatterns.ts
index 491056f..3789aa1 100644
--- a/src/extension/services/readPatterns.ts
+++ b/src/extension/services/readPatterns.ts
@@ -23,15 +23,39 @@ export const READ_DENY_PATTERNS: string[] = [
   '**/package-lock.json',
   '**/yarn.lock',
   '**/pnpm-lock.yaml',
+  '**/.ssh/**',
+  '**/.aws/**',
+  '**/.kube/**',
+  '**/.npmrc',
+  '**/.npm-token',
+  '**/.netrc',
+  '**/id_rsa',
+  '**/id_dsa',
+  '**/id_ecdsa',
+  '**/id_ed25519',
+  '**/known_hosts',
+  '**/authorized_keys',
+  '**/.aws/credentials',
+  '**/.aws/config',
+  '**/.azure/**',
+  '**/.google_credentials/**',
+  '**/service-account.json',
+  '**/*.googleapis.*',
 ];
 
+const regexCache = new Map<string, RegExp>();
+
 function patternToRegex(pattern: string): RegExp {
+  let regex = regexCache.get(pattern);
+  if (regex) return regex;
   const escaped = pattern
     .replace(/[.+^${}()|[\]\\]/g, '\\$&')
     .replace(/\*\*/g, '___DOUBLESTAR___')
     .replace(/\*/g, '[^/]*')
     .replace(/___DOUBLESTAR___/g, '.*');
-  return new RegExp(`^${escaped}$`);
+  regex = new RegExp(`^${escaped}$`, 'i');
+  regexCache.set(pattern, regex);
+  return regex;
 }
 
 export function isReadDenied(filePath: string): string | null {
diff --git a/src/extension/types.ts b/src/extension/types.ts
index 7c9a1e9..9707452 100644
--- a/src/extension/types.ts
+++ b/src/extension/types.ts
@@ -218,7 +218,6 @@ interface ReceiveMessagePayload {
   id?: string;
   project?: string;
   reason?: string;
-  [key: string]: unknown;
 }
 
 interface ReceiveChunkPayload {
@@ -253,7 +252,6 @@ interface SessionDeletedPayload {
 interface ErrorPayload {
   message: string;
   error?: string;
-  [key: string]: unknown;
 }
 
 interface ProviderListPayload extends ProviderListResult {}
@@ -275,7 +273,6 @@ interface FileSearchResultsPayload {
  */
 export interface SavedModelPayload {
   model?: string;
-  [key: string]: unknown;
 }
 
 interface ToolEventPayload {
@@ -303,13 +300,11 @@ interface MessageMetaPayload {
   requestId?: string;
   filePath?: string;
   meta?: Record<string, unknown>;
-  [key: string]: unknown;
 }
 
 interface ReasoningContentPayload {
   messageId?: string;
   content?: string;
-  [key: string]: unknown;
 }
 
 interface ReadFilePromptPayload {
@@ -318,7 +313,6 @@ interface ReadFilePromptPayload {
   type?: string;
   reason?: string;
   requestId?: string;
-  [key: string]: unknown;
 }
 
 interface SkillListPayload {
@@ -386,7 +380,6 @@ export interface ProjectInfo {
   project?: string;
   agent?: string;
   vcs?: Record<string, unknown>;
-  [key: string]: unknown;
 }
 
 /**
diff --git a/src/webview/App.tsx b/src/webview/App.tsx
index 3b6a53d..972a725 100644
--- a/src/webview/App.tsx
+++ b/src/webview/App.tsx
@@ -13,6 +13,7 @@ import { CommandItem } from './slashCommands';
 import { useChatState } from './hooks/useChatState';
 import { useModelManager } from './hooks/useModelManager';
 import { useMessageHandler } from './hooks/useMessageHandler';
+import { COLORS, flexRow, flexCenter, flexBetween, overlay, card, btnIcon, transitionColor, textSmall, textHeader, gap } from './styles';
 
 export default function App() {
   const {
@@ -52,14 +53,13 @@ export default function App() {
     processProviderList, tryAutoSelectModel,
   });
 
-  useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]);
+  useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, contextEvents]);
 
   useEffect(() => {
     postMessage({ type: 'webviewReady' });
   }, []);
 
   const handleSend = useCallback((prompt: string, context?: ContextPart[]) => {
-    console.log('[webview] Sending prompt:', prompt, 'context:', context?.length || 0, 'items');
     setBusy(true);
     setContextEvents([]);
     const firstWord = prompt.split(' ')[0];
@@ -194,40 +194,34 @@ export default function App() {
         <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 16px 12px', backgroundColor: '#181825', borderTop: '1px solid #313244' }}>
           <ModeSelector mode={mode} onChange={setMode} />
           <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
-            <button
-              onClick={() => setShowSessions(true)}
-              style={{
-                backgroundColor: 'transparent', border: 'none', color: '#585b70',
-                cursor: 'pointer', padding: 4, borderRadius: 4,
-                display: 'flex', alignItems: 'center', justifyContent: 'center',
-              }}
-              onMouseEnter={(e) => (e.currentTarget.style.color = '#cdd6f4')}
-              onMouseLeave={(e) => (e.currentTarget.style.color = '#585b70')}
-              title="Session History"
-            >
-              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
-                <circle cx="12" cy="12" r="10" />
-                <polyline points="12 6 12 12 16 14" />
-              </svg>
-            </button>
-            {providersLoaded ? (
-              <ModelSelector model={model} onChange={setModel} availableModels={availableModels.filter(m => !hiddenModels[m.id])} />
-            ) : (
-              <span style={{ fontSize: 11, color: '#585b70', padding: '4px 8px' }}>Loading...</span>
-            )}
-            <button
-              onClick={() => setShowProviders(true)}
-              style={{
-                backgroundColor: 'transparent', border: 'none',
-                color: showProviders ? '#89b4fa' : '#585b70',
-                cursor: 'pointer', padding: 4, borderRadius: 4,
-                display: 'flex', alignItems: 'center', justifyContent: 'center',
-                transition: 'color 0.15s',
-              }}
-              onMouseEnter={(e) => (e.currentTarget.style.color = '#cdd6f4')}
-              onMouseLeave={(e) => (e.currentTarget.style.color = showProviders ? '#89b4fa' : '#585b70')}
-              title="Provider Settings"
-            >
+              <button
+                onClick={() => setShowSessions(true)}
+                style={btnIcon}
+                onMouseEnter={(e) => (e.currentTarget.style.color = COLORS.text)}
+                onMouseLeave={(e) => (e.currentTarget.style.color = COLORS.textMuted)}
+                title="Session History"
+              >
+                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
+                  <circle cx="12" cy="12" r="10" />
+                  <polyline points="12 6 12 12 16 14" />
+                </svg>
+              </button>
+              {providersLoaded ? (
+                <ModelSelector model={model} onChange={setModel} availableModels={availableModels.filter(m => !hiddenModels[m.id])} />
+              ) : (
+                <span style={{ ...textSmall, padding: '4px 8px' }}>Loading...</span>
+              )}
+              <button
+                onClick={() => setShowProviders(true)}
+                style={{
+                  ...btnIcon,
+                  color: showProviders ? COLORS.accent : COLORS.textMuted,
+                  transition: 'color 0.15s',
+                }}
+                onMouseEnter={(e) => (e.currentTarget.style.color = COLORS.text)}
+                onMouseLeave={(e) => (e.currentTarget.style.color = showProviders ? COLORS.accent : COLORS.textMuted)}
+                title="Provider Settings"
+              >
               <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                 <circle cx="12" cy="12" r="3" />
                 <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
@@ -264,44 +258,36 @@ export default function App() {
       )}
 
       {readPermissionPrompt && (
-        <div style={{
-          position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
-          backgroundColor: 'rgba(0,0,0,0.6)', display: 'flex',
-          alignItems: 'center', justifyContent: 'center', zIndex: 1000,
-        }}>
-          <div style={{
-            backgroundColor: '#1e1e2e', border: '1px solid #45475a',
-            borderRadius: 12, padding: 24, maxWidth: 400, width: '90%',
-            boxShadow: '0 8px 32px rgba(0,0,0,0.4)',
-          }}>
-            <div style={{ fontSize: 14, fontWeight: 600, color: '#f38ba8', marginBottom: 8 }}>
+        <div style={overlay}>
+          <div style={card}>
+            <div style={{ ...textHeader, color: COLORS.red }}>
               Read Permission Required
             </div>
-            <div style={{ fontSize: 12, color: '#cdd6f4', marginBottom: 4 }}>
+            <div style={{ fontSize: 12, color: COLORS.text, marginBottom: 4 }}>
               The AI wants to read this file:
             </div>
             <div style={{
-              fontSize: 13, color: '#89b4fa', fontFamily: 'monospace',
+              fontSize: 13, color: COLORS.accent, fontFamily: 'monospace',
               padding: '8px 12px', backgroundColor: '#11111b',
               borderRadius: 6, marginBottom: 8, wordBreak: 'break-all',
             }}>
               {readPermissionPrompt.filePath}
             </div>
-            <div style={{ fontSize: 11, color: '#a6adc8', marginBottom: 16 }}>
+            <div style={{ ...textSmall, marginBottom: 16 }}>
               {readPermissionPrompt.reason}
             </div>
-            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
+            <div style={{ ...flexRow, justifyContent: 'flex-end', gap: 8 }}>
               <button onClick={() => handleRespondReadPermission('deny')} style={{
-                padding: '6px 14px', borderRadius: 6, border: '1px solid #45475a',
-                backgroundColor: 'transparent', color: '#cdd6f4', cursor: 'pointer', fontSize: 12,
+                padding: '6px 14px', borderRadius: 6, border: `1px solid ${COLORS.border}`,
+                backgroundColor: 'transparent', color: COLORS.text, cursor: 'pointer', fontSize: 12,
               }}>Deny</button>
               <button onClick={() => handleRespondReadPermission('allow')} style={{
                 padding: '6px 14px', borderRadius: 6, border: 'none',
-                backgroundColor: '#a6e3a1', color: '#11111b', cursor: 'pointer', fontSize: 12, fontWeight: 600,
+                backgroundColor: COLORS.green, color: '#11111b', cursor: 'pointer', fontSize: 12, fontWeight: 600,
               }}>Allow Once</button>
               <button onClick={() => handleRespondReadPermission('allow', true)} style={{
                 padding: '6px 14px', borderRadius: 6, border: 'none',
-                backgroundColor: '#89b4fa', color: '#11111b', cursor: 'pointer', fontSize: 12, fontWeight: 600,
+                backgroundColor: COLORS.accent, color: '#11111b', cursor: 'pointer', fontSize: 12, fontWeight: 600,
               }}>Always Allow</button>
             </div>
           </div>
diff --git a/src/webview/components/BottomInput.tsx b/src/webview/components/BottomInput.tsx
index 0655006..44c5304 100644
--- a/src/webview/components/BottomInput.tsx
+++ b/src/webview/components/BottomInput.tsx
@@ -2,6 +2,7 @@ import React, { useState, useRef, useEffect, useCallback } from 'react';
 import { ContextPart } from '../../extension/types';
 import { CommandItem } from '../slashCommands';
 import { SlashCommandPopup } from './SlashCommandPopup';
+import { COLORS, flexRow, flexCenter, btnIcon, textSmall, inputBase } from '../styles';
 
 interface FileResult {
   name: string;
@@ -40,6 +41,7 @@ export function BottomInput({ onSend, disabled, onSearchFiles, fileSearchResults
 
   // Close file search on outside click
   useEffect(() => {
+    if (!showFileSearch) return;
     const handler = (e: MouseEvent) => {
       if (fileSearchRef.current && !fileSearchRef.current.contains(e.target as Node)) {
         setShowFileSearch(false);
@@ -47,7 +49,7 @@ export function BottomInput({ onSend, disabled, onSearchFiles, fileSearchResults
     };
     document.addEventListener('mousedown', handler);
     return () => document.removeEventListener('mousedown', handler);
-  }, []);
+  }, [showFileSearch]);
 
   // Close slash popup on outside click
   useEffect(() => {
@@ -209,14 +211,14 @@ export function BottomInput({ onSend, disabled, onSearchFiles, fileSearchResults
             right: 16,
             maxHeight: 250,
             overflowY: 'auto',
-            backgroundColor: '#1e1e2e',
-            border: '1px solid #45475a',
+            backgroundColor: COLORS.bg,
+            border: `1px solid ${COLORS.border}`,
             borderRadius: 12,
             boxShadow: '0 -4px 20px rgba(0,0,0,0.4)',
             zIndex: 100,
           }}
         >
-          <div style={{ padding: '8px 12px', borderBottom: '1px solid #313244' }}>
+          <div style={{ padding: '8px 12px', borderBottom: `1px solid ${COLORS.bgHover}` }}>
             <input
               autoFocus
               value={fileSearchInput}
@@ -228,11 +230,11 @@ export function BottomInput({ onSend, disabled, onSearchFiles, fileSearchResults
               placeholder="Search files..."
               style={{
                 width: '100%',
-                backgroundColor: '#313244',
+                backgroundColor: COLORS.bgHover,
                 border: 'none',
                 borderRadius: 8,
                 padding: '8px 12px',
-                color: '#cdd6f4',
+                color: COLORS.text,
                 fontSize: 13,
                 outline: 'none',
                 boxSizing: 'border-box',
diff --git a/src/webview/components/ChatBubble.tsx b/src/webview/components/ChatBubble.tsx
index 8f01909..2671a12 100644
--- a/src/webview/components/ChatBubble.tsx
+++ b/src/webview/components/ChatBubble.tsx
@@ -3,6 +3,7 @@ import { ChatMessage } from '../../extension/types';
 import { Markdown } from './Markdown';
 import { getAgentColor } from './agentColors';
 import { ThinkingDots } from './ThinkingDots';
+import { COLORS, textNormal, textSmall, flexRow, gap } from '../styles';
 
 interface Props {
   message: ChatMessage;
@@ -76,7 +77,7 @@ export function ChatBubble({ message, onRevert }: Readonly<Props>) {
       }}
     >
       {message.role === 'assistant' && message.isStreaming && message.content.length < 20 && (
-        <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: '#89b4fa', fontSize: 12 }}>
+        <div style={{ ...flexRow, color: COLORS.accent, fontSize: 12, gap: 8 }}>
           <ThinkingDots />
           <span>Thinking...</span>
         </div>
@@ -85,13 +86,10 @@ export function ChatBubble({ message, onRevert }: Readonly<Props>) {
         <div style={{ marginBottom: 4 }}>
           <div
             onClick={() => setShowReasoning(!showReasoning)}
-            style={{
-              display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer',
-              fontSize: 11, color: '#6c7086', userSelect: 'none',
-            }}
+            style={{ ...flexRow, gap: 6, cursor: 'pointer', fontSize: 11, color: COLORS.textDim, userSelect: 'none' }}
           >
-            <span style={{ fontSize: 10, transition: 'transform 0.2s', transform: showReasoning ? 'rotate(90deg)' : 'rotate(0deg)' }}>▶</span>
-            <span>{message.isStreaming ? 'Reasoning...' : 'Reasoned for a few seconds'}</span>
+            <span>{showReasoning ? '▾' : '▸'}</span>
+            <span>Reasoning ({message.reasoning.length} chars)</span>
           </div>
           {showReasoning && (
             <div style={{
diff --git a/src/webview/components/DiffChanges.tsx b/src/webview/components/DiffChanges.tsx
index 34ca793..fa9f853 100644
--- a/src/webview/components/DiffChanges.tsx
+++ b/src/webview/components/DiffChanges.tsx
@@ -6,14 +6,20 @@ interface Props {
   variant?: 'default' | 'bars';
 }
 
+const TOTAL_BLOCKS = 5;
+const SMALL_DIFF_THRESHOLD = 5;
+const MIN_BLOCKS_THRESHOLD = 20;
+const RATIO_THRESHOLD = 4;
+const SMALL_ADD_LIMIT = 5;
+const SMALL_ADD_LIMIT_2 = 10;
+
 export function DiffChanges({ additions, deletions, variant = 'default' }: Props) {
   const total = additions + deletions;
 
   const blocks = useMemo(() => {
-    const TOTAL_BLOCKS = 5;
     if (additions === 0 && deletions === 0) return Array(TOTAL_BLOCKS).fill('neutral');
 
-    if (total < 5) {
+    if (total < SMALL_DIFF_THRESHOLD) {
       const added = additions > 0 ? 1 : 0;
       const deleted = deletions > 0 ? 1 : 0;
       return [
@@ -25,7 +31,7 @@ export function DiffChanges({ additions, deletions, variant = 'default' }: Props
 
     const ratio = additions > deletions ? additions / deletions : deletions / additions;
     let blocksForColors = TOTAL_BLOCKS;
-    if (total < 20 || ratio < 4) blocksForColors = TOTAL_BLOCKS - 1;
+    if (total < MIN_BLOCKS_THRESHOLD || ratio < RATIO_THRESHOLD) blocksForColors = TOTAL_BLOCKS - 1;
 
     const percentAdded = additions / total;
     const percentDeleted = deletions / total;
@@ -33,10 +39,10 @@ export function DiffChanges({ additions, deletions, variant = 'default' }: Props
     let added = additions > 0 ? Math.max(1, Math.round(percentAdded * blocksForColors)) : 0;
     let deleted = deletions > 0 ? Math.max(1, Math.round(percentDeleted * blocksForColors)) : 0;
 
-    if (additions > 0 && additions <= 5) added = Math.min(added, 1);
-    if (additions > 5 && additions <= 10) added = Math.min(added, 2);
-    if (deletions > 0 && deletions <= 5) deleted = Math.min(deleted, 1);
-    if (deletions > 5 && deletions <= 10) deleted = Math.min(deleted, 2);
+    if (additions > 0 && additions <= SMALL_ADD_LIMIT) added = Math.min(added, 1);
+    if (additions > SMALL_ADD_LIMIT && additions <= SMALL_ADD_LIMIT_2) added = Math.min(added, 2);
+    if (deletions > 0 && deletions <= SMALL_ADD_LIMIT) deleted = Math.min(deleted, 1);
+    if (deletions > SMALL_ADD_LIMIT && deletions <= SMALL_ADD_LIMIT_2) deleted = Math.min(deleted, 2);
 
     let totalAlloc = added + deleted;
     if (totalAlloc > blocksForColors) {
diff --git a/src/webview/components/Markdown.tsx b/src/webview/components/Markdown.tsx
index 2b05989..6e0207b 100644
--- a/src/webview/components/Markdown.tsx
+++ b/src/webview/components/Markdown.tsx
@@ -12,7 +12,10 @@ export function Markdown({ content }: Props) {
   const html = useMemo(() => {
     const raw = marked.parse(content, { gfm: true, breaks: true }) as string;
     const withCopyBtns = raw.replace(/<pre>/g, '<pre><button class="copy-btn">Copy</button>');
-    return DOMPurify.sanitize(withCopyBtns, { ADD_ATTR: ['class'] });
+    return DOMPurify.sanitize(withCopyBtns, {
+      ADD_ATTR: ['class'],
+      ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto):|[a-z]+:)/i,
+    });
   }, [content]);
 
   useEffect(() => {
diff --git a/src/webview/components/ProviderPopup.tsx b/src/webview/components/ProviderPopup.tsx
index 61153d1..87cf8aa 100644
--- a/src/webview/components/ProviderPopup.tsx
+++ b/src/webview/components/ProviderPopup.tsx
@@ -18,7 +18,7 @@ export function ProviderPopup({ onClose, onModelSelect, availableModels, hiddenM
   const [connected, setConnected] = useState<string[]>([]);
   const [saving, setSaving] = useState<Record<string, boolean>>({});
   const [messages, setMessages] = useState<Record<string, string>>({});
-  const apiKeyInputs = useRef<Record<string, string>>({});
+  const [apiKeyInputs, setApiKeyInputs] = useState<Record<string, string>>({});
   const popupRef = useRef<HTMLDivElement>(null);
 
   useEffect(() => {
@@ -56,12 +56,12 @@ export function ProviderPopup({ onClose, onModelSelect, availableModels, hiddenM
   }, {} as Record<string, typeof availableModels>);
 
   const handleSave = (providerId: string) => {
-    const key = apiKeyInputs.current[providerId];
+    const key = apiKeyInputs[providerId];
     if (!key) return;
     setSaving((prev) => ({ ...prev, [providerId]: true }));
     setMessages((prev) => ({ ...prev, [providerId]: 'Saving...' }));
     postMessage({ type: 'setApiKey', payload: { providerId, key } });
-    apiKeyInputs.current[providerId] = '';
+    setApiKeyInputs((prev) => ({ ...prev, [providerId]: '' }));
   };
 
   const handleRemove = (providerId: string) => {
@@ -315,8 +315,8 @@ export function ProviderPopup({ onClose, onModelSelect, availableModels, hiddenM
                           <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                             <input
                               type="password"
-                              value={apiKeyInputs.current[provider.id] || ''}
-                              onChange={(e) => { apiKeyInputs.current[provider.id] = e.target.value; }}
+                              value={apiKeyInputs[provider.id] || ''}
+                              onChange={(e) => { setApiKeyInputs((prev) => ({ ...prev, [provider.id]: e.target.value })); }}
                               placeholder={isConnected ? 'New API key...' : `${provider.name} API key`}
                               style={{
                                 flex: 1,
@@ -332,14 +332,14 @@ export function ProviderPopup({ onClose, onModelSelect, availableModels, hiddenM
                             />
                           <button
                             onClick={() => handleSave(provider.id)}
-                            disabled={saving[provider.id] || !apiKeyInputs.current[provider.id]}
+                            disabled={saving[provider.id] || !apiKeyInputs[provider.id]}
                             style={{
                               padding: '7px 14px',
                               borderRadius: 6,
                               border: 'none',
-                              backgroundColor: saving[provider.id] || !apiKeyInputs.current[provider.id] ? '#45475a' : '#7c3aed',
+                              backgroundColor: saving[provider.id] || !apiKeyInputs[provider.id] ? '#45475a' : '#7c3aed',
                               color: '#fff',
-                              cursor: saving[provider.id] || !apiKeyInputs.current[provider.id] ? 'not-allowed' : 'pointer',
+                              cursor: saving[provider.id] || !apiKeyInputs[provider.id] ? 'not-allowed' : 'pointer',
                               fontWeight: 500,
                               fontSize: 12,
                               whiteSpace: 'nowrap',
diff --git a/src/webview/components/SessionListPopup.tsx b/src/webview/components/SessionListPopup.tsx
index f3c3dcf..4fff909 100644
--- a/src/webview/components/SessionListPopup.tsx
+++ b/src/webview/components/SessionListPopup.tsx
@@ -36,8 +36,10 @@ export function SessionListPopup({ onClose, onSelect }: Props) {
 
   const handleDeleteOld = async (days: number) => {
     const now = Date.now();
-    const cutoff = now - days * 24 * 60 * 60 * 1000;
-    const oldSessions = sessions.filter(s => s.time?.created && s.time.created < cutoff);
+    const cutoff = days === 0 ? 0 : now - days * 24 * 60 * 60 * 1000;
+    const oldSessions = cutoff === 0
+      ? sessions
+      : sessions.filter(s => s.time?.created && s.time.created < cutoff);
     for (const s of oldSessions) {
       postMessage({ type: 'deleteSession', payload: { sessionId: s.id } });
     }
diff --git a/src/webview/components/SlashCommandPopup.tsx b/src/webview/components/SlashCommandPopup.tsx
index e1eb3d1..18694fb 100644
--- a/src/webview/components/SlashCommandPopup.tsx
+++ b/src/webview/components/SlashCommandPopup.tsx
@@ -51,9 +51,10 @@ export function SlashCommandPopup({ filter, skills, onSelect, onClose }: Readonl
   }, [filtered, selectedIndex, onSelect, onClose]);
 
   useEffect(() => {
+    if (filtered.length === 0) return;
     document.addEventListener('keydown', handleKeyDown);
     return () => document.removeEventListener('keydown', handleKeyDown);
-  }, [handleKeyDown]);
+  }, [handleKeyDown, filtered.length]);
 
   // Scroll selected into view
   useEffect(() => {
diff --git a/src/webview/hooks/useChatState.ts b/src/webview/hooks/useChatState.ts
index 5ddb571..2396b52 100644
--- a/src/webview/hooks/useChatState.ts
+++ b/src/webview/hooks/useChatState.ts
@@ -1,6 +1,12 @@
 import { useState, useRef, useCallback } from 'react';
 import { ChatMessage } from '../../extension/types';
 
+function genId(): string {
+  const arr = new Uint8Array(12);
+  crypto.getRandomValues(arr);
+  return Array.from(arr, (b) => b.toString(16).padStart(2, '0')).join('');
+}
+
 interface ContextEvent {
   id: string;
   name: string;
@@ -39,7 +45,7 @@ export function useChatState() {
       }
       const updated = [...prev];
       if (lastAssistantIdx < 0) {
-        const newId = Math.random().toString(36).slice(2);
+        const newId = genId();
         streamingMsgIdRef.current = newId;
         updated.push({
           role: 'assistant',
diff --git a/src/webview/hooks/useMessageHandler.ts b/src/webview/hooks/useMessageHandler.ts
index bfafe9f..0299601 100644
--- a/src/webview/hooks/useMessageHandler.ts
+++ b/src/webview/hooks/useMessageHandler.ts
@@ -3,6 +3,12 @@ import { ExtensionToWebviewMessage, ChatMessage, ProviderListResult, SavedModelP
 import { onMessage } from '../vscode-api';
 import { ModelItem } from './useModelManager';
 
+function genId(): string {
+  const arr = new Uint8Array(12);
+  crypto.getRandomValues(arr);
+  return Array.from(arr, (b) => b.toString(16).padStart(2, '0')).join('');
+}
+
 interface MessageHandlerState {
   // Chat state setters
   setMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>;
@@ -37,38 +43,39 @@ export function useMessageHandler(state: MessageHandlerState): void {
     setMessages, setBusy, setContextEvents,
     pendingChunkRef, chunkFlushTimerRef, streamingMsgIdRef, DEBOUNCE_MS,
     flushPendingChunk, cleanupStreaming,
-    setModel, setGitInfo, setAvailableModels, setHiddenModels,
+    setModel, setMode, setGitInfo, setAvailableModels, setHiddenModels,
     setProvidersLoaded, setSkills, setFileSearchResults, setFileSearchQuery,
     setRevertActive, setConfirmDialog, setReadPermissionPrompt,
     processProviderList, tryAutoSelectModel,
   } = state;
 
-  // Use refs for values that change and are read inside callbacks
-  const processProviderListRef = useRef(processProviderList);
-  processProviderListRef.current = processProviderList;
-  const tryAutoSelectRef = useRef(tryAutoSelectModel);
-  tryAutoSelectRef.current = tryAutoSelectModel;
+  const streamEndedRef = useRef(false);
 
   useEffect(() => {
+    const processProviderListRef = { current: processProviderList };
+    const tryAutoSelectRef = { current: tryAutoSelectModel };
+
     const unsubscribe = onMessage((msg: ExtensionToWebviewMessage) => {
       switch (msg.type) {
         case 'receiveMessage': {
+          streamEndedRef.current = false;
           const newMsg: ChatMessage = {
             role: msg.payload.role,
             content: msg.payload.content,
             timestamp: Date.now(),
-            id: Math.random().toString(36).slice(2),
+            id: genId(),
           };
           if (msg.payload.role === 'assistant') newMsg.isStreaming = true;
           setMessages((prev) => {
             const updated = [...prev, newMsg];
-            console.log('[webview] Messages updated, new count:', updated.length);
             return updated;
           });
           break;
         }
         case 'receiveChunk': {
+          if (streamEndedRef.current) break;
           if (msg.payload.fullContent) {
+            cleanupStreaming();
             flushPendingChunk();
             setMessages((prev) => {
               const updated = [...prev];
@@ -80,7 +87,7 @@ export function useMessageHandler(state: MessageHandlerState): void {
                   isStreaming: true,
                 };
               } else {
-                const newId = Math.random().toString(36).slice(2);
+                const newId = genId();
                 streamingMsgIdRef.current = newId;
                 updated.push({
                   role: 'assistant',
@@ -95,12 +102,16 @@ export function useMessageHandler(state: MessageHandlerState): void {
           } else {
             pendingChunkRef.current += msg.payload.content || '';
             if (!chunkFlushTimerRef.current) {
-              chunkFlushTimerRef.current = setTimeout(flushPendingChunk, DEBOUNCE_MS);
+              chunkFlushTimerRef.current = setTimeout(() => {
+                chunkFlushTimerRef.current = null;
+                if (!streamEndedRef.current) flushPendingChunk();
+              }, DEBOUNCE_MS);
             }
           }
           break;
         }
         case 'streamEnd': {
+          streamEndedRef.current = true;
           cleanupStreaming();
           flushPendingChunk();
           streamingMsgIdRef.current = null;
@@ -129,7 +140,7 @@ export function useMessageHandler(state: MessageHandlerState): void {
               role: m.info?.role === 'user' ? 'user' : 'assistant',
               content: m.parts?.map((p: any) => p.text || p.content || '').join('\n') || m.info?.content || '',
               timestamp: m.info?.time?.created || Date.now(),
-              id: m.info?.id || Math.random().toString(36).slice(2),
+              id: m.info?.id || genId(),
             }));
             setMessages(converted);
           }
@@ -154,7 +165,7 @@ export function useMessageHandler(state: MessageHandlerState): void {
         case 'error': {
           setMessages((prev) => [
             ...prev,
-            { role: 'assistant', content: `❌ ${msg.payload.message}`, timestamp: Date.now(), id: Math.random().toString(36).slice(2) },
+            { role: 'assistant', content: `❌ ${msg.payload.message}`, timestamp: Date.now(), id: genId() },
           ]);
           setBusy(false);
           break;
@@ -175,7 +186,7 @@ export function useMessageHandler(state: MessageHandlerState): void {
         }
         case 'toolEvent': {
           const event = msg.payload;
-          const eventId = event.id || `tool_${Date.now()}_${Math.random().toString(36).slice(2)}`;
+          const eventId = event.id || `tool_${Date.now()}_${genId()}`;
           const isContextTool = ['read', 'glob', 'grep', 'list', 'webfetch', 'websearch', 'search'].includes(event.name);
           if (isContextTool) {
             setContextEvents((prev) => {
@@ -215,7 +226,7 @@ export function useMessageHandler(state: MessageHandlerState): void {
               role: m.info?.role === 'user' ? 'user' : 'assistant',
               content: m.parts?.map((p: any) => p.text || p.content || '').join('\n') || m.info?.content || '',
               timestamp: m.info?.time?.created || Date.now(),
-              id: m.info?.id || Math.random().toString(36).slice(2),
+              id: m.info?.id || genId(),
             }));
             setMessages(converted);
           }
@@ -301,7 +312,13 @@ export function useMessageHandler(state: MessageHandlerState): void {
       cleanupStreaming();
       flushPendingChunk();
     };
-    // All deps are stable setter functions or refs - run once
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-  }, []);
+  }, [
+    setMessages, setBusy, setContextEvents,
+    pendingChunkRef, chunkFlushTimerRef, streamingMsgIdRef, DEBOUNCE_MS,
+    flushPendingChunk, cleanupStreaming,
+    setModel, setMode, setGitInfo, setAvailableModels, setHiddenModels,
+    setProvidersLoaded, setSkills, setFileSearchResults, setFileSearchQuery,
+    setRevertActive, setConfirmDialog, setReadPermissionPrompt,
+    processProviderList, tryAutoSelectModel,
+  ]);
 }
diff --git a/src/webview/vscode-api.ts b/src/webview/vscode-api.ts
index a73a1a3..b26dd21 100644
--- a/src/webview/vscode-api.ts
+++ b/src/webview/vscode-api.ts
@@ -1,7 +1,5 @@
 import { WebviewToExtensionMessage, ExtensionToWebviewMessage, EXTENSION_TO_WEBVIEW_TYPES } from '../extension/types';
 
-const VALID_EXTENSION_TYPES = EXTENSION_TO_WEBVIEW_TYPES;
-
 declare function acquireVsCodeApi(): any;
 const vscode = typeof acquireVsCodeApi === 'function' ? acquireVsCodeApi() : (globalThis as any).vscode;
 
@@ -12,11 +10,10 @@ export function postMessage(msg: WebviewToExtensionMessage) {
 export function onMessage(handler: (msg: ExtensionToWebviewMessage) => void): () => void {
   const wrapped = (event: MessageEvent) => {
     const msg = event.data;
-    if (!msg || typeof msg !== 'object' || !VALID_EXTENSION_TYPES.includes(msg.type)) {
+    if (!msg || typeof msg !== 'object' || !EXTENSION_TO_WEBVIEW_TYPES.includes(msg.type)) {
       console.warn('[webview] Ignored message with unknown type:', msg?.type);
       return;
     }
-    console.log('[webview] Received message from extension:', msg.type);
     handler(msg);
   };
   window.addEventListener('message', wrapped);
diff --git a/tsconfig.extension.json b/tsconfig.extension.json
index c9ee1ea..27cb805 100644
--- a/tsconfig.extension.json
+++ b/tsconfig.extension.json
@@ -15,5 +15,5 @@
     "types": ["node"]
   },
   "include": ["src/extension/**/*"],
-  "exclude": ["node_modules", ".vscode-test"]
+  "exclude": ["node_modules", ".vscode-test", "**/*.test.ts"]
 }

diff --git "a/C:\\Projects\\opencode_sidebar\\.cursorrules" "b/C:\\Projects\\opencode_sidebar\\.cursorrules" new file mode 100644 index 0000000..0a3e5c8 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\.cursorrules" @@ -0,0 +1,38 @@ +<!-- code-review-graph MCP tools --> +## MCP Tools: code-review-graph + +**IMPORTANT: This project has a knowledge graph. ALWAYS use the +code-review-graph MCP tools BEFORE using Grep/Glob/Read to explore +the codebase.** The graph is faster, cheaper (fewer tokens), and gives +you structural context (callers, dependents, test coverage) that file +scanning cannot. + +### When to use graph tools FIRST + +- **Exploring code**: `semantic_search_nodes` or `query_graph` instead of Grep +- **Understanding impact**: `get_impact_radius` instead of manually tracing imports +- **Code review**: `detect_changes` + `get_review_context` instead of reading entire files +- **Finding relationships**: `query_graph` with callers_of/callees_of/imports_of/tests_for +- **Architecture questions**: `get_architecture_overview` + `list_communities` + +Fall back to Grep/Glob/Read **only** when the graph doesn't cover what you need. + +### Key Tools + +| Tool | Use when | +|------|----------| +| `detect_changes` | Reviewing code changes  gives risk-scored analysis | +| `get_review_context` | Need source snippets for review  token-efficient | +| `get_impact_radius` | Understanding blast radius of a change | +| `get_affected_flows` | Finding which execution paths are impacted | +| `query_graph` | Tracing callers, callees, imports, tests, dependencies | +| `semantic_search_nodes` | Finding functions/classes by name or keyword | +| `get_architecture_overview` | Understanding high-level codebase structure | +| `refactor_tool` | Planning renames, finding dead code | + +### Workflow + +1. The graph auto-updates on file changes (via hooks). +2. Use `detect_changes` for code review. +3. Use `get_affected_flows` to understand impact. +4. Use `query_graph` pattern="tests_for" to check coverage.
diff --git "a/C:\\Projects\\opencode_sidebar\\.mcp.json" "b/C:\\Projects\\opencode_sidebar\\.mcp.json" new file mode 100644 index 0000000..c942808 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\.mcp.json" @@ -0,0 +1,12 @@ +{ +  "mcpServers": { +    "code-review-graph": { +      "command": "uvx", +      "args": [ +        "code-review-graph", +        "serve" +      ], +      "type": "stdio" +    } +  } +}
diff --git "a/C:\\Projects\\opencode_sidebar\\.opencode.json" "b/C:\\Projects\\opencode_sidebar\\.opencode.json" new file mode 100644 index 0000000..81d79fa --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\.opencode.json" @@ -0,0 +1,13 @@ +{ +  "mcpServers": { +    "code-review-graph": { +      "command": "uvx", +      "args": [ +        "code-review-graph", +        "serve" +      ], +      "type": "stdio", +      "env": [] +    } +  } +}
diff --git "a/C:\\Projects\\opencode_sidebar\\.windsurfrules" "b/C:\\Projects\\opencode_sidebar\\.windsurfrules" new file mode 100644 index 0000000..0a3e5c8 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\.windsurfrules" @@ -0,0 +1,38 @@ +<!-- code-review-graph MCP tools --> +## MCP Tools: code-review-graph + +**IMPORTANT: This project has a knowledge graph. ALWAYS use the +code-review-graph MCP tools BEFORE using Grep/Glob/Read to explore +the codebase.** The graph is faster, cheaper (fewer tokens), and gives +you structural context (callers, dependents, test coverage) that file +scanning cannot. + +### When to use graph tools FIRST + +- **Exploring code**: `semantic_search_nodes` or `query_graph` instead of Grep +- **Understanding impact**: `get_impact_radius` instead of manually tracing imports +- **Code review**: `detect_changes` + `get_review_context` instead of reading entire files +- **Finding relationships**: `query_graph` with callers_of/callees_of/imports_of/tests_for +- **Architecture questions**: `get_architecture_overview` + `list_communities` + +Fall back to Grep/Glob/Read **only** when the graph doesn't cover what you need. + +### Key Tools + +| Tool | Use when | +|------|----------| +| `detect_changes` | Reviewing code changes  gives risk-scored analysis | +| `get_review_context` | Need source snippets for review  token-efficient | +| `get_impact_radius` | Understanding blast radius of a change | +| `get_affected_flows` | Finding which execution paths are impacted | +| `query_graph` | Tracing callers, callees, imports, tests, dependencies | +| `semantic_search_nodes` | Finding functions/classes by name or keyword | +| `get_architecture_overview` | Understanding high-level codebase structure | +| `refactor_tool` | Planning renames, finding dead code | + +### Workflow + +1. The graph auto-updates on file changes (via hooks). +2. Use `detect_changes` for code review. +3. Use `get_affected_flows` to understand impact. +4. Use `query_graph` pattern="tests_for" to check coverage.
diff --git "a/C:\\Projects\\opencode_sidebar\\CLAUDE.md" "b/C:\\Projects\\opencode_sidebar\\CLAUDE.md" new file mode 100644 index 0000000..0a3e5c8 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\CLAUDE.md" @@ -0,0 +1,38 @@ +<!-- code-review-graph MCP tools --> +## MCP Tools: code-review-graph + +**IMPORTANT: This project has a knowledge graph. ALWAYS use the +code-review-graph MCP tools BEFORE using Grep/Glob/Read to explore +the codebase.** The graph is faster, cheaper (fewer tokens), and gives +you structural context (callers, dependents, test coverage) that file +scanning cannot. + +### When to use graph tools FIRST + +- **Exploring code**: `semantic_search_nodes` or `query_graph` instead of Grep +- **Understanding impact**: `get_impact_radius` instead of manually tracing imports +- **Code review**: `detect_changes` + `get_review_context` instead of reading entire files +- **Finding relationships**: `query_graph` with callers_of/callees_of/imports_of/tests_for +- **Architecture questions**: `get_architecture_overview` + `list_communities` + +Fall back to Grep/Glob/Read **only** when the graph doesn't cover what you need. + +### Key Tools + +| Tool | Use when | +|------|----------| +| `detect_changes` | Reviewing code changes  gives risk-scored analysis | +| `get_review_context` | Need source snippets for review  token-efficient | +| `get_impact_radius` | Understanding blast radius of a change | +| `get_affected_flows` | Finding which execution paths are impacted | +| `query_graph` | Tracing callers, callees, imports, tests, dependencies | +| `semantic_search_nodes` | Finding functions/classes by name or keyword | +| `get_architecture_overview` | Understanding high-level codebase structure | +| `refactor_tool` | Planning renames, finding dead code | + +### Workflow + +1. The graph auto-updates on file changes (via hooks). +2. Use `detect_changes` for code review. +3. Use `get_affected_flows` to understand impact. +4. Use `query_graph` pattern="tests_for" to check coverage.
diff --git "a/C:\\Projects\\opencode_sidebar\\GEMINI.md" "b/C:\\Projects\\opencode_sidebar\\GEMINI.md" new file mode 100644 index 0000000..0a3e5c8 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\GEMINI.md" @@ -0,0 +1,38 @@ +<!-- code-review-graph MCP tools --> +## MCP Tools: code-review-graph + +**IMPORTANT: This project has a knowledge graph. ALWAYS use the +code-review-graph MCP tools BEFORE using Grep/Glob/Read to explore +the codebase.** The graph is faster, cheaper (fewer tokens), and gives +you structural context (callers, dependents, test coverage) that file +scanning cannot. + +### When to use graph tools FIRST + +- **Exploring code**: `semantic_search_nodes` or `query_graph` instead of Grep +- **Understanding impact**: `get_impact_radius` instead of manually tracing imports +- **Code review**: `detect_changes` + `get_review_context` instead of reading entire files +- **Finding relationships**: `query_graph` with callers_of/callees_of/imports_of/tests_for +- **Architecture questions**: `get_architecture_overview` + `list_communities` + +Fall back to Grep/Glob/Read **only** when the graph doesn't cover what you need. + +### Key Tools + +| Tool | Use when | +|------|----------| +| `detect_changes` | Reviewing code changes  gives risk-scored analysis | +| `get_review_context` | Need source snippets for review  token-efficient | +| `get_impact_radius` | Understanding blast radius of a change | +| `get_affected_flows` | Finding which execution paths are impacted | +| `query_graph` | Tracing callers, callees, imports, tests, dependencies | +| `semantic_search_nodes` | Finding functions/classes by name or keyword | +| `get_architecture_overview` | Understanding high-level codebase structure | +| `refactor_tool` | Planning renames, finding dead code | + +### Workflow + +1. The graph auto-updates on file changes (via hooks). +2. Use `detect_changes` for code review. +3. Use `get_affected_flows` to understand impact. +4. Use `query_graph` pattern="tests_for" to check coverage.
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\AuthService.test.ts" "b/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\AuthService.test.ts" new file mode 100644 index 0000000..587c656 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\AuthService.test.ts" @@ -0,0 +1,22 @@ +import { describe, it, expect, vi } from 'vitest'; +import { AuthService } from './AuthService'; + +describe('AuthService', () => { +  const mockContext = { +    secrets: { +      get: vi.fn().mockResolvedValue(undefined), +      store: vi.fn().mockResolvedValue(undefined), +      delete: vi.fn().mockResolvedValue(undefined), +    }, +  } as any; + +  const mockOpencode = { +    url: 'http://localhost:1234', +    authHeader: { Authorization: 'Basic abc' }, +  } as any; + +  it('should be instantiable', () => { +    const authService = new AuthService(mockOpencode, mockContext); +    expect(authService).toBeDefined(); +  }); +}); \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\EventDispatcher.test.ts" "b/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\EventDispatcher.test.ts" new file mode 100644 index 0000000..e057528 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\EventDispatcher.test.ts" @@ -0,0 +1,248 @@ +import { describe, it, expect } from 'vitest'; +import { EventDispatcher } from './EventDispatcher'; + +describe('EventDispatcher', () => { +  const createDispatcher = (callbacks: any = {}) => new EventDispatcher(callbacks); + +  it('should call onContent for message.part.delta with field text', () => { +    let capturedContent = ''; +    const dispatcher = createDispatcher({ +      onContent: (text: string) => { capturedContent = text; }, +    }); + +    dispatcher.dispatch({ +      type: 'message.part.delta', +      properties: { field: 'text', delta: 'Hello world' }, +    }, 'session-1'); + +    expect(capturedContent).toBe('Hello world'); +  }); + +  it('should call onReasoning for reasoning delta', () => { +    let capturedReasoning = ''; +    const dispatcher = createDispatcher({ +      onReasoning: (text: string) => { capturedReasoning = text; }, +    }); + +    dispatcher.dispatch({ +      type: 'message.part.updated', +      properties: { +        part: { id: 'p1', type: 'reasoning' }, +      }, +    }, 'session-1'); + +    dispatcher.resetSession('session-1'); + +    dispatcher.dispatch({ +      type: 'message.part.updated', +      properties: { +        part: { id: 'p1', type: 'reasoning' }, +      }, +    }, 'session-1'); + +    dispatcher.dispatch({ +      type: 'message.part.delta', +      properties: { field: 'text', delta: 'Thinking...', partID: 'p1' }, +    }, 'session-1'); + +    expect(capturedReasoning).toBe('Thinking...'); +  }); + +  it('should call onError for session.error', () => { +    let capturedError = ''; +    const dispatcher = createDispatcher({ +      onError: (err: string) => { capturedError = err; }, +    }); + +    dispatcher.dispatch({ +      type: 'session.error', +      properties: { error: { message: 'Something went wrong' } }, +    }, 'session-1'); + +    expect(capturedError).toBe('Something went wrong'); +  }); + +  it('should call onError with unknown for missing message', () => { +    let capturedError = ''; +    const dispatcher = createDispatcher({ +      onError: (err: string) => { capturedError = err; }, +    }); + +    dispatcher.dispatch({ +      type: 'session.error', +      properties: {}, +    }, 'session-1'); + +    expect(capturedError).toBe('Unknown error'); +  }); + +  it('should track part types in sessionPartTypes', () => { +    const dispatcher = createDispatcher({}); + +    dispatcher.dispatch({ +      type: 'message.part.updated', +      properties: { +        part: { id: 'part-1', type: 'tool_call', name: 'read', args: {} }, +      }, +    }, 'session-abc'); + +    dispatcher.dispatch({ +      type: 'message.part.updated', +      properties: { +        part: { id: 'part-2', type: 'tool', tool: 'read' }, +      }, +    }, 'session-abc'); + +    dispatcher.resetSession('session-abc'); +    dispatcher.clearSession('session-abc'); +  }); + +  it('should call onDiffs for message.updated with summary diffs', () => { +    let capturedDiffs: any[] = []; +    const dispatcher = createDispatcher({ +      onDiffs: (diffs: any[]) => { capturedDiffs = diffs; }, +    }); + +    dispatcher.dispatch({ +      type: 'message.updated', +      properties: { +        info: { +          summary: { +            diffs: [ +              { path: 'file1.ts', content: '+1\n-1' }, +              { path: 'file2.ts', added: 5, deleted: 2 }, +            ], +          }, +        }, +      }, +    }, 'session-1'); + +    expect(capturedDiffs).toHaveLength(2); +    expect(capturedDiffs[0].path).toBe('file1.ts'); +    expect(capturedDiffs[1].path).toBe('file2.ts'); +  }); + +  it('should call onDiffs for session.diff', () => { +    let capturedDiffs: any[] = []; +    const dispatcher = createDispatcher({ +      onDiffs: (diffs: any[]) => { capturedDiffs = diffs; }, +    }); + +    dispatcher.dispatch({ +      type: 'session.diff', +      properties: { +        diff: [ +          { path: 'changed.ts', content: '+1' }, +        ], +      }, +    }, 'session-1'); + +    expect(capturedDiffs).toHaveLength(1); +    expect(capturedDiffs[0].path).toBe('changed.ts'); +  }); + +  it('should call onToolEvent for permission.asked', () => { +    let capturedEvent: any = null; +    const dispatcher = createDispatcher({ +      onToolEvent: (event: any) => { capturedEvent = event; }, +    }); + +    dispatcher.dispatch({ +      type: 'permission.asked', +      properties: { +        id: 'perm-123', +        permission: 'read', +        patterns: ['**/.env'], +        sessionId: 'sess-1', +      }, +    }, 'session-1'); + +    expect(capturedEvent).not.toBeNull(); +    expect(capturedEvent.type).toBe('permission'); +    expect(capturedEvent.name).toBe('permission'); +    expect(capturedEvent.meta?.permType).toBe('read'); +  }); + +  it('should handle session.status idle', () => { +    const dispatcher = createDispatcher({}); + +    dispatcher.dispatch({ +      type: 'session.status', +      properties: { status: { type: 'idle' } }, +    }, 'session-idle'); + +    dispatcher.clearSession('session-idle'); +  }); +}); + +describe('EventDispatcher - tool events', () => { +  it('should emit tool_call event', () => { +    let toolName = ''; +    let toolArgs: any = null; +    const dispatcher = new EventDispatcher({ +      onToolCall: (name: string, args: any) => { +        toolName = name; +        toolArgs = args; +      }, +    }); + +    dispatcher.dispatch({ +      type: 'message.part.updated', +      properties: { +        part: { +          id: 'call-1', +          type: 'tool_call', +          name: 'grep', +          args: { pattern: 'TODO' }, +        }, +      }, +    }, 'session-1'); + +    expect(toolName).toBe('grep'); +    expect(toolArgs.pattern).toBe('TODO'); +  }); + +  it('should emit tool_result completed', () => { +    let event: any = null; +    const dispatcher = new EventDispatcher({ +      onToolEvent: (e) => { event = e; }, +    }); + +    dispatcher.dispatch({ +      type: 'message.part.updated', +      properties: { +        part: { +          id: 'result-1', +          type: 'tool', +          tool: 'task', +          state: { status: 'completed', result: 'done', metadata: { sessionId: 's-1' } }, +        }, +      }, +    }, 'session-1'); + +    expect(event.status).toBe('completed'); +    expect(event.meta?.sessionId).toBe('s-1'); +  }); + +  it('should emit tool_result failed', () => { +    let event: any = null; +    const dispatcher = new EventDispatcher({ +      onToolEvent: (e) => { event = e; }, +      onError: () => {}, +    }); + +    dispatcher.dispatch({ +      type: 'message.part.updated', +      properties: { +        part: { +          id: 'fail-1', +          type: 'tool', +          tool: 'read', +          state: { status: 'failed', error: 'File not found' }, +        }, +      }, +    }, 'session-1'); + +    expect(event.status).toBe('failed'); +  }); +}); \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\SseStream.test.ts" "b/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\SseStream.test.ts" new file mode 100644 index 0000000..52f8317 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\extension\\services\\SseStream.test.ts" @@ -0,0 +1,111 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { SseStream } from './SseStream'; + +describe('SseStream', () => { +  const mockFetch = vi.fn(); + +  beforeEach(() => { +    vi.stubGlobal('fetch', mockFetch); +  }); + +  it('should parse data: lines', async () => { +    const encoder = new TextEncoder(); +    const mockReader = { +      read: vi.fn() +        .mockResolvedValueOnce({ done: false, value: encoder.encode('data: {"type":"test","properties":{}}\n\n') }) +        .mockResolvedValueOnce({ done: true }), +    }; + +    mockFetch.mockResolvedValue({ +      ok: true, +      body: { getReader: () => mockReader }, +    }); + +    const events: any[] = []; +    const stream = new SseStream(); +    await stream.connect('http://localhost/event', {}, (e) => events.push(e), { aborted: false } as any); + +    expect(events).toHaveLength(1); +    expect(events[0].type).toBe('test'); +  }); + +  it('should handle multi-line data', async () => { +    const encoder = new TextEncoder(); +    const mockReader = { +      read: vi.fn() +        .mockResolvedValueOnce({ done: false, value: encoder.encode('data: {"type":"msg","properties":{"part":{"id":"1","type":"text"}}}\ndata: {"type":"msg","properties":{"part":{"id":"1","type":"text","result":"done"}}}\n\n') }) +        .mockResolvedValueOnce({ done: true }), +    }; + +    mockFetch.mockResolvedValue({ +      ok: true, +      body: { getReader: () => mockReader }, +    }); + +    const events: any[] = []; +    const stream = new SseStream(); +    await stream.connect('http://localhost/event', {}, (e) => events.push(e), { aborted: false } as any); + +    expect(events).toHaveLength(2); +  }); + +  it('should handle event: prefix for event type', async () => { +    const encoder = new TextEncoder(); +    const mockReader = { +      read: vi.fn() +        .mockResolvedValueOnce({ done: false, value: encoder.encode('event: message\ndata: {"type":"test","properties":{}}\n\n') }) +        .mockResolvedValueOnce({ done: true }), +    }; + +    mockFetch.mockResolvedValue({ +      ok: true, +      body: { getReader: () => mockReader }, +    }); + +    const events: any[] = []; +    const stream = new SseStream(); +    await stream.connect('http://localhost/event', {}, (e) => events.push(e), { aborted: false } as any); + +    expect(events).toHaveLength(1); +    expect(events[0].type).toBe('test'); +  }); + +  it('should handle retry: directive', async () => { +    const encoder = new TextEncoder(); +    const mockReader = { +      read: vi.fn() +        .mockResolvedValueOnce({ done: false, value: encoder.encode('retry: 5000\ndata: {"type":"test","properties":{}}\n\n') }) +        .mockResolvedValueOnce({ done: true }), +    }; + +    mockFetch.mockResolvedValue({ +      ok: true, +      body: { getReader: () => mockReader }, +    }); + +    const stream = new SseStream(); +    await stream.connect('http://localhost/event', {}, () => {}, { aborted: false } as any); +  }); + +  it('should retry on failure', async () => { +    const encoder = new TextEncoder(); +    let attempts = 0; +    const mockReader = { +      read: vi.fn().mockImplementation(() => { +        attempts++; +        if (attempts < 2) throw new Error('Connection reset'); +        return { done: true }; +      }), +    }; + +    mockFetch.mockResolvedValue({ +      ok: true, +      body: { getReader: () => mockReader }, +    }); + +    const stream = new SseStream(); +    stream.maxRetries = 1; + +    await stream.connect('http://localhost/event', {}, () => {}, { aborted: false } as any); +  }); +}); \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\extension\\integration\\MessageProtocol.test.ts" "b/C:\\Projects\\opencode_sidebar\\src\\extension\\integration\\MessageProtocol.test.ts" new file mode 100644 index 0000000..0d894c0 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\extension\\integration\\MessageProtocol.test.ts" @@ -0,0 +1,174 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { ExtensionToWebviewMessage, WebviewToExtensionMessage } from '../types'; + +describe('Extension-Webview Message Protocol', () => { +  describe('Message Type Definitions', () => { +    it('should have all required webview-to-extension message types', () => { +      const requiredTypes = [ +        'sendMessage', +        'acceptReview', +        'rejectReview', +        'clearChat', +        'abort', +        'getSessions', +        'loadSession', +        'deleteSession', +        'switchAgent', +        'listProviders', +        'setApiKey', +        'removeApiKey', +        'searchFiles', +        'getSavedModel', +        'saveModel', +        'revertMessage', +        'unrevert', +        'respondPermission', +        'respondReadPermission', +        'openDiff', +        'runCommand', +        'loadSkills', +        'webviewReady', +      ]; + +      const typeMap: Record<string, boolean> = {}; +      for (const t of requiredTypes) { +        typeMap[t] = true; +      } + +      expect(typeMap['sendMessage']).toBe(true); +      expect(typeMap['webviewReady']).toBe(true); +    }); + +    it('should have all required extension-to-webview message types', () => { +      const requiredTypes = [ +        'receiveMessage', +        'receiveChunk', +        'streamEnd', +        'reviewReady', +        'reviewResolved', +        'status', +        'gitInfo', +        'projectInfo', +        'sessionList', +        'sessionLoaded', +        'sessionDeleted', +        'agentList', +        'error', +        'providerList', +        'providerUpdated', +        'fileSearchResults', +        'savedModel', +        'toolEvent', +        'revertResult', +        'messageMeta', +        'reasoningContent', +        'readFilePrompt', +        'skillList', +      ]; + +      expect(requiredTypes.length).toBeGreaterThan(20); +    }); +  }); + +  describe('Message Payload Validation', () => { +    it('should validate sendMessage payload structure', () => { +      const validPayload: WebviewToExtensionMessage['payload'] = { +        prompt: 'Hello world', +        model: 'openai/gpt-4', +        mode: 'Build', +        context: [ +          { type: 'file', path: 'src/index.ts' }, +        ], +      }; + +      expect(validPayload.prompt).toBeDefined(); +      expect(validPayload.mode).toBeDefined(); +    }); + +    it('should validate toolEvent payload structure', () => { +      const validPayload: ExtensionToWebviewMessage['payload'] = { +        id: 'tool-123', +        type: 'tool_call', +        name: 'read', +        status: 'running', +        content: 'Reading file...', +        meta: { path: 'src/index.ts' }, +      }; + +      expect(validPayload.type).toBe('tool_call'); +      expect(validPayload.status).toBe('running'); +    }); + +    it('should validate receiveChunk payload structure', () => { +      const validPayload: ExtensionToWebviewMessage['payload'] = { +        content: 'Hello', +        fullContent: 'Hello world', +      }; + +      expect(validPayload.content).toBeDefined(); +    }); +  }); + +  describe('Session Flow', () => { +    it('should track session lifecycle', () => { +      const sessionStates: string[] = []; + +      sessionStates.push('created'); +      sessionStates.push('active'); +      sessionStates.push('idle'); + +      expect(sessionStates).toContain('created'); +      expect(sessionStates).toContain('idle'); +    }); +  }); + +  describe('Streaming Flow', () => { +    it('should handle streaming message sequence', () => { +      const messages: string[] = []; + +      messages.push('receiveMessage:assistant:empty'); +      messages.push('receiveChunk:Hello'); +      messages.push('receiveChunk: world'); +      messages.push('streamEnd:Hello world'); + +      expect(messages[0]).toContain('receiveMessage'); +      expect(messages[3]).toContain('streamEnd'); +    }); + +    it('should handle tool events during streaming', () => { +      const events: any[] = []; + +      events.push({ type: 'tool_call', name: 'read', status: 'running' }); +      events.push({ type: 'file_read', name: 'read', status: 'completed' }); +      events.push({ type: 'tool_result', name: 'read', status: 'completed' }); + +      expect(events[0].status).toBe('running'); +      expect(events[1].type).toBe('file_read'); +    }); +  }); + +  describe('Permission Flow', () => { +    it('should handle permission request flow', () => { +      const permission = { +        id: 'perm-123', +        type: 'read', +        patterns: ['**/.env'], +        response: 'allow', +        remember: true, +      }; + +      expect(permission.response).toBe('allow'); +      expect(permission.remember).toBe(true); +    }); + +    it('should handle read permission request flow', () => { +      const readPerm = { +        filePath: 'config/.env', +        response: 'deny', +        requestId: 'req-456', +      }; + +      expect(readPerm.response).toBe('deny'); +    }); +  }); +}); \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\extension\\integration\\SidebarProvider.test.ts" "b/C:\\Projects\\opencode_sidebar\\src\\extension\\integration\\SidebarProvider.test.ts" new file mode 100644 index 0000000..d90b56f --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\extension\\integration\\SidebarProvider.test.ts" @@ -0,0 +1,122 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SidebarProvider } from '../providers/SidebarProvider'; +import * as vscode from 'vscode'; + +vi.mock('vscode', () => ({ +  workspace: { +    workspaceFolders: [{ uri: { fsPath: '/test/workspace' } }], +    fs: { +      readFile: vi.fn(), +      readDirectory: vi.fn(), +    }, +  }, +  window: { +    registerWebviewViewProvider: vi.fn(), +    showTextDocument: vi.fn(), +  }, +  Uri: { +    joinPath: vi.fn(), +    file: vi.fn(), +  }, +  EventEmitter: vi.fn(), +})); + +describe('SidebarProvider Message Handling', () => { +  let provider: SidebarProvider; +  let mockContext: any; +  let extensionUri: vscode.Uri; + +  beforeEach(() => { +    mockContext = { +      extensionUri: { fsPath: '/test/ext' }, +      secrets: { +        get: vi.fn().mockResolvedValue(undefined), +        store: vi.fn().mockResolvedValue(undefined), +        delete: vi.fn().mockResolvedValue(undefined), +      }, +      subscriptions: [], +    }; +    extensionUri = { fsPath: '/test/ext' } as any; +    provider = new SidebarProvider(extensionUri, mockContext); +  }); + +  describe('Message Type Validation', () => { +    it('should accept valid message types', () => { +      const validTypes = [ +        'sendMessage', +        'searchFiles', +        'listProviders', +        'setApiKey', +        'loadSkills', +      ]; + +      for (const type of validTypes) { +        expect(validTypes).toContain(type); +      } +    }); +  }); + +  describe('Payload Validation', () => { +    it('should validate searchFiles payload', () => { +      const isValid = provider.validatePayload('searchFiles', { query: '*.ts' }); +      expect(isValid).toBe(true); +    }); + +    it('should reject searchFiles with missing query', () => { +      const isValid = provider.validatePayload('searchFiles', {}); +      expect(isValid).toBe(false); +    }); + +    it('should validate setApiKey payload', () => { +      const isValid = provider.validatePayload('setApiKey', { providerId: 'openai', key: 'sk-123' }); +      expect(isValid).toBe(true); +    }); + +    it('should reject setApiKey with missing fields', () => { +      const isValid = provider.validatePayload('setApiKey', { providerId: 'openai' }); +      expect(isValid).toBe(false); +    }); + +    it('should validate runCommand payload', () => { +      const isValid = provider.validatePayload('runCommand', { command: 'init' }); +      expect(isValid).toBe(true); +    }); + +    it('should validate loadSession payload', () => { +      const isValid = provider.validatePayload('loadSession', { sessionId: 'sess-123' }); +      expect(isValid).toBe(true); +    }); +  }); + +  describe('Message Type Mapping', () => { +    it('should have handlers for all WEBVIEW_TO_EXTENSION_TYPES', () => { +      const handlers = [ +        'searchFiles', +        'getSavedModel', +        'saveModel', +        'revertMessage', +        'unrevert', +        'respondPermission', +        'respondReadPermission', +        'loadSkills', +        'runCommand', +        'webviewReady', +        'sendMessage', +        'acceptReview', +        'rejectReview', +        'clearChat', +        'abort', +        'getSessions', +        'loadSession', +        'deleteSession', +        'switchAgent', +        'listProviders', +        'setApiKey', +        'removeApiKey', +        'openDiff', +      ]; + +      expect(handlers.length).toBe(23); +    }); +  }); +}); \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\extension\\utils\\diffUtils.ts" "b/C:\\Projects\\opencode_sidebar\\src\\extension\\utils\\diffUtils.ts" new file mode 100644 index 0000000..db9f577 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\extension\\utils\\diffUtils.ts" @@ -0,0 +1,20 @@ +export interface NormalizedDiff { +  path: string; +  added: number; +  deleted: number; +  content: string; +} + +export function normalizeDiff(d: any): NormalizedDiff { +  const path = d.path || d.file || ''; +  const content = d.content || d.patch || ''; +  let added = typeof d.added === 'number' ? d.added : 0; +  let deleted = typeof d.deleted === 'number' ? d.deleted : 0; +  if (added === 0 && deleted === 0 && content) { +    for (const line of content.split('\n')) { +      if (line.startsWith('+') && !line.startsWith('+++')) added++; +      if (line.startsWith('-') && !line.startsWith('---')) deleted++; +    } +  } +  return { path, added, deleted, content }; +} \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\extension\\utils\\diffUtils.test.ts" "b/C:\\Projects\\opencode_sidebar\\src\\extension\\utils\\diffUtils.test.ts" new file mode 100644 index 0000000..a5c3dd3 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\extension\\utils\\diffUtils.test.ts" @@ -0,0 +1,79 @@ +import { describe, it, expect } from 'vitest'; +import { normalizeDiff, NormalizedDiff } from './diffUtils'; + +describe('normalizeDiff', () => { +  it('should handle diff with path and content', () => { +    const input = { +      path: 'src/index.ts', +      content: '+1\n-2', +    }; +    const result = normalizeDiff(input); +    expect(result.path).toBe('src/index.ts'); +    expect(result.added).toBe(1); +    expect(result.deleted).toBe(1); +  }); + +  it('should handle diff with file field', () => { +    const input = { +      file: 'src/app.ts', +      content: '+5\n-3', +    }; +    const result = normalizeDiff(input); +    expect(result.path).toBe('src/app.ts'); +  }); + +  it('should use patch field as content', () => { +    const input = { +      path: 'test.js', +      patch: '+10\n-5', +    }; +    const result = normalizeDiff(input); +    expect(result.content).toBe('+10\n-5'); +  }); + +  it('should use provided added/deleted counts', () => { +    const input = { +      path: 'file.ts', +      added: 20, +      deleted: 10, +      content: '', +    }; +    const result = normalizeDiff(input); +    expect(result.added).toBe(20); +    expect(result.deleted).toBe(10); +  }); + +  it('should count lines when added/deleted not provided', () => { +    const input = { +      path: 'test.ts', +      content: '+const a = 1;\n+const b = 2;\n-const c = 3;\n-const d = 4;\n+const e = 5;\n', +    }; +    const result = normalizeDiff(input); +    expect(result.added).toBe(3); +    expect(result.deleted).toBe(2); +  }); + +  it('should ignore +++ and --- headers', () => { +    const input = { +      path: 'f.ts', +      content: '+++ b/src/f.ts\n- const a;\n+ const a = 1;\n', +    }; +    const result = normalizeDiff(input); +    expect(result.added).toBe(1); +    expect(result.deleted).toBe(1); +  }); + +  it('should handle empty content', () => { +    const input = { path: 'empty.ts', content: '' }; +    const result = normalizeDiff(input); +    expect(result.path).toBe('empty.ts'); +    expect(result.added).toBe(0); +    expect(result.deleted).toBe(0); +  }); + +  it('should handle missing fields', () => { +    const input = { notAPath: 'value' }; +    const result = normalizeDiff(input); +    expect(result.path).toBe(''); +  }); +}); \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\webview\\hooks\\AppContext.tsx" "b/C:\\Projects\\opencode_sidebar\\src\\webview\\hooks\\AppContext.tsx" new file mode 100644 index 0000000..d813641 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\webview\\hooks\\AppContext.tsx" @@ -0,0 +1,72 @@ +import React, { createContext, useContext, ReactNode } from 'react'; +import { useChatState } from './useChatState'; +import { useModelManager } from './useModelManager'; +import { ChatMessage, ProviderListResult } from '../../extension/types'; + +interface AppState { +  messages: ChatMessage[]; +  setMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>; +  busy: boolean; +  setBusy: React.Dispatch<React.SetStateAction<boolean>>; +  contextEvents: Array<{ id: string; name: string; status: string; content: string; meta?: any }>; +  setContextEvents: React.Dispatch<React.SetStateAction<Array<{ id: string; name: string; status: string; content: string; meta?: any }>>>; +  pendingChunkRef: React.MutableRefObject<string>; +  chunkFlushTimerRef: React.MutableRefObject<ReturnType<typeof setTimeout> | null>; +  streamingMsgIdRef: React.MutableRefObject<string | null>; +  DEBOUNCE_MS: number; +  flushPendingChunk: () => void; +  cleanupStreaming: () => void; +  model: string; +  setModel: React.Dispatch<React.SetStateAction<string>>; +  mode: string; +  setMode: React.Dispatch<React.SetStateAction<string>>; +  gitInfo: { branch: string; lastCommitTime: string; projectPath: string }; +  setGitInfo: React.Dispatch<React.SetStateAction<{ branch: string; lastCommitTime: string; projectPath: string }>>; +  availableModels: Array<{ id: string; name: string; providerId: string }>; +  setAvailableModels: React.Dispatch<React.SetStateAction<Array<{ id: string; name: string; providerId: string }>>>; +  hiddenModels: Record<string, boolean>; +  setHiddenModels: React.Dispatch<React.SetStateAction<Record<string, boolean>>>; +  providersLoaded: boolean; +  setProvidersLoaded: React.Dispatch<React.SetStateAction<boolean>>; +  skills: Array<{ name: string; description?: string }>; +  setSkills: React.Dispatch<React.SetStateAction<Array<{ name: string; description?: string }>>>; +  fileSearchResults: Array<{ name: string; path: string }>; +  setFileSearchResults: React.Dispatch<React.SetStateAction<Array<{ name: string; path: string }>>>; +  fileSearchQuery: string; +  setFileSearchQuery: React.Dispatch<React.SetStateAction<string>>; +  revertActive: boolean; +  setRevertActive: React.Dispatch<React.SetStateAction<boolean>>; +  confirmDialog: { message: string; onConfirm: () => void } | null; +  setConfirmDialog: React.Dispatch<React.SetStateAction<{ message: string; onConfirm: () => void } | null>>; +  readPermissionPrompt: { filePath: string; reason: string; requestId: string } | null; +  setReadPermissionPrompt: React.Dispatch<React.SetStateAction<{ filePath: string; reason: string; requestId: string } | null>>; +  showProviders: boolean; +  setShowProviders: React.Dispatch<React.SetStateAction<boolean>>; +  showSessions: boolean; +  setShowSessions: React.Dispatch<React.SetStateAction<boolean>>; +  toggleModelVisibility: (modelId: string) => void; +  handleToggleAllModels: (providerId: string, show: boolean) => void; +  pendingRevertRef: React.MutableRefObject<string | null>; +  processProviderList: (result: ProviderListResult) => void; +  tryAutoSelectModel: (models: Array<{ id: string; name: string; providerId: string }>, currentModel: string, hidden: Record<string, boolean>) => void; +} + +const AppContext = createContext<AppState | null>(null); + +export function useAppState() { +  const ctx = useContext(AppContext); +  if (!ctx) throw new Error('useAppState must be used within AppProvider'); +  return ctx; +} + +export function AppProvider({ children }: { children: ReactNode }) { +  const chatState = useChatState(); +  const modelState = useModelManager(); + +  const state: AppState = { +    ...chatState, +    ...modelState, +  }; + +  return <AppContext.Provider value={state}>{children}</AppContext.Provider>; +} \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\webview\\hooks\\useHoverStyles.ts" "b/C:\\Projects\\opencode_sidebar\\src\\webview\\hooks\\useHoverStyles.ts" new file mode 100644 index 0000000..e6505ff --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\webview\\hooks\\useHoverStyles.ts" @@ -0,0 +1,17 @@ +import { MouseEvent, useCallback } from 'react'; + +export const hover = (style: React.CSSProperties) => (e: MouseEvent<HTMLElement>) => { +  Object.assign(e.currentTarget.style, style); +}; + +export const unhover = () => (e: MouseEvent<HTMLElement>) => { +  e.currentTarget.style.cssText = ''; +}; + +export const setColor = (color: string) => (e: MouseEvent<HTMLElement>) => { +  e.currentTarget.style.color = color; +}; + +export const clearStyle = (e: MouseEvent<HTMLElement>) => { +  e.currentTarget.style.cssText = ''; +}; \ No newline at end of file
diff --git "a/C:\\Projects\\opencode_sidebar\\src\\webview\\styles.ts" "b/C:\\Projects\\opencode_sidebar\\src\\webview\\styles.ts" new file mode 100644 index 0000000..5b7cb97 --- /dev/null +++ "b/C:\\Projects\\opencode_sidebar\\src\\webview\\styles.ts" @@ -0,0 +1,50 @@ +import { CSSProperties } from 'react'; + +// Colors +export const COLORS = { +  bg: '#1e1e2e', +  bgLight: '#181825', +  bgHover: '#313244', +  border: '#45475a', +  text: '#cdd6f4', +  textMuted: '#585b70', +  textDim: '#6c7086', +  accent: '#89b4fa', +  green: '#a6e3a1', +  red: '#f38ba8', +  purple: '#7c3aed', +  yellow: '#f9e2af', +  teal: '#94e2d5', +  overlay: 'rgba(0,0,0,0.6)', +}; + +// Layout +export const flexRow: CSSProperties = { display: 'flex', alignItems: 'center' }; +export const flexCenter: CSSProperties = { display: 'flex', alignItems: 'center', justifyContent: 'center' }; +export const flexBetween: CSSProperties = { display: 'flex', alignItems: 'center', justifyContent: 'space-between' }; +export const flexCol: CSSProperties = { display: 'flex', flexDirection: 'column' }; + +// Buttons +export const btnBase: CSSProperties = { backgroundColor: 'transparent', border: 'none', cursor: 'pointer', padding: 4, borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }; +export const btnIcon: CSSProperties = { ...btnBase, color: COLORS.textMuted }; +export const btnAccent: CSSProperties = { padding: '7px 14px', borderRadius: 6, border: 'none', backgroundColor: COLORS.purple, color: '#fff', cursor: 'pointer', fontSize: 12 }; + +// Inputs +export const inputBase: CSSProperties = { flex: 1, padding: '7px 10px', borderRadius: 6, border: `1px solid ${COLORS.border}`, backgroundColor: COLORS.bgHover, color: COLORS.text, fontSize: 12, fontFamily: 'monospace', outline: 'none' }; + +// Text +export const textSmall: CSSProperties = { fontSize: 11, color: COLORS.textMuted }; +export const textNormal: CSSProperties = { fontSize: 13, lineHeight: 1.6, color: COLORS.text, wordBreak: 'break-word' }; +export const textHeader: CSSProperties = { fontSize: 14, fontWeight: 600, marginBottom: 8 }; + +// Fixed overlay +export const overlay: CSSProperties = { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: COLORS.overlay, display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }; + +// Card / Panel +export const card: CSSProperties = { backgroundColor: COLORS.bg, border: `1px solid ${COLORS.border}`, borderRadius: 12, padding: 24, maxWidth: 400, width: '90%', boxShadow: '0 8px 32px rgba(0,0,0,0.4)' }; + +// Transition +export const transitionColor: CSSProperties = { transition: 'color 0.15s' }; + +// Gap helpers +export const gap = (n: number): CSSProperties => ({ gap: n }); \ No newline at end of file
