pocket-tutor 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +171 -2
  3. package/bin/pocket-tutor.js +57 -0
  4. package/config.example.json +12 -0
  5. package/docs/CLIP_RULES.md +38 -0
  6. package/package.json +74 -4
  7. package/scripts/build-ui.mjs +25 -0
  8. package/scripts/clip-judge.js +106 -0
  9. package/scripts/doctor.js +58 -0
  10. package/scripts/setup-visuals.js +27 -0
  11. package/scripts/visual_scene.py +279 -0
  12. package/src/astryx-themes.js +18 -0
  13. package/src/browser.js +38 -0
  14. package/src/config.js +84 -0
  15. package/src/graph.js +114 -0
  16. package/src/helper.ps1 +67 -0
  17. package/src/main.js +490 -0
  18. package/src/model.js +283 -0
  19. package/src/native.js +50 -0
  20. package/src/place.js +29 -0
  21. package/src/preload.js +17 -0
  22. package/src/privacy.js +40 -0
  23. package/src/project.js +252 -0
  24. package/src/search.js +111 -0
  25. package/src/themes/lens/lens.css +1165 -0
  26. package/src/themes/lens/lens.css.d.ts +9 -0
  27. package/src/themes/lens/lens.d.ts +14 -0
  28. package/src/themes/lens/lens.fonts.css +2 -0
  29. package/src/themes/lens/lens.js +627 -0
  30. package/src/themes/lens/lens.variants.d.ts +22 -0
  31. package/src/themes/lens/lensTheme.doc.mjs +10 -0
  32. package/src/themes/lens/lensTheme.ts +2 -0
  33. package/src/ui/app.jsx +268 -0
  34. package/src/ui/dist/assets/KaTeX_AMS-Regular-CYEKBG2K.woff +0 -0
  35. package/src/ui/dist/assets/KaTeX_AMS-Regular-JKX5W2C4.ttf +0 -0
  36. package/src/ui/dist/assets/KaTeX_AMS-Regular-U6PRYMIZ.woff2 +0 -0
  37. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-5QL5CMTE.woff2 +0 -0
  38. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-WZ3QSGD3.woff +0 -0
  39. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-ZTS3R3HK.ttf +0 -0
  40. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-3LKEU76G.woff +0 -0
  41. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-A7XRTZ5Q.ttf +0 -0
  42. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-KX5MEWCF.woff2 +0 -0
  43. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-2QVFK6NQ.woff2 +0 -0
  44. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-T4SWXBMT.woff +0 -0
  45. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-WGHVTYOR.ttf +0 -0
  46. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-2PEIFJSJ.woff2 +0 -0
  47. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-5U4OPH2X.ttf +0 -0
  48. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-PQMHCIK6.woff +0 -0
  49. package/src/ui/dist/assets/KaTeX_Main-Bold-2GA4IZIN.woff +0 -0
  50. package/src/ui/dist/assets/KaTeX_Main-Bold-W5FBVCZM.ttf +0 -0
  51. package/src/ui/dist/assets/KaTeX_Main-Bold-YP5VVQRP.woff2 +0 -0
  52. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-4P4C7HJH.woff +0 -0
  53. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-N4V3DX7S.woff2 +0 -0
  54. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-ODMLBJJQ.ttf +0 -0
  55. package/src/ui/dist/assets/KaTeX_Main-Italic-I43T2HSR.ttf +0 -0
  56. package/src/ui/dist/assets/KaTeX_Main-Italic-RELBIK7M.woff2 +0 -0
  57. package/src/ui/dist/assets/KaTeX_Main-Italic-SASNQFN2.woff +0 -0
  58. package/src/ui/dist/assets/KaTeX_Main-Regular-ARRPAO67.woff2 +0 -0
  59. package/src/ui/dist/assets/KaTeX_Main-Regular-P5I74A2A.woff +0 -0
  60. package/src/ui/dist/assets/KaTeX_Main-Regular-W74P5G27.ttf +0 -0
  61. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-6EBV3DK5.woff +0 -0
  62. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-K4WTGH3J.woff2 +0 -0
  63. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-VB447A4D.ttf +0 -0
  64. package/src/ui/dist/assets/KaTeX_Math-Italic-6KGCHLFN.woff2 +0 -0
  65. package/src/ui/dist/assets/KaTeX_Math-Italic-KKK3USB2.woff +0 -0
  66. package/src/ui/dist/assets/KaTeX_Math-Italic-SON4MRCA.ttf +0 -0
  67. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-RRNVJFFW.woff2 +0 -0
  68. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-STQ6RXC7.ttf +0 -0
  69. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-X5M5EMOD.woff +0 -0
  70. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-HMPFTM52.woff2 +0 -0
  71. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-PSN4QKYX.woff +0 -0
  72. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-WTBAZBGY.ttf +0 -0
  73. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-2TL3USAE.ttf +0 -0
  74. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-OQCII6EP.woff +0 -0
  75. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-XIQ62X4E.woff2 +0 -0
  76. package/src/ui/dist/assets/KaTeX_Script-Regular-72OLXYNA.ttf +0 -0
  77. package/src/ui/dist/assets/KaTeX_Script-Regular-A5IFOEBS.woff +0 -0
  78. package/src/ui/dist/assets/KaTeX_Script-Regular-APUWIHLP.woff2 +0 -0
  79. package/src/ui/dist/assets/KaTeX_Size1-Regular-4HRHTS65.woff +0 -0
  80. package/src/ui/dist/assets/KaTeX_Size1-Regular-5LRUTBFT.woff2 +0 -0
  81. package/src/ui/dist/assets/KaTeX_Size1-Regular-7K6AASVL.ttf +0 -0
  82. package/src/ui/dist/assets/KaTeX_Size2-Regular-222HN3GT.ttf +0 -0
  83. package/src/ui/dist/assets/KaTeX_Size2-Regular-K5ZHAIS6.woff +0 -0
  84. package/src/ui/dist/assets/KaTeX_Size2-Regular-LELKET5D.woff2 +0 -0
  85. package/src/ui/dist/assets/KaTeX_Size3-Regular-TLFPAHDE.woff +0 -0
  86. package/src/ui/dist/assets/KaTeX_Size3-Regular-UFCO6WCA.ttf +0 -0
  87. package/src/ui/dist/assets/KaTeX_Size3-Regular-WQRQ47UD.woff2 +0 -0
  88. package/src/ui/dist/assets/KaTeX_Size4-Regular-7PGNVPQK.ttf +0 -0
  89. package/src/ui/dist/assets/KaTeX_Size4-Regular-CDMV7U5C.woff2 +0 -0
  90. package/src/ui/dist/assets/KaTeX_Size4-Regular-PKMWZHNC.woff +0 -0
  91. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-3F5K6SQ6.ttf +0 -0
  92. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-MJMFSK64.woff +0 -0
  93. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-VBYJ4NRC.woff2 +0 -0
  94. package/src/ui/dist/assets/figtree-latin-400-normal-PORFSHKN.woff2 +0 -0
  95. package/src/ui/dist/assets/figtree-latin-500-normal-AHYR5JKA.woff2 +0 -0
  96. package/src/ui/dist/assets/figtree-latin-600-normal-5C6Z7QEI.woff2 +0 -0
  97. package/src/ui/dist/assets/figtree-latin-700-normal-M33EANAW.woff2 +0 -0
  98. package/src/ui/dist/assets/figtree-latin-ext-400-normal-CK4ZBFIX.woff2 +0 -0
  99. package/src/ui/dist/assets/figtree-latin-ext-500-normal-M4H6A6MQ.woff2 +0 -0
  100. package/src/ui/dist/assets/figtree-latin-ext-600-normal-KUZFNAIE.woff2 +0 -0
  101. package/src/ui/dist/assets/figtree-latin-ext-700-normal-U3DQVDYX.woff2 +0 -0
  102. package/src/ui/dist/popup.css +1 -0
  103. package/src/ui/dist/popup.js +546 -0
  104. package/src/ui/popup.html +13 -0
  105. package/src/ui/state.js +89 -0
  106. package/src/visual.js +229 -0
package/src/main.js ADDED
@@ -0,0 +1,490 @@
1
+ // Pocket Tutor: select text anywhere, press the hotkey, and a small black box at the cursor explains it.
2
+ //
3
+ // hotkey ─▶ which window? (helper: fg) ─▶ privacy check ─▶ Ctrl+C (helper: copy) ─▶ read + restore clipboard
4
+ // ─▶ box at the cursor ─▶ plan (model: concept, related ideas, web or not, code words, math or not)
5
+ // ─▶ code snippets (git grep in the window's project) ┐
6
+ // ─▶ context graph (what earlier lookups taught) ├▶ answer (model, streamed)
7
+ // ─▶ web results, only for general ideas (no key) ┘
8
+ // ─▶ remember the lookup in the graph; for math only, a ManimGL clip of the formula
9
+ // The box shows only the explanation (and, for math, the clip). Close and minimize are its only buttons.
10
+ // path:line in the answer opens the file in VS Code.
11
+ const { app, BrowserWindow, globalShortcut, clipboard, screen, ipcMain, shell, Tray, Menu, nativeImage } = require('electron')
12
+ const fs = require('fs')
13
+ const path = require('path')
14
+ const config = require('./config')
15
+ const { Native } = require('./native')
16
+ const { blocked, mask } = require('./privacy')
17
+ const project = require('./project')
18
+ const search = require('./search')
19
+ const model = require('./model')
20
+ const graph = require('./graph')
21
+ const visual = require('./visual')
22
+ const { placeNear, fitBox, BOX } = require('./place')
23
+ const { openUrl, openInEditor } = require('./browser')
24
+
25
+ const DOT = 48 // minimized: a small "0" at the same spot
26
+ let cfg = config.load()
27
+ let native, popup, tray, detail
28
+ let pending = null // the window you pressed the hotkey in with nothing selected: the next question is asked about it
29
+ let run = 0 // each hotkey press gets a number; work for an older press is dropped
30
+ let current = null // { root } of the latest lookup, for opening code links
31
+ let minimized = null // the box's size before it was minimized
32
+ let last = null // the latest finished lookup, for the detail window: { id, selection, where, plan, snippets, web, notes, video, detail }
33
+
34
+ // the self-test runs beside a normal copy: its own profile, no lock, no hotkey, no tray
35
+ const SELFTEST = process.env.POCKET_TUTOR_SELFTEST
36
+ if (SELFTEST) app.setPath('userData', path.join(require('os').tmpdir(), 'pocket-tutor-selftest'))
37
+ if (!SELFTEST && !app.requestSingleInstanceLock()) app.quit()
38
+ else app.whenReady().then(start)
39
+
40
+ const log = (...a) => console.log('[lens]', ...a)
41
+
42
+ function start() {
43
+ app.setAppUserModelId('pocket-tutor') // groups the windows under one taskbar entry with the lens icon
44
+ native = new Native(log)
45
+ createPopup()
46
+ if (!SELFTEST) {
47
+ createTray(); registerHotkey()
48
+ console.log(`Pocket Tutor is running in the system tray.\nSelect text and press ${cfg.hotkey} to explain it. Press it with nothing selected to ask anything.\nQuit from the tray icon, or press Ctrl+C here.\n`)
49
+ }
50
+ ipcMain.on('open-url', (_e, url) => openUrl(url, cfg, shell))
51
+ ipcMain.on('open-code', (_e, { file, line }) => current && openInEditor(current.root, file, line, shell))
52
+ ipcMain.on('close', () => hide())
53
+ ipcMain.on('fit', (_e, m) => fit(m && m.height, m && m.width))
54
+ ipcMain.on('minimize', () => minimize())
55
+ ipcMain.on('restore', () => restore())
56
+ ipcMain.on('detail', () => openDetail().catch((e) => log('detail:', e.message)))
57
+ ipcMain.on('ask', (_e, m) => ask(m).catch((e) => log('ask:', e.message)))
58
+ ipcMain.on('detail-close', () => { if (detail && !detail.isDestroyed()) detail.hide() })
59
+ if (SELFTEST) selfTest(SELFTEST)
60
+ }
61
+
62
+ // POCKET_TUTOR_SELFTEST=out.png npm start: render a sample lookup into the box, save a screenshot, quit.
63
+ // POCKET_TUTOR_SELFTEST_VIDEO=clip.mp4 adds a clip; POCKET_TUTOR_SELFTEST_MIN=1 also shoots the minimized dot.
64
+ // Checks the window and the renderer without keys or keystrokes.
65
+ function selfTest(out) {
66
+ popup.webContents.on('console-message', (e) => { if (e.level === 'error' || e.level === 'warning') log('popup:', e.message) })
67
+ popup.webContents.once('did-finish-load', async () => {
68
+ // POCKET_TUTOR_SELFTEST_STREAM=1: stream an answer word by word and log the box size as it goes;
69
+ // the size must not change until the answer is done
70
+ if (process.env.POCKET_TUTOR_SELFTEST_STREAM) {
71
+ const words = ('**RMSNorm** keeps the numbers in a layer at a steady size. It divides each vector by its average size, the *root mean square*, then multiplies by a learned scale. '.repeat(4)).split(' ')
72
+ show()
73
+ send('state', { id: 1, phase: 'start' })
74
+ const sizes = []
75
+ for (let i = 1; i <= words.length; i += 4) {
76
+ send('state', { id: 1, phase: 'answer', text: words.slice(0, i).join(' ') })
77
+ await new Promise((r) => setTimeout(r, 150))
78
+ sizes.push(popup.getSize().join('x'))
79
+ }
80
+ log('while writing', [...new Set(sizes)].join(' → '))
81
+ send('state', { id: 1, phase: 'done' })
82
+ await new Promise((r) => setTimeout(r, 1500))
83
+ log('when done', popup.getSize().join('x'))
84
+ fs.writeFileSync(out, (await popup.webContents.capturePage()).toPNG())
85
+ return app.exit(0)
86
+ }
87
+ send('state', { id: 1, phase: 'start' })
88
+ send('state', { id: 1, phase: 'sources', snippets: [{ file: 'src/model/norm.py', line: 7 }] })
89
+ send('state', { id: 1, phase: 'answer', text: '**RMSNorm** keeps the numbers in a layer at a steady size. It divides each vector by its average size, the *root mean square*, so the $L^2 d$ attention cost is untouched.\n\n$$y = \\frac{x}{\\sqrt{\\mathrm{mean}(x^2) + \\epsilon}} \\cdot g$$\n\nIn your code, `src/model/norm.py:7` defines it as a small module with one learned scale $g$.' })
90
+ const clip = process.env.POCKET_TUTOR_SELFTEST_VIDEO
91
+ send('state', { id: 1, phase: 'done', drawing: !!clip })
92
+ if (clip) send('state', { id: 1, phase: 'visual', video: `data:video/mp4;base64,${fs.readFileSync(clip).toString('base64')}` })
93
+ show()
94
+ await new Promise((r) => setTimeout(r, 3000))
95
+ fs.writeFileSync(out, (await popup.webContents.capturePage()).toPNG())
96
+ log('box size', popup.getSize().join('x'))
97
+ if (process.env.POCKET_TUTOR_SELFTEST_DETAIL) {
98
+ const video = clip ? `data:video/mp4;base64,${fs.readFileSync(clip).toString('base64')}` : null
99
+ last = { id: 1, selection: 'RMSNorm', where: {}, plan: { concept: 'RMSNorm', related: ['LayerNorm', 'Pre-norm Transformer'] },
100
+ snippets: [{ file: 'src/model/norm.py', line: 7, from: 5, code: 'import torch\n\nclass RMSNorm(nn.Module):\n def __init__(self, d, eps=1e-6):\n super().__init__()' }],
101
+ web: [{ title: 'Root Mean Square Layer Normalization', url: 'https://arxiv.org/abs/1910.07467', site: 'arxiv.org' }],
102
+ notes: ['- LayerNorm: normalizes with mean and variance'], video,
103
+ detail: '## What it is\n\n**RMSNorm** keeps the numbers flowing through a layer at a steady size, so training stays stable.\n\n## How it works\n\n1. Square every number in the vector.\n2. Take the average of the squares.\n3. Take the square root: that is the *root mean square*.\n4. Divide every number by it, then multiply by a learned scale `g`.\n\n## In your code\n\n`src/model/norm.py:7` defines it as a small module with one learned scale.\n\n## Example\n\n```python\nx = [3, 4]\nrms = sqrt((9 + 16) / 2) # 3.54\ny = [3 / 3.54, 4 / 3.54] # [0.85, 1.13]\n```\n\n## Watch out for\n\n- `eps` stops a divide-by-zero when all numbers are 0.\n\n## Related ideas\n\n- LayerNorm, which also subtracts the mean.' }
104
+ await openDetail()
105
+ await new Promise((r) => setTimeout(r, 2500))
106
+ fs.writeFileSync(out.replace(/\.png$/, '_detail.png'), (await detail.webContents.capturePage()).toPNG())
107
+ log('detail size', detail.getSize().join('x'))
108
+ quitting = true
109
+ }
110
+ if (process.env.POCKET_TUTOR_SELFTEST_MIN) {
111
+ minimize()
112
+ await new Promise((r) => setTimeout(r, 800))
113
+ fs.writeFileSync(out.replace(/\.png$/, '_min.png'), (await popup.webContents.capturePage()).toPNG())
114
+ log('dot size', popup.getSize().join('x'))
115
+ }
116
+ app.quit()
117
+ })
118
+ }
119
+
120
+ function registerHotkey() {
121
+ globalShortcut.unregisterAll()
122
+ const ok = globalShortcut.register(cfg.hotkey, () => lookup().catch((e) => log('lookup failed:', e.message)))
123
+ log(ok ? `hotkey ${cfg.hotkey}` : `could not register ${cfg.hotkey}; another app owns it. Set "hotkey" in ${config.FILE}`)
124
+ if (tray) tray.setToolTip(ok ? `Pocket Tutor: select text, then ${cfg.hotkey}` : `Pocket Tutor: hotkey ${cfg.hotkey} is taken`)
125
+ }
126
+
127
+ // ---- the box ----------------------------------------------------------------------------------------
128
+
129
+ function createPopup() {
130
+ popup = new BrowserWindow({
131
+ width: BOX.minW, height: BOX.minH, show: false, frame: false, icon: lensIcon(256), resizable: false, skipTaskbar: true, alwaysOnTop: true,
132
+ minimizable: false, maximizable: false, fullscreenable: false, backgroundColor: '#000000', transparent: false,
133
+ webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, sandbox: true, nodeIntegration: false },
134
+ })
135
+ popup.loadFile(path.join(__dirname, 'ui', 'popup.html'))
136
+ // links never navigate the box itself
137
+ popup.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
138
+ popup.webContents.on('will-navigate', (e) => e.preventDefault())
139
+ }
140
+
141
+ function hide() { if (popup && !popup.isDestroyed()) popup.hide() }
142
+
143
+ function show() {
144
+ if (minimized) restore()
145
+ const cursor = screen.getCursorScreenPoint()
146
+ const area = screen.getDisplayNearestPoint(cursor).workArea
147
+ // each lookup opens at one landscape size and keeps it while the answer is written; fit() runs once it is done
148
+ const { x, y } = placeNear(cursor, BOX.work, area)
149
+ popup.setBounds({ x, y, width: BOX.work.w, height: BOX.work.h })
150
+ popup.show()
151
+ popup.focus()
152
+ }
153
+
154
+ // the page says how tall its content is at the current width; the box follows, always wider than tall,
155
+ // widening when the text gets long (place.js fitBox), and kept on the screen
156
+ function fit(h, measuredAt) {
157
+ if (!popup || popup.isDestroyed() || minimized) return
158
+ const b = popup.getBounds()
159
+ // a report measured before the last resize is stale; acting on it widened the box all the way to the maximum
160
+ if (process.env.POCKET_TUTOR_DEBUG_FIT) log('fit', h, 'measured at', measuredAt, 'window', b.width)
161
+ if (measuredAt && Math.abs(measuredAt - b.width) > 4) return
162
+ const area = screen.getDisplayMatching(b).workArea
163
+ // never bigger than it opened: a long answer scrolls
164
+ const fitted = fitBox(Math.ceil(Number(h) || 0), b.width, area.width - 40)
165
+ const w = Math.min(fitted.w, b.width), height = Math.min(fitted.h, b.height)
166
+ const x = Math.max(area.x, Math.min(b.x, area.x + area.width - w))
167
+ const y = Math.max(area.y, Math.min(b.y, area.y + area.height - height))
168
+ if (w !== b.width || height !== b.height || x !== b.x || y !== b.y) popup.setBounds({ x, y, width: w, height })
169
+ }
170
+
171
+ function minimize() {
172
+ if (!popup || popup.isDestroyed() || minimized) return
173
+ minimized = popup.getBounds()
174
+ send('mode', 'min')
175
+ popup.setBounds({ x: minimized.x + minimized.width - DOT, y: minimized.y, width: DOT, height: DOT })
176
+ }
177
+
178
+ function restore() {
179
+ if (!popup || popup.isDestroyed() || !minimized) return
180
+ const b = minimized
181
+ minimized = null
182
+ popup.setBounds(b)
183
+ send('mode', 'full')
184
+ }
185
+
186
+ const send = (channel, data) => { if (popup && !popup.isDestroyed()) popup.webContents.send(channel, data) }
187
+ const sendDetail = (data) => { if (detail && !detail.isDestroyed()) detail.webContents.send('detail', data) }
188
+
189
+ // ---- the detail window: a big landscape window with the full explanation and everything behind it ----
190
+
191
+ function createDetail() {
192
+ const area = screen.getDisplayNearestPoint(screen.getCursorScreenPoint()).workArea
193
+ const w = Math.min(1180, area.width - 80), h = Math.min(Math.round(w * 0.62), area.height - 60)
194
+ detail = new BrowserWindow({
195
+ width: w, height: h, x: area.x + Math.round((area.width - w) / 2), y: area.y + Math.round((area.height - h) / 2),
196
+ show: false, frame: false, icon: lensIcon(256), resizable: true, minWidth: 720, minHeight: 420, backgroundColor: '#000000', title: 'Pocket Tutor',
197
+ webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, sandbox: true, nodeIntegration: false },
198
+ })
199
+ detail.loadFile(path.join(__dirname, 'ui', 'popup.html'), { query: { view: 'detail' } })
200
+ detail.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
201
+ detail.webContents.on('will-navigate', (e) => e.preventDefault())
202
+ detail.on('close', (e) => { if (!quitting) { e.preventDefault(); detail.hide() } })
203
+ return new Promise((r) => detail.webContents.once('did-finish-load', r))
204
+ }
205
+
206
+ async function openDetail() {
207
+ if (!last) return
208
+ const fresh = !detail || detail.isDestroyed()
209
+ if (fresh) await createDetail()
210
+ const L = last
211
+ const start = () => sendDetail({ id: L.id, phase: 'start', title: L.plan.concept, snippets: L.snippets, web: L.web,
212
+ related: L.plan.related, notes: L.notes, video: L.video })
213
+ start()
214
+ detail.show(); detail.focus()
215
+ if (L.detail) return sendDetail({ id: L.id, phase: 'answer', text: L.detail, done: true }) // already written
216
+ // more information, not just more room: gather wider before writing.
217
+ // Twice the code snippets, more of the graph, and the web when the box didn't search (unless the words
218
+ // only mean something in this project).
219
+ if (!L.gathered) {
220
+ L.gathered = true
221
+ const [more, web] = await Promise.all([
222
+ L.where.root ? project.searchCode(L.where.root, searchTerms(L.plan), { exact: firstLine(L.selection), max: cfg.max_snippets * 2, openFile: L.where.file }).catch(() => L.snippets) : L.snippets,
223
+ L.web.length || !L.plan.query ? L.web : search.webSearch(L.plan.query, cfg, cfg.web_results).catch(() => []),
224
+ ])
225
+ L.snippets = more.length >= L.snippets.length ? more : L.snippets
226
+ L.web = web
227
+ const g = cfg.remember ? graph.load(config.GRAPH) : graph.empty()
228
+ L.notes = graph.recall(g, `${L.plan.concept} ${L.plan.related.join(' ')} ${L.selection}`, L.where.root || null, 12)
229
+ start()
230
+ }
231
+ try {
232
+ const push = throttled((t) => sendDetail({ id: L.id, phase: 'answer', text: model.fixHeadings(t) }))
233
+ let text
234
+ try {
235
+ text = await model.chat(cfg, cfg.model, model.detailMessages(L.selection, L.where, L.snippets, L.web, L.notes), {
236
+ maxTokens: 8000, timeoutMs: 180000, onChunk: push })
237
+ } finally { push.cancel() }
238
+ L.detail = model.fixHeadings(text)
239
+ sendDetail({ id: L.id, phase: 'answer', text: L.detail, done: true })
240
+ } catch (e) { sendDetail({ id: L.id, phase: 'error', message: e.message }) }
241
+ }
242
+
243
+ // ---- follow-up questions: "I didn't understand", asked in the box or in the detail window ----
244
+ // The question is masked like the selection, the model is told the explanation it gave, and the answer streams
245
+ // back into the window it was asked in. One at a time per lookup; a new lookup drops it.
246
+ async function ask({ question, view }) {
247
+ if (pending && view !== 'detail') {
248
+ const { id, where, title } = pending
249
+ pending = null
250
+ const text = mask(String(question || '')).trim().slice(0, model.MAX_SELECTION)
251
+ if (!text || id !== run) return
252
+ where.root = project.workspaceRoot(where, title, cfg.roots)
253
+ where.profile = project.profile(where.root)
254
+ current = { root: where.root || null }
255
+ send('state', { id, phase: 'start' })
256
+ return log(await explain(id, text, where))
257
+ }
258
+ const L = last
259
+ if (!L || L.asking || !cfg.llm_key) return
260
+ const to = view === 'detail' ? sendDetail : (d) => send('state', d)
261
+ const q = mask(String(question || '')).trim().slice(0, 500)
262
+ const history = L.qa[view === 'detail' ? 'detail' : 'box']
263
+ const explanation = view === 'detail' && L.detail ? L.detail : L.answer
264
+ L.asking = true
265
+ to({ id: L.id, phase: 'ask-start', q })
266
+ try {
267
+ const push = throttled((t) => last === L && to({ id: L.id, phase: 'ask-answer', text: t }))
268
+ let text
269
+ try {
270
+ text = await model.chat(cfg, cfg.model, model.followupMessages(L.selection, L.where, L.snippets, L.web, L.notes, explanation, history, q), {
271
+ maxTokens: 700, onChunk: push })
272
+ } finally { push.cancel() }
273
+ history.push({ q, a: text })
274
+ if (last === L) { to({ id: L.id, phase: 'ask-answer', text }); to({ id: L.id, phase: 'ask-done' }) }
275
+ } catch (e) { if (last === L) to({ id: L.id, phase: 'ask-error', message: e.message }) }
276
+ finally { L.asking = false }
277
+ }
278
+
279
+ // Streamed text arrives on every token (dozens a second). Redrawing the whole Markdown each time made the text shake.
280
+ // This passes the latest value on at most once per `ms`; cancel() before the final send so a late one can't overwrite it.
281
+ function throttled(fn, ms = 120) {
282
+ let lastRun = 0, timer = null, pending
283
+ const run = () => { timer = null; lastRun = Date.now(); fn(pending) }
284
+ const f = (v) => { pending = v; const wait = ms - (Date.now() - lastRun); if (wait <= 0) { clearTimeout(timer); run() } else if (!timer) timer = setTimeout(run, wait) }
285
+ f.cancel = () => { clearTimeout(timer); timer = null }
286
+ return f
287
+ }
288
+
289
+ let quitting = false
290
+ app.on('before-quit', () => { quitting = true })
291
+
292
+ // the app icon: a white lens on a dark rounded square, drawn into a BGRA bitmap at any size so no image file is needed
293
+ function lensIcon(n = 16) {
294
+ const buf = Buffer.alloc(n * n * 4)
295
+ const cx = n * 0.42, r = n * 0.26, w = Math.max(1.2, n * 0.075)
296
+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
297
+ // the dark rounded square
298
+ const dx = Math.max(Math.abs(x + 0.5 - n / 2) - (n / 2 - n * 0.2), 0), dy = Math.max(Math.abs(y + 0.5 - n / 2) - (n / 2 - n * 0.2), 0)
299
+ const inside = Math.hypot(dx, dy) <= n * 0.2
300
+ if (!inside) continue
301
+ let v = 0x14
302
+ // the ring and the handle, anti-aliased by distance
303
+ const d = Math.hypot(x + 0.5 - cx, y + 0.5 - cx)
304
+ const ring = Math.max(0, Math.min(1, w / 2 + 0.5 - Math.abs(d - r)))
305
+ const t = ((x + 0.5 - cx) + (y + 0.5 - cx)) / Math.SQRT2 - r // along the diagonal, from the ring outwards
306
+ const across = Math.abs((x + 0.5 - cx) - (y + 0.5 - cx)) / Math.SQRT2
307
+ const handle = t > -w * 0.2 && t < n * 0.26 ? Math.max(0, Math.min(1, w / 2 + 0.5 - across)) : 0
308
+ const a = Math.max(ring, handle)
309
+ v = Math.round(v + (0xf2 - v) * a)
310
+ buf.set([v, v, v, 0xff], (y * n + x) * 4)
311
+ }
312
+ return nativeImage.createFromBitmap(buf, { width: n, height: n })
313
+ }
314
+
315
+ function createTray() {
316
+ tray = new Tray(lensIcon(32))
317
+ tray.setToolTip(`Pocket Tutor: select text, then ${cfg.hotkey}`)
318
+ tray.setContextMenu(Menu.buildFromTemplate([
319
+ { label: `Explain selection (${cfg.hotkey})`, enabled: false },
320
+ { label: 'Reload settings', click: () => { cfg = config.load(); registerHotkey() } },
321
+ { label: 'Open settings folder', click: () => shell.openPath(config.HOME) },
322
+ { label: 'Forget saved context', click: () => { try { fs.rmSync(config.GRAPH, { force: true }) } catch (e) { log('forget:', e.message) } } },
323
+ { type: 'separator' },
324
+ { label: 'Quit Pocket Tutor', click: () => app.quit() },
325
+ ]))
326
+ }
327
+
328
+ // ---- the selection --------------------------------------------------------------------------------
329
+
330
+ // Copy what is selected in the window you were in, without losing what was on your clipboard.
331
+ async function grabSelection(terminal) {
332
+ const saved = { text: clipboard.readText(), html: clipboard.readHTML(), image: clipboard.readImage() }
333
+ clipboard.clear()
334
+ let text = ''
335
+ try {
336
+ await native.copy(terminal)
337
+ for (let i = 0; i < 20 && !text; i++) { // apps take a moment to fill the clipboard
338
+ await new Promise((r) => setTimeout(r, 40))
339
+ text = clipboard.readText()
340
+ }
341
+ } finally {
342
+ const restore = {}
343
+ if (saved.text) restore.text = saved.text
344
+ if (saved.html) restore.html = saved.html
345
+ if (!saved.image.isEmpty()) restore.image = saved.image
346
+ if (Object.keys(restore).length) clipboard.write(restore)
347
+ else clipboard.clear()
348
+ }
349
+ return text.trim()
350
+ }
351
+
352
+ // ---- one lookup -----------------------------------------------------------------------------------
353
+
354
+ const NO_MODEL = 'Pocket Tutor needs a model. Set a key (a free Vercel AI Gateway key works) or point it at any OpenAI-compatible server. Run pocket-tutor doctor, or see the README.'
355
+
356
+ async function lookup() {
357
+ const id = ++run
358
+ const fresh = () => id === run
359
+ let fg
360
+ try { fg = await native.foreground() } catch (e) { log('foreground:', e.message); return }
361
+ if (fg.pid === process.pid) return // the hotkey was pressed inside the box
362
+
363
+ const why = blocked(fg.app, fg.title)
364
+ const where = project.parseWindow(fg.app, fg.title)
365
+ if (why) {
366
+ send('state', { id, phase: 'blocked', message: `Pocket Tutor doesn't read text from ${why}.` })
367
+ return show()
368
+ }
369
+
370
+ pending = null
371
+ const raw = await grabSelection(where.kind === 'terminal')
372
+ if (!fresh()) return
373
+ if (!raw) {
374
+ // nothing selected: the box opens as a question line, and what you type is explained like a selection
375
+ if (!cfg.llm_key) { send('state', { id, phase: 'empty', message: NO_MODEL }); return show() }
376
+ pending = { id, where, title: fg.title }
377
+ send('state', { id, phase: 'ready' })
378
+ return show()
379
+ }
380
+ const selection = mask(raw).slice(0, model.MAX_SELECTION)
381
+ where.root = project.workspaceRoot(where, fg.title, cfg.roots)
382
+ where.profile = project.profile(where.root)
383
+ current = { root: where.root || null }
384
+
385
+ if (!cfg.llm_key) {
386
+ send('state', { id, phase: 'empty', message: NO_MODEL })
387
+ return show()
388
+ }
389
+ send('state', { id, phase: 'start' })
390
+ show()
391
+ const steps = await explain(id, selection, where)
392
+ log(steps)
393
+ }
394
+
395
+ // selection → plan → code + graph + web → answer → remember → picture. Sends each phase to the box.
396
+ async function explain(id, selection, where) {
397
+ const fresh = () => id === run
398
+ const t0 = Date.now()
399
+ const ms = () => `${Date.now() - t0} ms`
400
+
401
+ // 1. The answer doesn't wait for the planner (a whole model call, 1-1.6 s, and the free tier's rate limit
402
+ // counts it). A quick plan made without the model starts the searches at once; the planner runs
403
+ // alongside and feeds what comes after the answer: the graph, the math clip and the detail window.
404
+ const quick = model.quickPlan(selection, where)
405
+ const planP = model.chat(cfg, cfg.plan_model, model.planMessages(selection, where), { json: true, maxTokens: 400, timeoutMs: 20000 })
406
+ .then((r) => model.parsePlan(r, selection, where))
407
+ .catch((e) => { log('plan:', e.message); return model.fallbackPlan(selection, where) })
408
+
409
+ // 2. code, earlier context and the web, side by side. The web gets at most 2.5 s.
410
+ const g = cfg.remember ? graph.load(config.GRAPH) : graph.empty()
411
+ const notes = graph.recall(g, `${quick.concept} ${selection}`, where.root || null)
412
+ const codeP = where.root
413
+ ? project.searchCode(where.root, searchTerms(quick), { exact: firstLine(selection), max: cfg.max_snippets, openFile: where.file }).catch((e) => { log('code:', e.message); return [] })
414
+ : Promise.resolve([])
415
+ const webP = quick.web
416
+ ? Promise.race([search.webSearch(quick.query, cfg, cfg.web_results), new Promise((res) => setTimeout(() => res([]), 2500))]).catch((e) => { log('web:', e.message); return [] })
417
+ : Promise.resolve([])
418
+ const [snippets, web] = await Promise.all([codeP, webP])
419
+ if (!fresh()) return 'dropped after sources'
420
+ const tPlan = ms()
421
+ send('state', { id, phase: 'sources', snippets })
422
+
423
+ // 3. the answer
424
+ let answer = ''
425
+ try {
426
+ const push = throttled((text) => fresh() && send('state', { id, phase: 'answer', text }))
427
+ try {
428
+ answer = await model.chat(cfg, cfg.model, model.answerMessages(selection, where, snippets, web, notes), { maxTokens: 1200, onChunk: push })
429
+ } finally { push.cancel() }
430
+ if (fresh()) send('state', { id, phase: 'answer', text: answer })
431
+ } catch (e) {
432
+ if (fresh()) send('state', { id, phase: 'done', error: e.message })
433
+ return `answer failed: ${e.message}`
434
+ }
435
+ if (!fresh()) return 'dropped after answer'
436
+ // the planner has almost always finished by now; the box never waits more than 1.5 s more for it
437
+ const plan = (await Promise.race([planP, new Promise((res) => setTimeout(() => res(null), 1500))])) || quick
438
+ if (!fresh()) return 'dropped after plan'
439
+ const wantsPicture = plan.math && cfg.visuals && visual.available()
440
+ last = { id, selection, where, plan, snippets, web, notes, video: null, detail: null, answer, qa: { box: [], detail: [] }, asking: false }
441
+ if (plan === quick) planP.then((p) => { if (last && last.id === id) last.plan = p })
442
+ send('state', { id, phase: 'done', drawing: wantsPicture })
443
+ const tAnswer = ms()
444
+
445
+ // 4. remember it: the concept, what it connects to, and where it sits in this project
446
+ if (cfg.remember && answer) {
447
+ try {
448
+ const cited = snippets.filter((s) => answer.includes(`${s.file}:`))
449
+ graph.save(config.GRAPH, graph.remember(g, { concept: plan.concept, summary: mask(graph.summaryOf(answer)), related: plan.related,
450
+ files: (cited.length ? cited : snippets.slice(0, 2)).map((s) => ({ file: s.file, line: s.line })), root: where.root || null }))
451
+ } catch (e) { log('graph:', e.message) }
452
+ }
453
+
454
+ // 5. math only: a short ManimGL clip that builds the formula and explains each part
455
+ let drew = 'no clip'
456
+ if (wantsPicture) {
457
+ let video = null
458
+ try {
459
+ // the clip shows the selection's own formula, checked against docs/CLIP_RULES.md; one retry with the
460
+ // problems listed, then whatever still breaks a rule is dropped. A wrong clip is worse than none (R10).
461
+ const ask = async (problems) => visual.cleanSpec(model.parseJson(await model.chat(cfg, cfg.plan_model,
462
+ model.formulaMessages(plan.concept, answer, selection, problems), { json: true, maxTokens: 600, timeoutMs: 20000 })))
463
+ let spec = await ask([])
464
+ let problems = visual.checkSpec(spec, selection)
465
+ let tries = 1
466
+ if (spec && problems.length && fresh()) { spec = await ask(problems); problems = visual.checkSpec(spec, selection); tries = 2 }
467
+ spec = visual.settle(spec, problems)
468
+ if (spec && fresh()) video = `data:video/mp4;base64,${(await visual.render(spec)).toString('base64')}`
469
+ drew = spec ? `formula clip with ${spec.parts.length} parts after ${tries} ${tries > 1 ? 'tries' : 'try'} at ${ms()}`
470
+ : `no clip (${problems.map((p) => p.msg).join('; ').slice(0, 160) || 'no formula'})`
471
+ } catch (e) { drew = `math clip failed: ${e.message}${/trampoline|canonicalize|ENOENT/i.test(e.message) ? ' (run pocket-tutor setup-visuals again: the Python environment was moved or is broken)' : ''}` }
472
+ if (fresh()) { send('state', { id, phase: 'visual', video }); if (last && last.id === id) last.video = video }
473
+ }
474
+ return `"${plan.concept}"${plan.fallback ? ' (simple plan)' : ''} | sources at ${tPlan} | web ${quick.web ? web.length : 'skipped'} | ${snippets.length} snippets | ${notes.length} notes | answer ${tAnswer} | ${drew}`
475
+ }
476
+
477
+ // what to look for in the project: the planner's words, or at least the idea's own name (notes and docs
478
+ // talk about ideas by name; a Markdown selection once got no search words at all)
479
+ function searchTerms(plan) {
480
+ return plan.code_terms && plan.code_terms.length ? plan.code_terms : [plan.concept].filter(Boolean)
481
+ }
482
+
483
+ // the first line of a code selection, to find exactly where it sits in the project
484
+ function firstLine(selection) {
485
+ const line = selection.split(/\r?\n/).map((l) => l.trim()).find((l) => l.length >= 4)
486
+ return line && line.length <= 120 ? line : null
487
+ }
488
+
489
+ app.on('will-quit', () => { globalShortcut.unregisterAll(); if (native) native.stop() })
490
+ app.on('window-all-closed', (e) => e.preventDefault())