|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Atom++ — AI (M2, feature: edit with diff) |
| 3 | + * |
| 4 | + * Select code → describe a change → the model rewrites it → review a side-by-side diff → |
| 5 | + * Apply or Discard using the buttons on the diff editor's toolbar. The proposed text is |
| 6 | + * served through a virtual document so the diff shows syntax-highlighted before/after |
| 7 | + * without touching your file until you click Apply. |
| 8 | + *--------------------------------------------------------------------------------------------*/ |
| 9 | +// @ts-check |
| 10 | +'use strict'; |
| 11 | + |
| 12 | +const vscode = require('vscode'); |
| 13 | +const path = require('path'); |
| 14 | + |
| 15 | +const SCHEME = 'atompp-ai'; |
| 16 | +const CTX_DIFF_ACTIVE = 'atompp.ai.diffActive'; |
| 17 | + |
| 18 | +/** @type {Map<string,string>} virtual-doc uri -> content */ |
| 19 | +const contents = new Map(); |
| 20 | +/** @type {Map<string,{docUri:vscode.Uri, range:vscode.Range, newText:string, origUri:vscode.Uri}>} keyed by proposed uri */ |
| 21 | +const pending = new Map(); |
| 22 | +let counter = 0; |
| 23 | +let providerRegistered = false; |
| 24 | + |
| 25 | +const EDIT_SYSTEM = |
| 26 | + 'You are a precise code editor. Rewrite the user\'s code so it satisfies their instruction. ' + |
| 27 | + 'Output ONLY the rewritten code — no explanations, no commentary, and no Markdown code fences.'; |
| 28 | + |
| 29 | +function stripFences(text) { |
| 30 | + let s = text.trim(); |
| 31 | + s = s.replace(/^```[a-zA-Z0-9_+\-.]*\n?/, ''); |
| 32 | + s = s.replace(/\n?```$/, ''); |
| 33 | + return s; |
| 34 | +} |
| 35 | + |
| 36 | +function registerProvider(context) { |
| 37 | + if (providerRegistered) { return; } |
| 38 | + providerRegistered = true; |
| 39 | + context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider(SCHEME, { |
| 40 | + provideTextDocumentContent(uri) { return contents.get(uri.toString()) || ''; } |
| 41 | + })); |
| 42 | +} |
| 43 | + |
| 44 | +/** The proposed-uri of the diff in the currently active tab, if it's one of ours. */ |
| 45 | +function activeProposedUri() { |
| 46 | + const group = vscode.window.tabGroups.activeTabGroup; |
| 47 | + const input = /** @type {any} */ (group && group.activeTab && group.activeTab.input); |
| 48 | + if (input && input.modified && input.modified.scheme === SCHEME && pending.has(input.modified.toString())) { |
| 49 | + return input.modified; |
| 50 | + } |
| 51 | + return undefined; |
| 52 | +} |
| 53 | + |
| 54 | +function updateDiffContext() { |
| 55 | + vscode.commands.executeCommand('setContext', CTX_DIFF_ACTIVE, !!activeProposedUri()); |
| 56 | +} |
| 57 | + |
| 58 | +function cleanup(propUri) { |
| 59 | + const key = propUri.toString(); |
| 60 | + const p = pending.get(key); |
| 61 | + if (p) { contents.delete(p.origUri.toString()); } |
| 62 | + contents.delete(key); |
| 63 | + pending.delete(key); |
| 64 | +} |
| 65 | + |
| 66 | +async function closeDiffTab(propUri) { |
| 67 | + for (const group of vscode.window.tabGroups.all) { |
| 68 | + for (const tab of group.tabs) { |
| 69 | + const input = /** @type {any} */ (tab.input); |
| 70 | + if (input && input.modified && input.modified.toString() === propUri.toString()) { |
| 71 | + await vscode.window.tabGroups.close(tab); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +async function applyEdit() { |
| 78 | + const propUri = activeProposedUri(); |
| 79 | + if (!propUri) { return; } |
| 80 | + const p = pending.get(propUri.toString()); |
| 81 | + if (!p) { return; } |
| 82 | + const we = new vscode.WorkspaceEdit(); |
| 83 | + we.replace(p.docUri, p.range, p.newText); |
| 84 | + await vscode.workspace.applyEdit(we); |
| 85 | + cleanup(propUri); |
| 86 | + await closeDiffTab(propUri); |
| 87 | + updateDiffContext(); |
| 88 | + vscode.window.setStatusBarMessage('$(check) Atom++ AI: edit applied', 2000); |
| 89 | +} |
| 90 | + |
| 91 | +async function discardEdit() { |
| 92 | + const propUri = activeProposedUri(); |
| 93 | + if (!propUri) { return; } |
| 94 | + cleanup(propUri); |
| 95 | + await closeDiffTab(propUri); |
| 96 | + updateDiffContext(); |
| 97 | + vscode.window.setStatusBarMessage('Atom++ AI: edit discarded', 1500); |
| 98 | +} |
| 99 | + |
| 100 | +/** @param {{aiConfig:()=>any, getClaudeKey:()=>Promise<string|undefined>, streamClaude:Function, streamOllama:Function}} deps */ |
| 101 | +async function editSelection(deps) { |
| 102 | + const ed = vscode.window.activeTextEditor; |
| 103 | + if (!ed || ed.selection.isEmpty) { |
| 104 | + vscode.window.showInformationMessage('Atom++ AI: select the code you want to edit first.'); |
| 105 | + return; |
| 106 | + } |
| 107 | + const instruction = await vscode.window.showInputBox({ |
| 108 | + title: 'Atom++ AI — Edit selection', |
| 109 | + prompt: 'Describe the change', |
| 110 | + placeHolder: 'e.g. add error handling and a JSDoc comment', |
| 111 | + ignoreFocusOut: true |
| 112 | + }); |
| 113 | + if (!instruction) { return; } |
| 114 | + |
| 115 | + const doc = ed.document; |
| 116 | + const range = new vscode.Range(ed.selection.start, ed.selection.end); |
| 117 | + const original = doc.getText(range); |
| 118 | + const lang = doc.languageId || ''; |
| 119 | + const userMsg = `Instruction: ${instruction}\n\nCode (${lang}):\n${original}`; |
| 120 | + |
| 121 | + let result = ''; |
| 122 | + try { |
| 123 | + await vscode.window.withProgress( |
| 124 | + { location: vscode.ProgressLocation.Notification, title: 'Atom++ AI is editing…', cancellable: true }, |
| 125 | + async (_progress, token) => { |
| 126 | + const ac = new AbortController(); |
| 127 | + token.onCancellationRequested(() => ac.abort()); |
| 128 | + const onDelta = (d) => { result += d; }; |
| 129 | + const cfg = deps.aiConfig(); |
| 130 | + if (cfg.get('provider', 'claude') === 'claude') { |
| 131 | + const key = await deps.getClaudeKey(); |
| 132 | + if (!key) { throw new Error('No Anthropic API key set.'); } |
| 133 | + await deps.streamClaude({ |
| 134 | + apiKey: key, model: cfg.get('claude.model', 'claude-sonnet-4-6'), |
| 135 | + maxTokens: cfg.get('claude.maxTokens', 4096), system: EDIT_SYSTEM, |
| 136 | + messages: [{ role: 'user', content: userMsg }], signal: ac.signal, onDelta |
| 137 | + }); |
| 138 | + } else { |
| 139 | + await deps.streamOllama({ |
| 140 | + url: cfg.get('ollama.url', 'http://localhost:11434'), model: cfg.get('ollama.model', 'llama3.1'), |
| 141 | + system: EDIT_SYSTEM, messages: [{ role: 'user', content: userMsg }], signal: ac.signal, onDelta |
| 142 | + }); |
| 143 | + } |
| 144 | + } |
| 145 | + ); |
| 146 | + } catch (e) { |
| 147 | + vscode.window.showErrorMessage('Atom++ AI edit failed: ' + String((e && e.message) || e)); |
| 148 | + return; |
| 149 | + } |
| 150 | + |
| 151 | + const proposed = stripFences(result); |
| 152 | + if (!proposed.trim()) { vscode.window.showWarningMessage('Atom++ AI: no edit was produced.'); return; } |
| 153 | + |
| 154 | + const ext = path.extname(doc.uri.fsPath) || '.txt'; |
| 155 | + const n = ++counter; |
| 156 | + const origUri = vscode.Uri.parse(`${SCHEME}:/${n}/current${ext}`); |
| 157 | + const propUri = vscode.Uri.parse(`${SCHEME}:/${n}/proposed${ext}`); |
| 158 | + contents.set(origUri.toString(), original); |
| 159 | + contents.set(propUri.toString(), proposed); |
| 160 | + pending.set(propUri.toString(), { docUri: doc.uri, range, newText: proposed, origUri }); |
| 161 | + |
| 162 | + await vscode.commands.executeCommand('vscode.diff', origUri, propUri, |
| 163 | + 'Atom++ AI: proposed edit — use ✓ Apply / ✗ Discard above', { preview: true }); |
| 164 | + updateDiffContext(); |
| 165 | +} |
| 166 | + |
| 167 | +/** @param {vscode.ExtensionContext} context @param {object} deps */ |
| 168 | +function registerAiEdit(context, deps) { |
| 169 | + registerProvider(context); |
| 170 | + context.subscriptions.push( |
| 171 | + vscode.commands.registerCommand('atompp.ai.editSelection', () => editSelection(deps)), |
| 172 | + vscode.commands.registerCommand('atompp.ai.applyEdit', applyEdit), |
| 173 | + vscode.commands.registerCommand('atompp.ai.discardEdit', discardEdit), |
| 174 | + vscode.window.tabGroups.onDidChangeTabGroups(updateDiffContext), |
| 175 | + vscode.window.tabGroups.onDidChangeTabs((e) => { |
| 176 | + // If the user closes our diff tab without choosing, clean up. |
| 177 | + for (const tab of e.closed) { |
| 178 | + const input = /** @type {any} */ (tab.input); |
| 179 | + if (input && input.modified && input.modified.scheme === SCHEME) { |
| 180 | + cleanup(input.modified); |
| 181 | + } |
| 182 | + } |
| 183 | + updateDiffContext(); |
| 184 | + }) |
| 185 | + ); |
| 186 | +} |
| 187 | + |
| 188 | +module.exports = { registerAiEdit }; |
0 commit comments