Add browser extension and shell completions (Milestones 12-13)

M12: Browser Extension
- Chrome/Edge Manifest V3 extension
- Popup UI for saving pages
- Context menu integration (save page/selection/link)
- Background service worker
- Content script for extraction

M13: Shell Completions
- Bash, Zsh, Fish, PowerShell completions
- Dynamic node ID completion
- Dynamic tag completion
- Dynamic graph completion
- Auto-install command (--install)
This commit is contained in:
2026-02-03 11:35:41 +01:00
parent b1c62c5da9
commit f21426fc43
11 changed files with 1248 additions and 0 deletions

75
extension/README.md Normal file
View File

@@ -0,0 +1,75 @@
# Cortex Browser Extension
Save web content directly to your Cortex knowledge graph.
## Features
- One-click save from any webpage
- Right-click context menu integration
- Save selected text only
- Auto-extract page title and content
- Tag suggestions based on URL
## Installation
### Chrome / Edge
1. Open `chrome://extensions` (or `edge://extensions`)
2. Enable "Developer mode" in the top right
3. Click "Load unpacked"
4. Select this `extension` folder
### Firefox
1. Open `about:debugging`
2. Click "This Firefox"
3. Click "Load Temporary Add-on"
4. Select `manifest.json` from this folder
## Usage
### Popup
1. Click the Cortex icon in your browser toolbar
2. Edit the title and tags as needed
3. Choose whether to include page content
4. Click "Save"
### Context Menu
- **Save page**: Right-click anywhere on a page → "Save page to Cortex"
- **Save selection**: Select text, right-click → "Save selection to Cortex"
- **Save link**: Right-click a link → "Save link to Cortex"
## Requirements
The Cortex server must be running for the extension to work:
```bash
cortex serve
```
By default, the extension connects to `http://localhost:3100/api`.
## Development
The extension uses Manifest V3 and consists of:
- `manifest.json` - Extension configuration
- `popup/` - Popup UI (HTML, CSS, JS)
- `background/` - Service worker for context menus
- `content/` - Content script for page extraction
- `icons/` - Extension icons
## Icon Generation
To generate PNG icons from the SVG:
```bash
# Using ImageMagick
convert icons/icon.svg -resize 16x16 icons/icon-16.png
convert icons/icon.svg -resize 48x48 icons/icon-48.png
convert icons/icon.svg -resize 128x128 icons/icon-128.png
```
Or use an online SVG to PNG converter.

View File

@@ -0,0 +1,136 @@
// Background service worker for Cortex browser extension
const CORTEX_API = 'http://localhost:3100/api';
// Create context menu on install
chrome.runtime.onInstalled.addListener(() => {
// Save page context menu
chrome.contextMenus.create({
id: 'cortex-save-page',
title: 'Save page to Cortex',
contexts: ['page'],
});
// Save selection context menu
chrome.contextMenus.create({
id: 'cortex-save-selection',
title: 'Save selection to Cortex',
contexts: ['selection'],
});
// Save link context menu
chrome.contextMenus.create({
id: 'cortex-save-link',
title: 'Save link to Cortex',
contexts: ['link'],
});
});
// Handle context menu clicks
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
try {
let content = '';
let title = tab.title;
if (info.menuItemId === 'cortex-save-selection') {
content = info.selectionText || '';
title = `Selection from: ${tab.title}`;
} else if (info.menuItemId === 'cortex-save-link') {
content = `Link: ${info.linkUrl}`;
title = info.linkUrl;
} else {
// Get full page content
const [{ result }] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: extractPageContent,
});
content = result?.content || '';
title = result?.title || tab.title;
}
// Save to Cortex
await saveToCortex({
title,
content,
url: tab.url,
kind: 'memory',
tags: ['web-clip'],
});
// Show notification (if supported)
if (chrome.notifications) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon-48.png',
title: 'Saved to Cortex',
message: title.slice(0, 50),
});
}
} catch (err) {
console.error('Context menu action failed:', err);
}
});
// Function to extract page content (injected into page)
function extractPageContent() {
// Simple content extraction
// A full implementation would use Readability
const title = document.title;
// Try to get main content
const article = document.querySelector('article');
const main = document.querySelector('main');
const content = article?.textContent || main?.textContent || document.body.textContent || '';
// Clean up content
const cleanContent = content
.replace(/\s+/g, ' ')
.replace(/\n+/g, '\n')
.trim()
.slice(0, 50000); // Limit content size
return {
title,
content: cleanContent,
url: window.location.href,
};
}
// Save to Cortex API
async function saveToCortex(data) {
const response = await fetch(`${CORTEX_API}/nodes`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
kind: data.kind || 'memory',
title: data.title,
content: data.content,
tags: data.tags || ['web-clip'],
metadata: {
source: {
type: 'url',
url: data.url,
savedAt: Date.now(),
},
},
}),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
// Listen for messages from content script or popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'save') {
saveToCortex(request.data)
.then(node => sendResponse({ success: true, nodeId: node.id }))
.catch(err => sendResponse({ success: false, error: err.message }));
return true; // Keep channel open for async response
}
});

View File

@@ -0,0 +1,80 @@
// Content script for Cortex browser extension
// Injected into web pages to extract content
// Extract page content
function extractContent() {
const title = document.title;
// Get selected text
const selection = window.getSelection()?.toString() || '';
// Try to find main content using common selectors
let content = '';
const contentSelectors = [
'article',
'[role="main"]',
'main',
'.post-content',
'.article-content',
'.entry-content',
'.content',
'#content',
];
for (const selector of contentSelectors) {
const el = document.querySelector(selector);
if (el && el.textContent) {
content = el.textContent;
break;
}
}
// Fall back to body content
if (!content) {
content = document.body.textContent || '';
}
// Clean up content
content = content
.replace(/\s+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim()
.slice(0, 100000); // Limit to 100k chars
// Get meta description
const metaDesc = document.querySelector('meta[name="description"]')?.content || '';
// Get author
const author = document.querySelector('meta[name="author"]')?.content ||
document.querySelector('[rel="author"]')?.textContent || '';
// Get published date
const datePublished = document.querySelector('meta[property="article:published_time"]')?.content ||
document.querySelector('time[datetime]')?.getAttribute('datetime') || '';
return {
title,
content,
selection,
excerpt: metaDesc || content.slice(0, 200),
url: window.location.href,
author,
datePublished,
};
}
// Listen for messages from popup or background
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'extract') {
try {
const data = extractContent();
sendResponse(data);
} catch (err) {
sendResponse({ error: err.message });
}
}
return true; // Keep channel open for async response
});
// Make extract function available globally for background script injection
window.__cortexExtract = extractContent;

23
extension/icons/icon.svg Normal file
View File

@@ -0,0 +1,23 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#4fc3f7;stop-opacity:1" />
<stop offset="100%" style="stop-color:#29b6f6;stop-opacity:1" />
</linearGradient>
</defs>
<circle cx="64" cy="64" r="56" fill="url(#grad)"/>
<g fill="#fff">
<!-- Brain/memory icon representation -->
<circle cx="64" cy="48" r="8"/>
<circle cx="44" cy="68" r="6"/>
<circle cx="84" cy="68" r="6"/>
<circle cx="54" cy="88" r="5"/>
<circle cx="74" cy="88" r="5"/>
<!-- Connections -->
<path d="M64 56 L44 62" stroke="#fff" stroke-width="2" fill="none"/>
<path d="M64 56 L84 62" stroke="#fff" stroke-width="2" fill="none"/>
<path d="M44 74 L54 83" stroke="#fff" stroke-width="2" fill="none"/>
<path d="M84 74 L74 83" stroke="#fff" stroke-width="2" fill="none"/>
<path d="M54 88 L74 88" stroke="#fff" stroke-width="2" fill="none"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1012 B

36
extension/manifest.json Normal file
View File

@@ -0,0 +1,36 @@
{
"manifest_version": 3,
"name": "Cortex - Save to Memory",
"version": "1.0.0",
"description": "Save web content to your Cortex knowledge graph",
"permissions": [
"activeTab",
"contextMenus",
"storage"
],
"host_permissions": [
"http://localhost:3100/*"
],
"action": {
"default_popup": "popup/popup.html",
"default_icon": {
"16": "icons/icon-16.png",
"48": "icons/icon-48.png",
"128": "icons/icon-128.png"
}
},
"background": {
"service_worker": "background/background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content/content.js"]
}
],
"icons": {
"16": "icons/icon-16.png",
"48": "icons/icon-48.png",
"128": "icons/icon-128.png"
}
}

136
extension/popup/popup.css Normal file
View File

@@ -0,0 +1,136 @@
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px;
width: 320px;
padding: 16px;
background: #1a1a2e;
color: #eee;
}
.container {
display: flex;
flex-direction: column;
gap: 12px;
}
h1 {
font-size: 18px;
font-weight: 600;
color: #4fc3f7;
margin-bottom: 8px;
}
.status {
padding: 8px;
border-radius: 4px;
font-size: 12px;
display: none;
}
.status.success {
display: block;
background: #1b5e20;
color: #a5d6a7;
}
.status.error {
display: block;
background: #b71c1c;
color: #ef9a9a;
}
.field {
display: flex;
flex-direction: column;
gap: 4px;
}
.field.checkbox {
flex-direction: row;
align-items: center;
}
.field.checkbox label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
label {
font-size: 12px;
color: #aaa;
font-weight: 500;
}
input[type="text"],
select {
padding: 8px 12px;
border: 1px solid #333;
border-radius: 4px;
background: #0f0f23;
color: #eee;
font-size: 14px;
}
input[type="text"]:focus,
select:focus {
outline: none;
border-color: #4fc3f7;
}
select {
cursor: pointer;
}
input[type="checkbox"] {
width: 16px;
height: 16px;
cursor: pointer;
}
.actions {
display: flex;
gap: 8px;
margin-top: 8px;
}
button {
flex: 1;
padding: 10px 16px;
border: none;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.2s;
}
button.primary {
background: #4fc3f7;
color: #000;
}
button.primary:hover {
background: #29b6f6;
}
button:not(.primary) {
background: #333;
color: #eee;
}
button:not(.primary):hover {
background: #444;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}

View File

@@ -0,0 +1,55 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div class="container">
<h1>Save to Cortex</h1>
<div id="status" class="status"></div>
<div class="field">
<label for="title">Title</label>
<input type="text" id="title" placeholder="Page title">
</div>
<div class="field">
<label for="kind">Kind</label>
<select id="kind">
<option value="memory">Memory</option>
<option value="component">Component</option>
<option value="decision">Decision</option>
<option value="task">Task</option>
</select>
</div>
<div class="field">
<label for="tags">Tags</label>
<input type="text" id="tags" placeholder="comma, separated, tags">
</div>
<div class="field checkbox">
<label>
<input type="checkbox" id="includeContent" checked>
Include page content
</label>
</div>
<div class="field checkbox">
<label>
<input type="checkbox" id="selectionOnly">
Selection only
</label>
</div>
<div class="actions">
<button id="save" class="primary">Save</button>
<button id="cancel">Cancel</button>
</div>
</div>
<script src="popup.js"></script>
</body>
</html>

136
extension/popup/popup.js Normal file
View File

@@ -0,0 +1,136 @@
// Popup script for Cortex browser extension
const CORTEX_API = 'http://localhost:3100/api';
// DOM elements
const titleInput = document.getElementById('title');
const kindSelect = document.getElementById('kind');
const tagsInput = document.getElementById('tags');
const includeContent = document.getElementById('includeContent');
const selectionOnly = document.getElementById('selectionOnly');
const saveButton = document.getElementById('save');
const cancelButton = document.getElementById('cancel');
const statusDiv = document.getElementById('status');
let pageData = null;
// Initialize popup
async function init() {
try {
// Get current tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// Request content from content script
const response = await chrome.tabs.sendMessage(tab.id, { action: 'extract' });
pageData = response;
// Pre-fill form
titleInput.value = response.title || tab.title || '';
// Suggest tags based on URL
const url = new URL(tab.url);
const suggestedTags = ['web-clip'];
if (url.hostname.includes('github')) suggestedTags.push('github');
if (url.hostname.includes('docs')) suggestedTags.push('documentation');
if (url.hostname.includes('stackoverflow')) suggestedTags.push('stackoverflow');
tagsInput.value = suggestedTags.join(', ');
// Enable selection only if there's selected text
if (response.selection) {
selectionOnly.disabled = false;
} else {
selectionOnly.disabled = true;
}
} catch (err) {
showStatus('Could not extract page content', 'error');
console.error('Init error:', err);
}
}
// Save to Cortex
async function save() {
saveButton.disabled = true;
saveButton.textContent = 'Saving...';
try {
const content = selectionOnly.checked
? pageData?.selection
: (includeContent.checked ? pageData?.content : '');
const tags = tagsInput.value
.split(',')
.map(t => t.trim())
.filter(t => t.length > 0);
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await fetch(`${CORTEX_API}/nodes`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
kind: kindSelect.value,
title: titleInput.value,
content: content,
tags: tags,
metadata: {
source: {
type: 'url',
url: tab.url,
savedAt: Date.now(),
},
},
}),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const node = await response.json();
showStatus(`Saved! ID: ${node.id.slice(0, 8)}`, 'success');
// Close popup after brief delay
setTimeout(() => window.close(), 1500);
} catch (err) {
showStatus(`Failed to save: ${err.message}`, 'error');
console.error('Save error:', err);
// Check if Cortex server is running
if (err.message.includes('fetch')) {
showStatus('Is Cortex server running? (cortex serve)', 'error');
}
} finally {
saveButton.disabled = false;
saveButton.textContent = 'Save';
}
}
// Show status message
function showStatus(message, type) {
statusDiv.textContent = message;
statusDiv.className = `status ${type}`;
}
// Event listeners
saveButton.addEventListener('click', save);
cancelButton.addEventListener('click', () => window.close());
// Toggle selection only checkbox when include content is unchecked
includeContent.addEventListener('change', () => {
if (!includeContent.checked) {
selectionOnly.checked = false;
}
});
selectionOnly.addEventListener('change', () => {
if (selectionOnly.checked) {
includeContent.checked = true;
}
});
// Initialize on load
init();