pocket-tutor 0.0.0-stage → 1.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +185 -2
  3. package/bin/pocket-tutor.js +127 -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 +526 -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/setup.js +60 -0
  26. package/src/themes/lens/lens.css +1165 -0
  27. package/src/themes/lens/lens.css.d.ts +9 -0
  28. package/src/themes/lens/lens.d.ts +14 -0
  29. package/src/themes/lens/lens.fonts.css +2 -0
  30. package/src/themes/lens/lens.js +627 -0
  31. package/src/themes/lens/lens.variants.d.ts +22 -0
  32. package/src/themes/lens/lensTheme.doc.mjs +10 -0
  33. package/src/themes/lens/lensTheme.ts +2 -0
  34. package/src/tools.js +102 -0
  35. package/src/ui/app.jsx +268 -0
  36. package/src/ui/dist/assets/KaTeX_AMS-Regular-CYEKBG2K.woff +0 -0
  37. package/src/ui/dist/assets/KaTeX_AMS-Regular-JKX5W2C4.ttf +0 -0
  38. package/src/ui/dist/assets/KaTeX_AMS-Regular-U6PRYMIZ.woff2 +0 -0
  39. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-5QL5CMTE.woff2 +0 -0
  40. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-WZ3QSGD3.woff +0 -0
  41. package/src/ui/dist/assets/KaTeX_Caligraphic-Bold-ZTS3R3HK.ttf +0 -0
  42. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-3LKEU76G.woff +0 -0
  43. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-A7XRTZ5Q.ttf +0 -0
  44. package/src/ui/dist/assets/KaTeX_Caligraphic-Regular-KX5MEWCF.woff2 +0 -0
  45. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-2QVFK6NQ.woff2 +0 -0
  46. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-T4SWXBMT.woff +0 -0
  47. package/src/ui/dist/assets/KaTeX_Fraktur-Bold-WGHVTYOR.ttf +0 -0
  48. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-2PEIFJSJ.woff2 +0 -0
  49. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-5U4OPH2X.ttf +0 -0
  50. package/src/ui/dist/assets/KaTeX_Fraktur-Regular-PQMHCIK6.woff +0 -0
  51. package/src/ui/dist/assets/KaTeX_Main-Bold-2GA4IZIN.woff +0 -0
  52. package/src/ui/dist/assets/KaTeX_Main-Bold-W5FBVCZM.ttf +0 -0
  53. package/src/ui/dist/assets/KaTeX_Main-Bold-YP5VVQRP.woff2 +0 -0
  54. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-4P4C7HJH.woff +0 -0
  55. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-N4V3DX7S.woff2 +0 -0
  56. package/src/ui/dist/assets/KaTeX_Main-BoldItalic-ODMLBJJQ.ttf +0 -0
  57. package/src/ui/dist/assets/KaTeX_Main-Italic-I43T2HSR.ttf +0 -0
  58. package/src/ui/dist/assets/KaTeX_Main-Italic-RELBIK7M.woff2 +0 -0
  59. package/src/ui/dist/assets/KaTeX_Main-Italic-SASNQFN2.woff +0 -0
  60. package/src/ui/dist/assets/KaTeX_Main-Regular-ARRPAO67.woff2 +0 -0
  61. package/src/ui/dist/assets/KaTeX_Main-Regular-P5I74A2A.woff +0 -0
  62. package/src/ui/dist/assets/KaTeX_Main-Regular-W74P5G27.ttf +0 -0
  63. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-6EBV3DK5.woff +0 -0
  64. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-K4WTGH3J.woff2 +0 -0
  65. package/src/ui/dist/assets/KaTeX_Math-BoldItalic-VB447A4D.ttf +0 -0
  66. package/src/ui/dist/assets/KaTeX_Math-Italic-6KGCHLFN.woff2 +0 -0
  67. package/src/ui/dist/assets/KaTeX_Math-Italic-KKK3USB2.woff +0 -0
  68. package/src/ui/dist/assets/KaTeX_Math-Italic-SON4MRCA.ttf +0 -0
  69. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-RRNVJFFW.woff2 +0 -0
  70. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-STQ6RXC7.ttf +0 -0
  71. package/src/ui/dist/assets/KaTeX_SansSerif-Bold-X5M5EMOD.woff +0 -0
  72. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-HMPFTM52.woff2 +0 -0
  73. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-PSN4QKYX.woff +0 -0
  74. package/src/ui/dist/assets/KaTeX_SansSerif-Italic-WTBAZBGY.ttf +0 -0
  75. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-2TL3USAE.ttf +0 -0
  76. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-OQCII6EP.woff +0 -0
  77. package/src/ui/dist/assets/KaTeX_SansSerif-Regular-XIQ62X4E.woff2 +0 -0
  78. package/src/ui/dist/assets/KaTeX_Script-Regular-72OLXYNA.ttf +0 -0
  79. package/src/ui/dist/assets/KaTeX_Script-Regular-A5IFOEBS.woff +0 -0
  80. package/src/ui/dist/assets/KaTeX_Script-Regular-APUWIHLP.woff2 +0 -0
  81. package/src/ui/dist/assets/KaTeX_Size1-Regular-4HRHTS65.woff +0 -0
  82. package/src/ui/dist/assets/KaTeX_Size1-Regular-5LRUTBFT.woff2 +0 -0
  83. package/src/ui/dist/assets/KaTeX_Size1-Regular-7K6AASVL.ttf +0 -0
  84. package/src/ui/dist/assets/KaTeX_Size2-Regular-222HN3GT.ttf +0 -0
  85. package/src/ui/dist/assets/KaTeX_Size2-Regular-K5ZHAIS6.woff +0 -0
  86. package/src/ui/dist/assets/KaTeX_Size2-Regular-LELKET5D.woff2 +0 -0
  87. package/src/ui/dist/assets/KaTeX_Size3-Regular-TLFPAHDE.woff +0 -0
  88. package/src/ui/dist/assets/KaTeX_Size3-Regular-UFCO6WCA.ttf +0 -0
  89. package/src/ui/dist/assets/KaTeX_Size3-Regular-WQRQ47UD.woff2 +0 -0
  90. package/src/ui/dist/assets/KaTeX_Size4-Regular-7PGNVPQK.ttf +0 -0
  91. package/src/ui/dist/assets/KaTeX_Size4-Regular-CDMV7U5C.woff2 +0 -0
  92. package/src/ui/dist/assets/KaTeX_Size4-Regular-PKMWZHNC.woff +0 -0
  93. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-3F5K6SQ6.ttf +0 -0
  94. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-MJMFSK64.woff +0 -0
  95. package/src/ui/dist/assets/KaTeX_Typewriter-Regular-VBYJ4NRC.woff2 +0 -0
  96. package/src/ui/dist/assets/figtree-latin-400-normal-PORFSHKN.woff2 +0 -0
  97. package/src/ui/dist/assets/figtree-latin-500-normal-AHYR5JKA.woff2 +0 -0
  98. package/src/ui/dist/assets/figtree-latin-600-normal-5C6Z7QEI.woff2 +0 -0
  99. package/src/ui/dist/assets/figtree-latin-700-normal-M33EANAW.woff2 +0 -0
  100. package/src/ui/dist/assets/figtree-latin-ext-400-normal-CK4ZBFIX.woff2 +0 -0
  101. package/src/ui/dist/assets/figtree-latin-ext-500-normal-M4H6A6MQ.woff2 +0 -0
  102. package/src/ui/dist/assets/figtree-latin-ext-600-normal-KUZFNAIE.woff2 +0 -0
  103. package/src/ui/dist/assets/figtree-latin-ext-700-normal-U3DQVDYX.woff2 +0 -0
  104. package/src/ui/dist/popup.css +1 -0
  105. package/src/ui/dist/popup.js +546 -0
  106. package/src/ui/popup.html +13 -0
  107. package/src/ui/state.js +89 -0
  108. package/src/visual.js +229 -0
package/src/helper.ps1 ADDED
@@ -0,0 +1,67 @@
1
+ # Pocket Tutor's hands. Started once by native.js and kept running, so the Win32 code below compiles only once.
2
+ # Reads one command per line on stdin, answers one JSON line on stdout:
3
+ # fg -> {"app": "...", "title": "...", "pid": n} the window you were in when you pressed the hotkey
4
+ # copy -> {"ok": true} waits until you let go of Shift/Alt/Win/Space, then presses Ctrl+C
5
+ # copyterminal -> {"ok": true} the same with Ctrl+Shift+C, because Ctrl+C in a terminal stops the running program
6
+ # It never reads the clipboard or writes anything to disk; main.js does the clipboard.
7
+
8
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
9
+ Add-Type @"
10
+ using System;
11
+ using System.Runtime.InteropServices;
12
+ using System.Text;
13
+ using System.Threading;
14
+ public static class LensWin {
15
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
16
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
17
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n);
18
+ [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vk);
19
+ [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
20
+ const uint UP = 0x0002;
21
+ public static string Title(IntPtr h) { var s = new StringBuilder(512); GetWindowText(h, s, 512); return s.ToString(); }
22
+ static bool Down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; }
23
+ // Shift, Alt, left/right Win, Space: wait (at most 1.5 s) so they don't turn Ctrl+C into another shortcut
24
+ public static void WaitForRelease() {
25
+ for (int i = 0; i < 75; i++) {
26
+ if (!Down(0x10) && !Down(0x12) && !Down(0x5B) && !Down(0x5C) && !Down(0x20)) return;
27
+ Thread.Sleep(20);
28
+ }
29
+ }
30
+ public static void Copy(bool terminal) {
31
+ WaitForRelease();
32
+ keybd_event(0x11, 0, 0, UIntPtr.Zero); // Ctrl down
33
+ if (terminal) keybd_event(0x10, 0, 0, UIntPtr.Zero); // Shift down
34
+ keybd_event(0x43, 0, 0, UIntPtr.Zero); // C
35
+ keybd_event(0x43, 0, UP, UIntPtr.Zero);
36
+ if (terminal) keybd_event(0x10, 0, UP, UIntPtr.Zero);
37
+ keybd_event(0x11, 0, UP, UIntPtr.Zero);
38
+ }
39
+ }
40
+ "@
41
+
42
+ [Console]::Out.WriteLine('{"ready":true}')
43
+ [Console]::Out.Flush()
44
+ while ($true) {
45
+ $cmd = [Console]::In.ReadLine()
46
+ if ($null -eq $cmd) { break }
47
+ $cmd = $cmd.Trim()
48
+ try {
49
+ if ($cmd -eq 'fg') {
50
+ $h = [LensWin]::GetForegroundWindow()
51
+ $procId = [uint32]0
52
+ [void][LensWin]::GetWindowThreadProcessId($h, [ref]$procId)
53
+ $name = ''
54
+ try { $name = (Get-Process -Id $procId -ErrorAction Stop).ProcessName } catch {}
55
+ $out = @{ app = $name.ToLower(); title = [LensWin]::Title($h); pid = $procId } | ConvertTo-Json -Compress
56
+ } elseif ($cmd -eq 'copy' -or $cmd -eq 'copyterminal') {
57
+ [LensWin]::Copy($cmd -eq 'copyterminal')
58
+ $out = '{"ok":true}'
59
+ } else {
60
+ $out = (@{ error = "unknown command: $cmd" } | ConvertTo-Json -Compress)
61
+ }
62
+ } catch {
63
+ $out = (@{ error = $_.Exception.Message } | ConvertTo-Json -Compress)
64
+ }
65
+ [Console]::Out.WriteLine($out)
66
+ [Console]::Out.Flush()
67
+ }
package/src/main.js ADDED
@@ -0,0 +1,526 @@
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
+ // POCKET_TUTOR_SELFTEST_SHAKE=1: stream a long answer into the detail window in small chunks and measure, after
88
+ // every chunk, whether any block that was already on screen moved or vanished. Appending text must never do that.
89
+ if (process.env.POCKET_TUTOR_SELFTEST_SHAKE) {
90
+ last = { id: 1, selection: 'RMSNorm', where: {}, plan: { concept: 'RMSNorm', related: ['LayerNorm'] }, snippets: [], web: [], notes: [], video: null, detail: '' }
91
+ await createDetail()
92
+ detail.show()
93
+ sendDetail({ id: 1, phase: 'start', title: 'RMSNorm', snippets: [], web: [], related: ['LayerNorm'], notes: [], video: null })
94
+ const para = 'RMSNorm keeps the numbers in a layer at a steady size, so training stays stable and the next layer sees values it can use. '
95
+ const doc = ['## What it is', para.repeat(3), '## How it works', '1. Square every number in the vector.\n2. Average the squares.\n3. Take the square root and divide.',
96
+ '```python\nclass RMSNorm(nn.Module):\n def forward(self, x):\n return x / x.pow(2).mean(-1, keepdim=True).sqrt()\n```',
97
+ 'The scale is $\gamma \cdot \frac{x}{\sqrt{\frac{1}{d}\sum_i x_i^2}}$ for each vector.', '$$y = \frac{x}{\text{RMS}(x)} \cdot g$$',
98
+ '## Why it matters', para.repeat(6), '## Example', para.repeat(4)].join('\n\n')
99
+ const probe = `(() => [...document.querySelectorAll('h1,h2,h3,p,li,pre')].map((e) => [(e.textContent || '').trim().slice(0, 24), Math.round(e.getBoundingClientRect().top + window.scrollY)]))()`
100
+ let prev = [], moved = 0, vanished = 0, frames = 0, shrank = 0, lastH = 0
101
+ const lines = []
102
+ for (let i = 40; i <= doc.length + 40; i += 40) {
103
+ sendDetail({ id: 1, phase: 'answer', text: model.fixHeadings(doc.slice(0, i)) })
104
+ await new Promise((r) => setTimeout(r, 140))
105
+ const now = await detail.webContents.executeJavaScript(probe)
106
+ frames++
107
+ // the page must only grow while text is added: a shrink means something was drawn one way, then redrawn
108
+ const h = await detail.webContents.executeJavaScript('document.documentElement.scrollHeight')
109
+ if (h < lastH - 2) { shrank++; lines.push(`frame ${frames}: page got shorter ${lastH} -> ${h}`) }
110
+ lastH = h
111
+ // every block but the newest one was complete before this chunk: it must still be there, in the same place
112
+ for (let k = 0; k < prev.length - 1; k++) {
113
+ if (!now[k] || now[k][0] !== prev[k][0]) { vanished++; lines.push(`frame ${frames}: block ${k} "${prev[k][0]}" changed or vanished`); break }
114
+ if (now[k][1] !== prev[k][1]) { moved++; lines.push(`frame ${frames}: block ${k} "${prev[k][0]}" moved ${prev[k][1]} -> ${now[k][1]}`) }
115
+ }
116
+ prev = now
117
+ }
118
+ sendDetail({ id: 1, phase: 'answer', text: model.fixHeadings(doc), done: true })
119
+ log(`shake test: ${frames} frames, ${moved} moves of earlier blocks, ${vanished} vanished or rewritten blocks, ${shrank} times the page got shorter`)
120
+ for (const l of lines.slice(0, 12)) log(' ', l)
121
+ return app.exit(moved || vanished || shrank ? 1 : 0)
122
+ }
123
+ send('state', { id: 1, phase: 'start' })
124
+ send('state', { id: 1, phase: 'sources', snippets: [{ file: 'src/model/norm.py', line: 7 }] })
125
+ 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$.' })
126
+ const clip = process.env.POCKET_TUTOR_SELFTEST_VIDEO
127
+ send('state', { id: 1, phase: 'done', drawing: !!clip })
128
+ if (clip) send('state', { id: 1, phase: 'visual', video: `data:video/mp4;base64,${fs.readFileSync(clip).toString('base64')}` })
129
+ show()
130
+ await new Promise((r) => setTimeout(r, 3000))
131
+ fs.writeFileSync(out, (await popup.webContents.capturePage()).toPNG())
132
+ log('box size', popup.getSize().join('x'))
133
+ if (process.env.POCKET_TUTOR_SELFTEST_DETAIL) {
134
+ const video = clip ? `data:video/mp4;base64,${fs.readFileSync(clip).toString('base64')}` : null
135
+ last = { id: 1, selection: 'RMSNorm', where: {}, plan: { concept: 'RMSNorm', related: ['LayerNorm', 'Pre-norm Transformer'] },
136
+ 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__()' }],
137
+ web: [{ title: 'Root Mean Square Layer Normalization', url: 'https://arxiv.org/abs/1910.07467', site: 'arxiv.org' }],
138
+ notes: ['- LayerNorm: normalizes with mean and variance'], video,
139
+ 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.' }
140
+ await openDetail()
141
+ await new Promise((r) => setTimeout(r, 2500))
142
+ fs.writeFileSync(out.replace(/\.png$/, '_detail.png'), (await detail.webContents.capturePage()).toPNG())
143
+ log('detail size', detail.getSize().join('x'))
144
+ quitting = true
145
+ }
146
+ if (process.env.POCKET_TUTOR_SELFTEST_MIN) {
147
+ minimize()
148
+ await new Promise((r) => setTimeout(r, 800))
149
+ fs.writeFileSync(out.replace(/\.png$/, '_min.png'), (await popup.webContents.capturePage()).toPNG())
150
+ log('dot size', popup.getSize().join('x'))
151
+ }
152
+ app.quit()
153
+ })
154
+ }
155
+
156
+ function registerHotkey() {
157
+ globalShortcut.unregisterAll()
158
+ const ok = globalShortcut.register(cfg.hotkey, () => lookup().catch((e) => log('lookup failed:', e.message)))
159
+ log(ok ? `hotkey ${cfg.hotkey}` : `could not register ${cfg.hotkey}; another app owns it. Set "hotkey" in ${config.FILE}`)
160
+ if (tray) tray.setToolTip(ok ? `Pocket Tutor: select text, then ${cfg.hotkey}` : `Pocket Tutor: hotkey ${cfg.hotkey} is taken`)
161
+ }
162
+
163
+ // ---- the box ----------------------------------------------------------------------------------------
164
+
165
+ function createPopup() {
166
+ popup = new BrowserWindow({
167
+ width: BOX.minW, height: BOX.minH, show: false, frame: false, icon: lensIcon(256), resizable: false, skipTaskbar: true, alwaysOnTop: true,
168
+ minimizable: false, maximizable: false, fullscreenable: false, backgroundColor: '#000000', transparent: false,
169
+ webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, sandbox: true, nodeIntegration: false },
170
+ })
171
+ popup.loadFile(path.join(__dirname, 'ui', 'popup.html'))
172
+ // links never navigate the box itself
173
+ popup.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
174
+ popup.webContents.on('will-navigate', (e) => e.preventDefault())
175
+ }
176
+
177
+ function hide() { if (popup && !popup.isDestroyed()) popup.hide() }
178
+
179
+ function show() {
180
+ if (minimized) restore()
181
+ const cursor = screen.getCursorScreenPoint()
182
+ const area = screen.getDisplayNearestPoint(cursor).workArea
183
+ // each lookup opens at one landscape size and keeps it while the answer is written; fit() runs once it is done
184
+ const { x, y } = placeNear(cursor, BOX.work, area)
185
+ popup.setBounds({ x, y, width: BOX.work.w, height: BOX.work.h })
186
+ popup.show()
187
+ popup.focus()
188
+ }
189
+
190
+ // the page says how tall its content is at the current width; the box follows, always wider than tall,
191
+ // widening when the text gets long (place.js fitBox), and kept on the screen
192
+ function fit(h, measuredAt) {
193
+ if (!popup || popup.isDestroyed() || minimized) return
194
+ const b = popup.getBounds()
195
+ // a report measured before the last resize is stale; acting on it widened the box all the way to the maximum
196
+ if (process.env.POCKET_TUTOR_DEBUG_FIT) log('fit', h, 'measured at', measuredAt, 'window', b.width)
197
+ if (measuredAt && Math.abs(measuredAt - b.width) > 4) return
198
+ const area = screen.getDisplayMatching(b).workArea
199
+ // never bigger than it opened: a long answer scrolls
200
+ const fitted = fitBox(Math.ceil(Number(h) || 0), b.width, area.width - 40)
201
+ const w = Math.min(fitted.w, b.width), height = Math.min(fitted.h, b.height)
202
+ const x = Math.max(area.x, Math.min(b.x, area.x + area.width - w))
203
+ const y = Math.max(area.y, Math.min(b.y, area.y + area.height - height))
204
+ if (w !== b.width || height !== b.height || x !== b.x || y !== b.y) popup.setBounds({ x, y, width: w, height })
205
+ }
206
+
207
+ function minimize() {
208
+ if (!popup || popup.isDestroyed() || minimized) return
209
+ minimized = popup.getBounds()
210
+ send('mode', 'min')
211
+ popup.setBounds({ x: minimized.x + minimized.width - DOT, y: minimized.y, width: DOT, height: DOT })
212
+ }
213
+
214
+ function restore() {
215
+ if (!popup || popup.isDestroyed() || !minimized) return
216
+ const b = minimized
217
+ minimized = null
218
+ popup.setBounds(b)
219
+ send('mode', 'full')
220
+ }
221
+
222
+ const send = (channel, data) => { if (popup && !popup.isDestroyed()) popup.webContents.send(channel, data) }
223
+ const sendDetail = (data) => { if (detail && !detail.isDestroyed()) detail.webContents.send('detail', data) }
224
+
225
+ // ---- the detail window: a big landscape window with the full explanation and everything behind it ----
226
+
227
+ function createDetail() {
228
+ const area = screen.getDisplayNearestPoint(screen.getCursorScreenPoint()).workArea
229
+ const w = Math.min(1180, area.width - 80), h = Math.min(Math.round(w * 0.62), area.height - 60)
230
+ detail = new BrowserWindow({
231
+ width: w, height: h, x: area.x + Math.round((area.width - w) / 2), y: area.y + Math.round((area.height - h) / 2),
232
+ show: false, frame: false, icon: lensIcon(256), resizable: true, minWidth: 720, minHeight: 420, backgroundColor: '#000000', title: 'Pocket Tutor',
233
+ webPreferences: { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, sandbox: true, nodeIntegration: false },
234
+ })
235
+ detail.loadFile(path.join(__dirname, 'ui', 'popup.html'), { query: { view: 'detail' } })
236
+ detail.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
237
+ detail.webContents.on('will-navigate', (e) => e.preventDefault())
238
+ detail.on('close', (e) => { if (!quitting) { e.preventDefault(); detail.hide() } })
239
+ return new Promise((r) => detail.webContents.once('did-finish-load', r))
240
+ }
241
+
242
+ async function openDetail() {
243
+ if (!last) return
244
+ const fresh = !detail || detail.isDestroyed()
245
+ if (fresh) await createDetail()
246
+ const L = last
247
+ const start = () => sendDetail({ id: L.id, phase: 'start', title: L.plan.concept, snippets: L.snippets, web: L.web,
248
+ related: L.plan.related, notes: L.notes, video: L.video })
249
+ start()
250
+ detail.show(); detail.focus()
251
+ if (L.detail) return sendDetail({ id: L.id, phase: 'answer', text: L.detail, done: true }) // already written
252
+ // more information, not just more room: gather wider before writing.
253
+ // Twice the code snippets, more of the graph, and the web when the box didn't search (unless the words
254
+ // only mean something in this project).
255
+ if (!L.gathered) {
256
+ L.gathered = true
257
+ const [more, web] = await Promise.all([
258
+ 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,
259
+ L.web.length || !L.plan.query ? L.web : search.webSearch(L.plan.query, cfg, cfg.web_results).catch(() => []),
260
+ ])
261
+ L.snippets = more.length >= L.snippets.length ? more : L.snippets
262
+ L.web = web
263
+ const g = cfg.remember ? graph.load(config.GRAPH) : graph.empty()
264
+ L.notes = graph.recall(g, `${L.plan.concept} ${L.plan.related.join(' ')} ${L.selection}`, L.where.root || null, 12)
265
+ start()
266
+ }
267
+ try {
268
+ const push = throttled((t) => sendDetail({ id: L.id, phase: 'answer', text: model.fixHeadings(t) }))
269
+ let text
270
+ try {
271
+ text = await model.chat(cfg, cfg.model, model.detailMessages(L.selection, L.where, L.snippets, L.web, L.notes), {
272
+ maxTokens: 8000, timeoutMs: 180000, onChunk: push })
273
+ } finally { push.cancel() }
274
+ L.detail = model.fixHeadings(text)
275
+ sendDetail({ id: L.id, phase: 'answer', text: L.detail, done: true })
276
+ } catch (e) { sendDetail({ id: L.id, phase: 'error', message: e.message }) }
277
+ }
278
+
279
+ // ---- follow-up questions: "I didn't understand", asked in the box or in the detail window ----
280
+ // The question is masked like the selection, the model is told the explanation it gave, and the answer streams
281
+ // back into the window it was asked in. One at a time per lookup; a new lookup drops it.
282
+ async function ask({ question, view }) {
283
+ if (pending && view !== 'detail') {
284
+ const { id, where, title } = pending
285
+ pending = null
286
+ const text = mask(String(question || '')).trim().slice(0, model.MAX_SELECTION)
287
+ if (!text || id !== run) return
288
+ where.root = project.workspaceRoot(where, title, cfg.roots)
289
+ where.profile = project.profile(where.root)
290
+ current = { root: where.root || null }
291
+ send('state', { id, phase: 'start' })
292
+ return log(await explain(id, text, where))
293
+ }
294
+ const L = last
295
+ if (!L || L.asking || !cfg.llm_key) return
296
+ const to = view === 'detail' ? sendDetail : (d) => send('state', d)
297
+ const q = mask(String(question || '')).trim().slice(0, 500)
298
+ const history = L.qa[view === 'detail' ? 'detail' : 'box']
299
+ const explanation = view === 'detail' && L.detail ? L.detail : L.answer
300
+ L.asking = true
301
+ to({ id: L.id, phase: 'ask-start', q })
302
+ try {
303
+ const push = throttled((t) => last === L && to({ id: L.id, phase: 'ask-answer', text: t }))
304
+ let text
305
+ try {
306
+ text = await model.chat(cfg, cfg.model, model.followupMessages(L.selection, L.where, L.snippets, L.web, L.notes, explanation, history, q), {
307
+ maxTokens: 700, onChunk: push })
308
+ } finally { push.cancel() }
309
+ history.push({ q, a: text })
310
+ if (last === L) { to({ id: L.id, phase: 'ask-answer', text }); to({ id: L.id, phase: 'ask-done' }) }
311
+ } catch (e) { if (last === L) to({ id: L.id, phase: 'ask-error', message: e.message }) }
312
+ finally { L.asking = false }
313
+ }
314
+
315
+ // Streamed text arrives on every token (dozens a second). Redrawing the whole Markdown each time made the text shake.
316
+ // This passes the latest value on at most once per `ms`; cancel() before the final send so a late one can't overwrite it.
317
+ function throttled(fn, ms = 120) {
318
+ let lastRun = 0, timer = null, pending
319
+ const run = () => { timer = null; lastRun = Date.now(); fn(pending) }
320
+ const f = (v) => { pending = v; const wait = ms - (Date.now() - lastRun); if (wait <= 0) { clearTimeout(timer); run() } else if (!timer) timer = setTimeout(run, wait) }
321
+ f.cancel = () => { clearTimeout(timer); timer = null }
322
+ return f
323
+ }
324
+
325
+ let quitting = false
326
+ app.on('before-quit', () => { quitting = true })
327
+
328
+ // 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
329
+ function lensIcon(n = 16) {
330
+ const buf = Buffer.alloc(n * n * 4)
331
+ const cx = n * 0.42, r = n * 0.26, w = Math.max(1.2, n * 0.075)
332
+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
333
+ // the dark rounded square
334
+ 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)
335
+ const inside = Math.hypot(dx, dy) <= n * 0.2
336
+ if (!inside) continue
337
+ let v = 0x14
338
+ // the ring and the handle, anti-aliased by distance
339
+ const d = Math.hypot(x + 0.5 - cx, y + 0.5 - cx)
340
+ const ring = Math.max(0, Math.min(1, w / 2 + 0.5 - Math.abs(d - r)))
341
+ const t = ((x + 0.5 - cx) + (y + 0.5 - cx)) / Math.SQRT2 - r // along the diagonal, from the ring outwards
342
+ const across = Math.abs((x + 0.5 - cx) - (y + 0.5 - cx)) / Math.SQRT2
343
+ const handle = t > -w * 0.2 && t < n * 0.26 ? Math.max(0, Math.min(1, w / 2 + 0.5 - across)) : 0
344
+ const a = Math.max(ring, handle)
345
+ v = Math.round(v + (0xf2 - v) * a)
346
+ buf.set([v, v, v, 0xff], (y * n + x) * 4)
347
+ }
348
+ return nativeImage.createFromBitmap(buf, { width: n, height: n })
349
+ }
350
+
351
+ function createTray() {
352
+ tray = new Tray(lensIcon(32))
353
+ tray.setToolTip(`Pocket Tutor: select text, then ${cfg.hotkey}`)
354
+ tray.setContextMenu(Menu.buildFromTemplate([
355
+ { label: `Explain selection (${cfg.hotkey})`, enabled: false },
356
+ { label: 'Reload settings', click: () => { cfg = config.load(); registerHotkey() } },
357
+ { label: 'Open settings folder', click: () => shell.openPath(config.HOME) },
358
+ { label: 'Forget saved context', click: () => { try { fs.rmSync(config.GRAPH, { force: true }) } catch (e) { log('forget:', e.message) } } },
359
+ { type: 'separator' },
360
+ { label: 'Quit Pocket Tutor', click: () => app.quit() },
361
+ ]))
362
+ }
363
+
364
+ // ---- the selection --------------------------------------------------------------------------------
365
+
366
+ // Copy what is selected in the window you were in, without losing what was on your clipboard.
367
+ async function grabSelection(terminal) {
368
+ const saved = { text: clipboard.readText(), html: clipboard.readHTML(), image: clipboard.readImage() }
369
+ clipboard.clear()
370
+ let text = ''
371
+ try {
372
+ await native.copy(terminal)
373
+ for (let i = 0; i < 20 && !text; i++) { // apps take a moment to fill the clipboard
374
+ await new Promise((r) => setTimeout(r, 40))
375
+ text = clipboard.readText()
376
+ }
377
+ } finally {
378
+ const restore = {}
379
+ if (saved.text) restore.text = saved.text
380
+ if (saved.html) restore.html = saved.html
381
+ if (!saved.image.isEmpty()) restore.image = saved.image
382
+ if (Object.keys(restore).length) clipboard.write(restore)
383
+ else clipboard.clear()
384
+ }
385
+ return text.trim()
386
+ }
387
+
388
+ // ---- one lookup -----------------------------------------------------------------------------------
389
+
390
+ 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 setup, or see the README.'
391
+
392
+ async function lookup() {
393
+ const id = ++run
394
+ const fresh = () => id === run
395
+ let fg
396
+ try { fg = await native.foreground() } catch (e) { log('foreground:', e.message); return }
397
+ if (fg.pid === process.pid) return // the hotkey was pressed inside the box
398
+
399
+ const why = blocked(fg.app, fg.title)
400
+ const where = project.parseWindow(fg.app, fg.title)
401
+ if (why) {
402
+ send('state', { id, phase: 'blocked', message: `Pocket Tutor doesn't read text from ${why}.` })
403
+ return show()
404
+ }
405
+
406
+ pending = null
407
+ const raw = await grabSelection(where.kind === 'terminal')
408
+ if (!fresh()) return
409
+ if (!raw) {
410
+ // nothing selected: the box opens as a question line, and what you type is explained like a selection
411
+ if (!cfg.llm_key) { send('state', { id, phase: 'empty', message: NO_MODEL }); return show() }
412
+ pending = { id, where, title: fg.title }
413
+ send('state', { id, phase: 'ready' })
414
+ return show()
415
+ }
416
+ const selection = mask(raw).slice(0, model.MAX_SELECTION)
417
+ where.root = project.workspaceRoot(where, fg.title, cfg.roots)
418
+ where.profile = project.profile(where.root)
419
+ current = { root: where.root || null }
420
+
421
+ if (!cfg.llm_key) {
422
+ send('state', { id, phase: 'empty', message: NO_MODEL })
423
+ return show()
424
+ }
425
+ send('state', { id, phase: 'start' })
426
+ show()
427
+ const steps = await explain(id, selection, where)
428
+ log(steps)
429
+ }
430
+
431
+ // selection → plan → code + graph + web → answer → remember → picture. Sends each phase to the box.
432
+ async function explain(id, selection, where) {
433
+ const fresh = () => id === run
434
+ const t0 = Date.now()
435
+ const ms = () => `${Date.now() - t0} ms`
436
+
437
+ // 1. The answer doesn't wait for the planner (a whole model call, 1-1.6 s, and the free tier's rate limit
438
+ // counts it). A quick plan made without the model starts the searches at once; the planner runs
439
+ // alongside and feeds what comes after the answer: the graph, the math clip and the detail window.
440
+ const quick = model.quickPlan(selection, where)
441
+ const planP = model.chat(cfg, cfg.plan_model, model.planMessages(selection, where), { json: true, maxTokens: 400, timeoutMs: 20000 })
442
+ .then((r) => model.parsePlan(r, selection, where))
443
+ .catch((e) => { log('plan:', e.message); return model.fallbackPlan(selection, where) })
444
+
445
+ // 2. code, earlier context and the web, side by side. The web gets at most 2.5 s.
446
+ const g = cfg.remember ? graph.load(config.GRAPH) : graph.empty()
447
+ const notes = graph.recall(g, `${quick.concept} ${selection}`, where.root || null)
448
+ const codeP = where.root
449
+ ? project.searchCode(where.root, searchTerms(quick), { exact: firstLine(selection), max: cfg.max_snippets, openFile: where.file }).catch((e) => { log('code:', e.message); return [] })
450
+ : Promise.resolve([])
451
+ const webP = quick.web
452
+ ? Promise.race([search.webSearch(quick.query, cfg, cfg.web_results), new Promise((res) => setTimeout(() => res([]), 2500))]).catch((e) => { log('web:', e.message); return [] })
453
+ : Promise.resolve([])
454
+ const [snippets, web] = await Promise.all([codeP, webP])
455
+ if (!fresh()) return 'dropped after sources'
456
+ const tPlan = ms()
457
+ send('state', { id, phase: 'sources', snippets })
458
+
459
+ // 3. the answer
460
+ let answer = ''
461
+ try {
462
+ const push = throttled((text) => fresh() && send('state', { id, phase: 'answer', text }))
463
+ try {
464
+ answer = await model.chat(cfg, cfg.model, model.answerMessages(selection, where, snippets, web, notes), { maxTokens: 1200, onChunk: push })
465
+ } finally { push.cancel() }
466
+ if (fresh()) send('state', { id, phase: 'answer', text: answer })
467
+ } catch (e) {
468
+ if (fresh()) send('state', { id, phase: 'done', error: e.message })
469
+ return `answer failed: ${e.message}`
470
+ }
471
+ if (!fresh()) return 'dropped after answer'
472
+ // the planner has almost always finished by now; the box never waits more than 1.5 s more for it
473
+ const plan = (await Promise.race([planP, new Promise((res) => setTimeout(() => res(null), 1500))])) || quick
474
+ if (!fresh()) return 'dropped after plan'
475
+ const wantsPicture = plan.math && cfg.visuals && visual.available()
476
+ last = { id, selection, where, plan, snippets, web, notes, video: null, detail: null, answer, qa: { box: [], detail: [] }, asking: false }
477
+ if (plan === quick) planP.then((p) => { if (last && last.id === id) last.plan = p })
478
+ send('state', { id, phase: 'done', drawing: wantsPicture })
479
+ const tAnswer = ms()
480
+
481
+ // 4. remember it: the concept, what it connects to, and where it sits in this project
482
+ if (cfg.remember && answer) {
483
+ try {
484
+ const cited = snippets.filter((s) => answer.includes(`${s.file}:`))
485
+ graph.save(config.GRAPH, graph.remember(g, { concept: plan.concept, summary: mask(graph.summaryOf(answer)), related: plan.related,
486
+ files: (cited.length ? cited : snippets.slice(0, 2)).map((s) => ({ file: s.file, line: s.line })), root: where.root || null }))
487
+ } catch (e) { log('graph:', e.message) }
488
+ }
489
+
490
+ // 5. math only: a short ManimGL clip that builds the formula and explains each part
491
+ let drew = 'no clip'
492
+ if (wantsPicture) {
493
+ let video = null
494
+ try {
495
+ // the clip shows the selection's own formula, checked against docs/CLIP_RULES.md; one retry with the
496
+ // problems listed, then whatever still breaks a rule is dropped. A wrong clip is worse than none (R10).
497
+ const ask = async (problems) => visual.cleanSpec(model.parseJson(await model.chat(cfg, cfg.plan_model,
498
+ model.formulaMessages(plan.concept, answer, selection, problems), { json: true, maxTokens: 600, timeoutMs: 20000 })))
499
+ let spec = await ask([])
500
+ let problems = visual.checkSpec(spec, selection)
501
+ let tries = 1
502
+ if (spec && problems.length && fresh()) { spec = await ask(problems); problems = visual.checkSpec(spec, selection); tries = 2 }
503
+ spec = visual.settle(spec, problems)
504
+ if (spec && fresh()) video = `data:video/mp4;base64,${(await visual.render(spec)).toString('base64')}`
505
+ drew = spec ? `formula clip with ${spec.parts.length} parts after ${tries} ${tries > 1 ? 'tries' : 'try'} at ${ms()}`
506
+ : `no clip (${problems.map((p) => p.msg).join('; ').slice(0, 160) || 'no formula'})`
507
+ } 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)' : ''}` }
508
+ if (fresh()) { send('state', { id, phase: 'visual', video }); if (last && last.id === id) last.video = video }
509
+ }
510
+ 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}`
511
+ }
512
+
513
+ // what to look for in the project: the planner's words, or at least the idea's own name (notes and docs
514
+ // talk about ideas by name; a Markdown selection once got no search words at all)
515
+ function searchTerms(plan) {
516
+ return plan.code_terms && plan.code_terms.length ? plan.code_terms : [plan.concept].filter(Boolean)
517
+ }
518
+
519
+ // the first line of a code selection, to find exactly where it sits in the project
520
+ function firstLine(selection) {
521
+ const line = selection.split(/\r?\n/).map((l) => l.trim()).find((l) => l.length >= 4)
522
+ return line && line.length <= 120 ? line : null
523
+ }
524
+
525
+ app.on('will-quit', () => { globalShortcut.unregisterAll(); if (native) native.stop() })
526
+ app.on('window-all-closed', (e) => e.preventDefault())