keepfold 0.6.4__py3-none-any.whl
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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,2712 @@
|
|
|
1
|
+
/* The Keepfold app page (docs/design/keepfold-app.md). Every string from the server goes in with
|
|
2
|
+
textContent; nothing here parses HTML. The key arrives once in the URL, then the URL is
|
|
3
|
+
cleaned and the key travels in the X-Keepfold-Token header. */
|
|
4
|
+
(() => {
|
|
5
|
+
'use strict';
|
|
6
|
+
// the key arrives once in the URL; this tab keeps it so a reload still works
|
|
7
|
+
let T = new URLSearchParams(location.search).get('t') || '';
|
|
8
|
+
try {
|
|
9
|
+
if (T) sessionStorage.setItem('keepfold.key', T); else T = sessionStorage.getItem('keepfold.key') || '';
|
|
10
|
+
} catch (e) { /* storage blocked: reopen the printed link after a reload */ }
|
|
11
|
+
history.replaceState(null, '', '/manage' + location.hash);
|
|
12
|
+
const $ = (id) => document.getElementById(id);
|
|
13
|
+
const SVGNS = 'http://www.w3.org/2000/svg';
|
|
14
|
+
const SECTIONS = ['tonight', 'setup', 'chat', 'status', 'review', 'xray', 'connect', 'llm', 'browse', 'vault'];
|
|
15
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
16
|
+
// resolves once the page shows (now if it does): hidden (the tray, minimised), nothing polls
|
|
17
|
+
const shown = () => new Promise((r) => {
|
|
18
|
+
if (!document.hidden) { r(); return; }
|
|
19
|
+
const on = () => { if (!document.hidden) { document.removeEventListener('visibilitychange', on); r(); } };
|
|
20
|
+
document.addEventListener('visibilitychange', on);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/* ---- DOM helpers ---- */
|
|
24
|
+
function h(tag, props, ...kids) {
|
|
25
|
+
const e = document.createElement(tag);
|
|
26
|
+
for (const [k, v] of Object.entries(props || {})) {
|
|
27
|
+
if (v == null || v === false) continue;
|
|
28
|
+
if (k === 'class') e.className = v;
|
|
29
|
+
else if (k === 'text') e.textContent = String(v);
|
|
30
|
+
else if (k === 'onclick' && tag === 'button') e.addEventListener('click', pressable(e, v));
|
|
31
|
+
else if (k.startsWith('on')) e.addEventListener(k.slice(2), v);
|
|
32
|
+
else if (k === 'value' || k === 'checked' || k === 'disabled') e[k] = v;
|
|
33
|
+
else e.setAttribute(k, v === true ? '' : String(v));
|
|
34
|
+
}
|
|
35
|
+
for (const c of kids.flat()) if (c != null && c !== false) e.append(c instanceof Node ? c : String(c));
|
|
36
|
+
return e;
|
|
37
|
+
}
|
|
38
|
+
function svgEl(tag, attrs) {
|
|
39
|
+
const e = document.createElementNS(SVGNS, tag);
|
|
40
|
+
for (const k in attrs || {}) e.setAttribute(k, attrs[k]);
|
|
41
|
+
return e;
|
|
42
|
+
}
|
|
43
|
+
// a click whose handler returns a promise (post, job, api, a copy) marks its button busy
|
|
44
|
+
// until it settles: aria-busy and the dots in app.css; a second click is ignored. Never
|
|
45
|
+
// disabled: that would drop keyboard focus to the page
|
|
46
|
+
function pressable(b, fn) {
|
|
47
|
+
return (ev) => {
|
|
48
|
+
if (b.getAttribute('aria-busy') === 'true') return undefined;
|
|
49
|
+
const r = fn(ev);
|
|
50
|
+
if (!r || typeof r.then !== 'function') return r;
|
|
51
|
+
b.setAttribute('aria-busy', 'true');
|
|
52
|
+
const done = () => b.removeAttribute('aria-busy');
|
|
53
|
+
r.then(done, done);
|
|
54
|
+
return r;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
const btn = (text, onclick, cls, extra) => h('button', { class: cls || 'btn', type: 'button', text, onclick, ...extra });
|
|
58
|
+
const ext = (href, text) => h('a', { href, text, target: '_blank', rel: 'noopener noreferrer' });
|
|
59
|
+
|
|
60
|
+
/* ---- dot matrix: the dashboard's authored 5x7 font, lit dots over the unlit cell ---- */
|
|
61
|
+
const FONT = {
|
|
62
|
+
0: [14, 17, 19, 21, 25, 17, 14], 1: [4, 12, 4, 4, 4, 4, 14], 2: [14, 17, 1, 2, 4, 8, 31],
|
|
63
|
+
3: [31, 2, 4, 2, 1, 17, 14], 4: [2, 6, 10, 18, 31, 2, 2], 5: [31, 16, 30, 1, 1, 17, 14],
|
|
64
|
+
6: [6, 8, 16, 30, 17, 17, 14], 7: [31, 1, 2, 4, 8, 8, 8], 8: [14, 17, 17, 14, 17, 17, 14],
|
|
65
|
+
9: [14, 17, 17, 15, 1, 2, 12], A: [14, 17, 17, 17, 31, 17, 17], B: [30, 17, 17, 30, 17, 17, 30],
|
|
66
|
+
C: [14, 17, 16, 16, 16, 17, 14], D: [28, 18, 17, 17, 17, 18, 28], E: [31, 16, 16, 30, 16, 16, 31],
|
|
67
|
+
F: [31, 16, 16, 30, 16, 16, 16], G: [14, 17, 16, 23, 17, 17, 15], H: [17, 17, 17, 31, 17, 17, 17],
|
|
68
|
+
I: [14, 4, 4, 4, 4, 4, 14], J: [7, 2, 2, 2, 2, 18, 12], K: [17, 18, 20, 24, 20, 18, 17],
|
|
69
|
+
L: [16, 16, 16, 16, 16, 16, 31], M: [17, 27, 21, 21, 17, 17, 17], N: [17, 17, 25, 21, 19, 17, 17],
|
|
70
|
+
O: [14, 17, 17, 17, 17, 17, 14], P: [30, 17, 17, 30, 16, 16, 16], Q: [14, 17, 17, 17, 21, 18, 13],
|
|
71
|
+
R: [30, 17, 17, 30, 20, 18, 17], S: [15, 16, 16, 14, 1, 1, 30], T: [31, 4, 4, 4, 4, 4, 4],
|
|
72
|
+
U: [17, 17, 17, 17, 17, 17, 14], V: [17, 17, 17, 17, 17, 10, 4], W: [17, 17, 17, 21, 21, 21, 10],
|
|
73
|
+
X: [17, 17, 10, 4, 10, 17, 17], Y: [17, 17, 17, 10, 4, 4, 4], Z: [31, 1, 2, 4, 8, 16, 31],
|
|
74
|
+
':': [0, 12, 12, 0, 12, 12, 0], '.': [0, 0, 0, 0, 0, 12, 12], '-': [0, 0, 0, 31, 0, 0, 0],
|
|
75
|
+
'/': [0, 1, 2, 4, 8, 16, 0], '+': [0, 4, 4, 31, 4, 4, 0], '%': [24, 25, 2, 4, 8, 19, 3],
|
|
76
|
+
' ': [0, 0, 0, 0, 0, 0, 0],
|
|
77
|
+
};
|
|
78
|
+
function dm(text, size, label) {
|
|
79
|
+
const t = String(text).toUpperCase();
|
|
80
|
+
const pitch = size + 1, r = size / 2, w = Math.max(1, t.length * 6 - 1) * pitch, ht = 7 * pitch;
|
|
81
|
+
let on = '', off = '';
|
|
82
|
+
[...t].forEach((ch, ci) => {
|
|
83
|
+
const rows = FONT[ch] || FONT[' '];
|
|
84
|
+
for (let y = 0; y < 7; y++) {
|
|
85
|
+
for (let x = 0; x < 5; x++) {
|
|
86
|
+
const cx = (ci * 6 + x) * pitch + pitch / 2, cy = y * pitch + pitch / 2;
|
|
87
|
+
const d = `M${cx - r} ${cy}a${r} ${r} 0 1 0 ${size} 0a${r} ${r} 0 1 0 ${-size} 0`;
|
|
88
|
+
if (rows[y] & (16 >> x)) on += d; else off += d;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
const s = svgEl('svg', { class: 'dm', viewBox: `0 0 ${w} ${ht}`, width: w, height: ht, role: 'img', 'aria-label': label || t });
|
|
93
|
+
s.append(svgEl('path', { class: 'off', d: off }), svgEl('path', { class: 'on', d: on }));
|
|
94
|
+
return s;
|
|
95
|
+
}
|
|
96
|
+
const ICONS = {
|
|
97
|
+
sun: ['M12 8a4 4 0 1 0 0.01 0', 'M12 2v2', 'M12 20v2', 'M2 12h2', 'M20 12h2', 'M4.9 4.9l1.4 1.4',
|
|
98
|
+
'M17.7 17.7l1.4 1.4', 'M4.9 19.1l1.4-1.4', 'M17.7 6.3l1.4-1.4'],
|
|
99
|
+
moon: ['M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z'],
|
|
100
|
+
copy: ['M9 9h10v10H9z', 'M5 15V5h10'],
|
|
101
|
+
check: ['M5 12.5l4.5 4.5L19 7.5'],
|
|
102
|
+
x: ['M6 6l12 12', 'M18 6L6 18'],
|
|
103
|
+
open: ['M14 4h6v6', 'M20 4l-9 9', 'M18 14v5H5V6h5'],
|
|
104
|
+
};
|
|
105
|
+
function icon(name) {
|
|
106
|
+
const s = svgEl('svg', { class: 'ico', viewBox: '0 0 24 24', 'aria-hidden': 'true' });
|
|
107
|
+
for (const d of ICONS[name]) s.append(svgEl('path', { d }));
|
|
108
|
+
return s;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/* ---- talking to the app ---- */
|
|
112
|
+
let dead = false;
|
|
113
|
+
// how this user reopens the app: the server says (the Start menu for an installer install)
|
|
114
|
+
const REOPEN = $('gone').getAttribute('data-reopen') || 'Run keepfold app again to reopen it.';
|
|
115
|
+
function gone(text) {
|
|
116
|
+
dead = true;
|
|
117
|
+
const g = $('gone');
|
|
118
|
+
if (text) g.textContent = text;
|
|
119
|
+
g.hidden = false;
|
|
120
|
+
for (const id of ['top', 'jobline', 'shell']) $(id).inert = true; // only the banner stays live
|
|
121
|
+
$('confirm').close();
|
|
122
|
+
}
|
|
123
|
+
async function api(path, body) {
|
|
124
|
+
let r;
|
|
125
|
+
try {
|
|
126
|
+
r = await fetch(path, body === undefined ? { headers: { 'X-Keepfold-Token': T } } : {
|
|
127
|
+
method: 'POST', headers: { 'X-Keepfold-Token': T, 'Content-Type': 'application/json' },
|
|
128
|
+
body: JSON.stringify(body),
|
|
129
|
+
});
|
|
130
|
+
} catch (e) {
|
|
131
|
+
gone();
|
|
132
|
+
throw new Error('The app is not answering.');
|
|
133
|
+
}
|
|
134
|
+
let data = {};
|
|
135
|
+
try { data = await r.json(); } catch (e) { /* no body */ }
|
|
136
|
+
if (r.status === 401) gone('This page lost its key. ' + REOPEN);
|
|
137
|
+
if (r.status === 409) poll(true); // busy: show the job this page did not start (an automatic import)
|
|
138
|
+
if (!r.ok) throw new Error(data.error || `The app answered ${r.status}.`);
|
|
139
|
+
return data;
|
|
140
|
+
}
|
|
141
|
+
/* toast: one message at a time; #toast-msg is the live region (role alert for an error).
|
|
142
|
+
The card stays in the page, faded out, so the region is always there to announce. */
|
|
143
|
+
let toastTimer = null, toastEnd = 0, toastLeft = 0, toastOn = false, toastHeld = false, toastAct = null;
|
|
144
|
+
function toastHide() {
|
|
145
|
+
clearTimeout(toastTimer);
|
|
146
|
+
if (toastAct) { toastAct.remove(); toastAct = null; }
|
|
147
|
+
toastTimer = null;
|
|
148
|
+
toastOn = false;
|
|
149
|
+
$('toast').classList.remove('on');
|
|
150
|
+
$('toast-x').hidden = true;
|
|
151
|
+
setTimeout(() => { if (!toastOn) $('toast-msg').textContent = ''; }, 120); // after the fade out
|
|
152
|
+
}
|
|
153
|
+
function toastRun(ms) {
|
|
154
|
+
clearTimeout(toastTimer);
|
|
155
|
+
toastEnd = Date.now() + ms;
|
|
156
|
+
toastTimer = setTimeout(toastHide, ms);
|
|
157
|
+
}
|
|
158
|
+
function toast(msg, long, kind, act) { // kind: 'error', 'ok' or none (info); act: [label, fn], a button after the text
|
|
159
|
+
const m = $('toast-msg');
|
|
160
|
+
m.setAttribute('role', kind === 'error' ? 'alert' : 'status');
|
|
161
|
+
m.textContent = msg;
|
|
162
|
+
if (toastAct) toastAct.remove();
|
|
163
|
+
toastAct = act ? btn(act[0], () => { toastHide(); act[1](); }) : null;
|
|
164
|
+
if (toastAct) m.after(toastAct);
|
|
165
|
+
$('toast').className = 'toast on' + (kind ? ' ' + kind : '');
|
|
166
|
+
$('toast-x').hidden = false;
|
|
167
|
+
toastOn = true;
|
|
168
|
+
toastLeft = long || kind === 'error' ? 6000 : Math.min(4000, 2500 + 25 * String(msg).length);
|
|
169
|
+
if (!toastHeld) toastRun(toastLeft);
|
|
170
|
+
}
|
|
171
|
+
toast.error = (msg) => toast(msg, true, 'error');
|
|
172
|
+
toast.ok = (msg) => toast(msg, false, 'ok');
|
|
173
|
+
// a screen reader hears a short confirmation (Saved, Copied) through the same live region
|
|
174
|
+
function announce(msg) {
|
|
175
|
+
if (toastOn) return; // a visible toast is being read already
|
|
176
|
+
const m = $('toast-msg');
|
|
177
|
+
m.setAttribute('role', 'status');
|
|
178
|
+
m.textContent = msg;
|
|
179
|
+
setTimeout(() => { if (!toastOn && m.textContent === msg) m.textContent = ''; }, 1500);
|
|
180
|
+
}
|
|
181
|
+
function toastHold() {
|
|
182
|
+
toastHeld = true;
|
|
183
|
+
if (toastTimer) { clearTimeout(toastTimer); toastTimer = null; toastLeft = Math.max(1000, toastEnd - Date.now()); }
|
|
184
|
+
}
|
|
185
|
+
function toastRelease() {
|
|
186
|
+
toastHeld = false;
|
|
187
|
+
if (toastOn) toastRun(toastLeft);
|
|
188
|
+
}
|
|
189
|
+
async function post(path, body, done) {
|
|
190
|
+
try {
|
|
191
|
+
const r = await api(path, body || {});
|
|
192
|
+
if (done) done(r);
|
|
193
|
+
return r;
|
|
194
|
+
} catch (e) {
|
|
195
|
+
toast.error(e.message);
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
// a check and a word beside a control for 1.5 s (a setting saved on change), also announced
|
|
200
|
+
function savedMark(ctrl) {
|
|
201
|
+
const mark = h('span', { class: 'saved', 'aria-hidden': 'true' }, icon('check'), 'Saved');
|
|
202
|
+
if (ctrl.parentNode && ctrl.parentNode.tagName === 'LABEL') ctrl.parentNode.append(mark);
|
|
203
|
+
else ctrl.after(mark);
|
|
204
|
+
announce('Saved');
|
|
205
|
+
setTimeout(() => mark.remove(), 1500);
|
|
206
|
+
}
|
|
207
|
+
// Copy: the label turns to a check and Copied for 1.5 s; a failure says so in a toast, or
|
|
208
|
+
// runs `onFail` (e.g. selects the text so Ctrl+C copies it)
|
|
209
|
+
function copyBtn(text, failMsg, cls, withIcon, onFail, onOk, label = 'Copy') {
|
|
210
|
+
const face = () => (withIcon ? [icon('copy'), label] : [label]);
|
|
211
|
+
let timer;
|
|
212
|
+
const b = btn('', () => Promise.resolve().then(text).then((t) => navigator.clipboard.writeText(t)).then(() => {
|
|
213
|
+
if (onOk) onOk();
|
|
214
|
+
clearTimeout(timer);
|
|
215
|
+
const ck = icon('check');
|
|
216
|
+
ck.classList.add('draw'); // the stroke is drawn (app.css .ico.draw)
|
|
217
|
+
b.replaceChildren(ck, 'Copied');
|
|
218
|
+
announce('Copied');
|
|
219
|
+
timer = setTimeout(() => b.replaceChildren(...face()), 1500);
|
|
220
|
+
}, () => (onFail ? onFail() : toast.error(failMsg))), cls);
|
|
221
|
+
b.replaceChildren(...face());
|
|
222
|
+
return b;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Motion (U2) is off under prefers-reduced-motion; every Web Animations call checks this first.
|
|
226
|
+
const still = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
227
|
+
// A number changed in place: the old text lies over it and fades out (--dur-1), the new fades in (--dur-2).
|
|
228
|
+
function crossFade(el, oldText) {
|
|
229
|
+
if (still() || !el.animate || !el.parentNode || !oldText) return;
|
|
230
|
+
const g = el.cloneNode(false);
|
|
231
|
+
g.className = (el.className ? el.className + ' ' : '') + 'xf-old';
|
|
232
|
+
g.textContent = oldText;
|
|
233
|
+
g.setAttribute('aria-hidden', 'true');
|
|
234
|
+
g.style.setProperty('left', el.offsetLeft + 'px');
|
|
235
|
+
g.style.setProperty('top', el.offsetTop + 'px');
|
|
236
|
+
el.after(g);
|
|
237
|
+
g.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 120, easing: 'cubic-bezier(.4,0,1,1)' }).finished.then(() => g.remove(), () => g.remove());
|
|
238
|
+
el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 200, easing: 'cubic-bezier(.2,.7,.2,1)' });
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/* ---- boards and rows ---- */
|
|
242
|
+
function board(title, opts, ...kids) {
|
|
243
|
+
const o = opts || {};
|
|
244
|
+
const band = h('div', { class: 'band' }, h('h2', { text: title }),
|
|
245
|
+
o.note != null ? h('span', { class: 'band-note' }, o.note) : null,
|
|
246
|
+
o.btn ? btn(o.btn[0], o.btn[1], 'band-btn', o.btn[2]) : null);
|
|
247
|
+
return h('div', { class: 'board' + (o.cls ? ' ' + o.cls : ''), id: o.id }, band, ...kids);
|
|
248
|
+
}
|
|
249
|
+
const STATE = { ok: ['●', 'Ready'], warn: ['◐', 'Check'], off: ['○', 'Off'], bad: ['↻', 'Failed'] };
|
|
250
|
+
function stateCell(s, word) {
|
|
251
|
+
return h('span', { class: 'state' }, h('span', { class: 'glyph g-' + s, 'aria-hidden': 'true', text: STATE[s][0] }),
|
|
252
|
+
' ' + (word || STATE[s][1]));
|
|
253
|
+
}
|
|
254
|
+
function row(title, value, sub, acts, cls) {
|
|
255
|
+
return h('div', { class: 'brow' + (cls ? ' ' + cls : '') },
|
|
256
|
+
h('div', { class: 't' },
|
|
257
|
+
h('div', { class: 'line1' }, h('span', { class: 'ttl', text: title }),
|
|
258
|
+
value != null && value !== '' ? h('span', { class: 'val', text: value, title: String(value) }) : null),
|
|
259
|
+
sub ? h('span', { class: 'sub', text: sub }) : null),
|
|
260
|
+
acts && acts.length ? h('div', { class: 'acts' }, ...acts) : null);
|
|
261
|
+
}
|
|
262
|
+
function note(text) { return h('p', { class: 'pad ink-2', text }); }
|
|
263
|
+
// the vault's note count, in words (Status's vault row, Dashboard and vault's Notes row)
|
|
264
|
+
const noteCount = (n) => h('span', { class: 'count', text: `${Number(n).toLocaleString('en-US')} note${Number(n) === 1 ? '' : 's'}` });
|
|
265
|
+
function fail(s, msg) {
|
|
266
|
+
$(s).replaceChildren(board('Not available', {}, note(msg)));
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/* ---- jobs: one at a time, a progress line under the header ---- */
|
|
270
|
+
const outputs = {};
|
|
271
|
+
let polling = false, pollAgain = false, hideTimer;
|
|
272
|
+
async function job(path, body) {
|
|
273
|
+
const r = await post(path, body);
|
|
274
|
+
if (r && r.disk) { // too little free space: nothing started; the owner may continue anyway
|
|
275
|
+
confirmDialog('Not enough free space', 'Continue anyway', [h('p', { class: 'ink-2', text: r.disk })],
|
|
276
|
+
() => job(path, { ...body, override: true }));
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
279
|
+
if (r) poll();
|
|
280
|
+
return r;
|
|
281
|
+
}
|
|
282
|
+
function showJob(j) {
|
|
283
|
+
clearTimeout(hideTimer);
|
|
284
|
+
const r = j.result || {};
|
|
285
|
+
const word = j.error ? 'failed' : r.cancelled ? 'cancelled' : r.need === 'embed' ? 'stopped: needs the search model' : r.need === 'voice' ? 'stopped: needs the speech model' : r.error === 'no_answer' ? 'no answer' : r.error ? 'stopped: needs setup' : r.ok === false ? 'failed' : 'done';
|
|
286
|
+
// running: the moving bar under the line; done: a brief success tint; failed: the error tint
|
|
287
|
+
$('jobline').classList.remove('idle', 'running', 'ok', 'bad', 'ended', 'determinate');
|
|
288
|
+
$('jobline').classList.add(j.running ? 'running' : word === 'done' ? 'ok' : word === 'failed' ? 'bad' : 'ended');
|
|
289
|
+
$('job-name').textContent = j.running ? j.name : `${j.name}: ${word}`;
|
|
290
|
+
// a stepped job: "Step 3 of 5 · checking titles · 42% · about 2 min left", a filling bar
|
|
291
|
+
const p = j.running ? j.progress : null;
|
|
292
|
+
if (p) {
|
|
293
|
+
$('jobline').classList.add('determinate');
|
|
294
|
+
$('jobline').style.setProperty('--pct', `${p.overall}%`);
|
|
295
|
+
$('jobline').style.setProperty('--f', String(p.overall / 100)); // the bar is scaleX(--f), app.css
|
|
296
|
+
}
|
|
297
|
+
// a finished job's error is the toast's (finish), so it shows once; the line says only "failed"
|
|
298
|
+
$('job-line').textContent = p ? stepText(p) : j.running ? j.line : '';
|
|
299
|
+
$('job-time').textContent = `${Math.round(j.seconds)} s`;
|
|
300
|
+
$('job-cancel').hidden = !(j.running && j.cancellable);
|
|
301
|
+
}
|
|
302
|
+
// initial: only a job still running (on open, the periodic look, a busy refusal); a job this
|
|
303
|
+
// page started while a look is under way is followed once that look ends, never dropped
|
|
304
|
+
async function poll(initial) {
|
|
305
|
+
if (polling) { if (!initial) pollAgain = true; return; }
|
|
306
|
+
polling = true;
|
|
307
|
+
try {
|
|
308
|
+
for (;;) {
|
|
309
|
+
if (pollAgain) { pollAgain = false; initial = false; }
|
|
310
|
+
const v = await api('/api/job');
|
|
311
|
+
const j = v.job;
|
|
312
|
+
if (!j || (initial && !j.running)) break; // on open: only a job still running
|
|
313
|
+
initial = false;
|
|
314
|
+
showJob(j);
|
|
315
|
+
const wl = wg.mine && $('wg-job'); // the welcome guide's own job: its line in the dialog too
|
|
316
|
+
if (wl) { wg.job = j; const n = wgJobLine(); wl.className = n.className; wl.textContent = n.textContent; }
|
|
317
|
+
if (!j.running) { finish(j); break; }
|
|
318
|
+
await sleep(600);
|
|
319
|
+
await shown();
|
|
320
|
+
}
|
|
321
|
+
} catch (e) { /* the app stopped: gone() said so */ } finally {
|
|
322
|
+
polling = false;
|
|
323
|
+
if (pollAgain && !dead) { pollAgain = false; poll(); }
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function stepText(p) {
|
|
327
|
+
const s = p.eta_s;
|
|
328
|
+
const left = s == null ? '' : s < 60 ? ' · less than a minute left'
|
|
329
|
+
: s < 3600 ? ` · about ${Math.round(s / 60)} min left` : ` · about ${Math.round(s / 3600)} h left`;
|
|
330
|
+
return `Step ${p.step} of ${p.steps} · ${p.label} · ${p.pct}%${left}`;
|
|
331
|
+
}
|
|
332
|
+
function idle() {
|
|
333
|
+
$('jobline').classList.remove('running', 'ok', 'bad', 'ended', 'determinate');
|
|
334
|
+
$('jobline').classList.add('idle');
|
|
335
|
+
$('job-name').textContent = 'Nothing running.';
|
|
336
|
+
$('job-line').textContent = '';
|
|
337
|
+
$('job-time').textContent = '';
|
|
338
|
+
$('job-cancel').hidden = true;
|
|
339
|
+
}
|
|
340
|
+
const jobFailed = (j) => { const r = j.result || {}; return !!j.error || (r.ok === false && !r.cancelled && !r.need); };
|
|
341
|
+
function finish(j) {
|
|
342
|
+
if (jobFailed(j)) toast.error(j.error || `${j.name}: failed.`);
|
|
343
|
+
else if (j.name === 'Setting up the vault' && j.result && j.result.vault) { // server.setup_vault's job
|
|
344
|
+
vaultChange.open = false;
|
|
345
|
+
vaultChange.text = '';
|
|
346
|
+
const r = j.result;
|
|
347
|
+
vaultChange.reconnect = !!r.reconnect; // AI apps still name the old folder: Connect's Apply moves them
|
|
348
|
+
if (r.reconnect) toast(`Keepfold now uses ${r.vault}. ${RECONNECT}`, true, null, ['Open Connect AI apps', () => show('connect', true)]);
|
|
349
|
+
else toast.ok(`Keepfold now uses ${r.vault}.`);
|
|
350
|
+
}
|
|
351
|
+
else if (j.section === 'connect' && !jobFailed(j)) vaultChange.reconnect = false;
|
|
352
|
+
else if (j.name === 'Start at login') toast.ok('The receiver now starts at login.'); // server.login's job name
|
|
353
|
+
if (wg.mine) { // the welcome guide's job ended: the step reads the new state
|
|
354
|
+
Object.assign(wg, { mine: false, job: j });
|
|
355
|
+
if (wg.open) wgLoad();
|
|
356
|
+
}
|
|
357
|
+
if (guide && guide.wait && j.section === 'setup') { // a guided import's own job: shown in its panel
|
|
358
|
+
const w = guide.wait;
|
|
359
|
+
guide.wait = null;
|
|
360
|
+
if (w === 'preview' && j.error) Object.assign(guide, { error: j.error, upload: null });
|
|
361
|
+
else if (w === 'preview') guide.preview = j.result;
|
|
362
|
+
else Object.assign(guide, { done: j, upload: j.result && j.result.need ? guide.upload : null });
|
|
363
|
+
} else if (j.section === 'update') { // shown in the Updates board
|
|
364
|
+
upd = j;
|
|
365
|
+
if (j.result && j.result.launched) gone('Keepfold is closing to install the update. It reopens by itself when it is done; you can close this tab.');
|
|
366
|
+
}
|
|
367
|
+
else {
|
|
368
|
+
// a command that stopped with an error (ok: false) failed too
|
|
369
|
+
outputs[j.section] = { title: j.name, nodes: resultNodes(j), error: jobFailed(j) };
|
|
370
|
+
if (desktopChanged(j)) toast(RESTART_DESKTOP, true);
|
|
371
|
+
}
|
|
372
|
+
hideTimer = setTimeout(idle, 8000);
|
|
373
|
+
if (current) load(current);
|
|
374
|
+
}
|
|
375
|
+
const RESTART_DESKTOP = 'Claude Desktop loads Keepfold only when it starts, and closing its window does not stop it: right-click the Claude icon near the clock (the tray; on a Mac, the menu bar), choose Quit, then open Claude again.';
|
|
376
|
+
const desktopChanged = (j) => j.section === 'connect' && !!j.result && (j.result.rows || []).some((x) => x.id === 'claude-desktop' && x.change !== 'error');
|
|
377
|
+
const OPS = { add: 'Add', update: 'Update', remove: 'Remove', ran: 'Ran', error: 'Error', none: '' };
|
|
378
|
+
function changeList(rows) {
|
|
379
|
+
return h('div', { class: 'pad' }, rows.map((r) => h('div', { class: 'chg' },
|
|
380
|
+
h('span', { class: 'op' + (r.change === 'error' ? ' g-bad' : ''), text: OPS[r.change] || r.change }),
|
|
381
|
+
h('strong', { text: r.label || '' }),
|
|
382
|
+
r.file ? h('span', { class: 'f mono', text: r.file }) : null,
|
|
383
|
+
r.detail ? h('span', { class: 'd', text: r.detail }) : null)));
|
|
384
|
+
}
|
|
385
|
+
function countsTable(obj) {
|
|
386
|
+
const keys = Object.keys(obj).sort();
|
|
387
|
+
return h('div', { class: 'table-scroll' }, h('table', {},
|
|
388
|
+
h('thead', {}, h('tr', {}, h('th', { text: 'What' }), h('th', { class: 'n', text: 'Count' }))),
|
|
389
|
+
h('tbody', {}, keys.map((k) => h('tr', {}, h('td', { text: k.replace(/_/g, ' ') }), h('td', { class: 'n', text: String(obj[k]) }))))));
|
|
390
|
+
}
|
|
391
|
+
function scanTable(rows) {
|
|
392
|
+
const cols = ['visits', 'searches', 'kept', 'private', 'dropped', 'maybe'];
|
|
393
|
+
return h('div', { class: 'table-scroll' }, h('table', {},
|
|
394
|
+
h('thead', {}, h('tr', {}, h('th', { text: 'Browser' }), h('th', { text: 'From' }), h('th', { text: 'To' }),
|
|
395
|
+
cols.map((c) => h('th', { class: 'n', text: c })))),
|
|
396
|
+
h('tbody', {}, rows.map((r) => h('tr', {}, h('td', { text: r.source }),
|
|
397
|
+
r.error ? h('td', { colspan: 2 + cols.length, text: 'not read' })
|
|
398
|
+
: [h('td', { text: r.first || '-' }), h('td', { text: r.last || '-' }),
|
|
399
|
+
cols.map((c) => h('td', { class: 'n', text: String(r[c] ?? 0) }))])))));
|
|
400
|
+
}
|
|
401
|
+
function resultNodes(j) {
|
|
402
|
+
const r = j.result || {};
|
|
403
|
+
const out = [];
|
|
404
|
+
if (j.error) out.push(row('Failed', null, j.error, null));
|
|
405
|
+
if (r.cancelled) out.push(row('Cancelled', null, 'Stopped before it finished; run it again any time.', null));
|
|
406
|
+
if (j.section === 'connect' && r.rows) out.push(r.rows.length ? changeList(r.rows) : note('Nothing changed.'));
|
|
407
|
+
if (desktopChanged(j)) out.push(row('Next: restart Claude Desktop', null, RESTART_DESKTOP, null));
|
|
408
|
+
if (r.kind === 'scan') out.push(r.rows.length ? scanTable(r.rows) : note('No browser history found on this computer.'));
|
|
409
|
+
if (r.kind === 'chat_eval') out.push(...chatEvalNodes(r));
|
|
410
|
+
if (r.counts) out.push(Object.keys(r.counts).length ? countsTable(r.counts) : note('Nothing to count.'));
|
|
411
|
+
if (r.answer) out.push(row('Answer', `${r.answer} in ${r.seconds} s`, r.runner, null));
|
|
412
|
+
if (r.admin) out.push(row('Install Git for everyone on this computer', null, r.admin,
|
|
413
|
+
[btn('Install Git for all users (Windows will ask for admin permission)', () => job('/api/setup/git', { scope: 'machine', from: j.section }), 'btn lit'), ext(r.license, 'License')]));
|
|
414
|
+
if (r.need === 'embed') out.push(row('Search model needed', null, r.lines[0], [btn('Download the search model', () => job('/api/setup/embed', {}), 'btn lit')]));
|
|
415
|
+
else if (r.lines && r.lines.length) out.push(h('pre', { class: 'out', text: r.lines.join('\n') }));
|
|
416
|
+
return out;
|
|
417
|
+
}
|
|
418
|
+
// the Chat test's summary (server.chat_eval): score, blockers, failures; all text, no markup
|
|
419
|
+
function chatEvalNodes(r) {
|
|
420
|
+
const blocked = r.blocked ? `${r.blocked} blocked${r.model ? '' : ` (${r.model_note})`}` : 'none blocked';
|
|
421
|
+
return [
|
|
422
|
+
row('Score', `${r.result}: ${r.passed} of ${r.ran} passed`, `${blocked} · the bar is ${r.bar} of ${r.total}${r.model ? ` · model ${r.model}` : ''}${r.stopped ? ' · stopped early' : ''} · vault ${r.manifest}`, null),
|
|
423
|
+
row('By query kind', null, Object.entries(r.queries).map(([k, v]) => `${k} ${v}`).join(' · '), null),
|
|
424
|
+
row('Misses', null, Object.entries(r.misses).map(([k, n]) => `${k.replace('_', ' ')} ${n}`).join(' · '), null),
|
|
425
|
+
row('Blockers', null, r.blockers.map((b) => `${b.state}: ${b.name}`).join(' · '), null),
|
|
426
|
+
r.failures.length
|
|
427
|
+
? h('ul', { class: 'pad' }, r.failures.map((f) => h('li', { text: `${f.id} ${f.question} · ${f.why} · Answer: ${f.answer}` })))
|
|
428
|
+
: note('No question failed.'),
|
|
429
|
+
];
|
|
430
|
+
}
|
|
431
|
+
function outputBoard(s) {
|
|
432
|
+
const o = outputs[s];
|
|
433
|
+
return o ? board(`Last action: ${o.title}`, { note: o.error ? 'failed' : 'finished' }, ...o.nodes) : null;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/* ---- sections ---- */
|
|
437
|
+
let current = null, landing = false; // landing: Status opened in place of the app's own choice
|
|
438
|
+
// A person's switch glides the nav highlight (View Transitions; app.css side-hl); the page itself
|
|
439
|
+
// swaps at once. Without the API, or under reduced motion, it is the plain switch.
|
|
440
|
+
function show(s, focus) {
|
|
441
|
+
if (focus) landing = false; // the user chose: Status's answer does not move them
|
|
442
|
+
if (!focus || s === current || !document.startViewTransition || still() || document.hidden) return showNow(s, focus);
|
|
443
|
+
document.startViewTransition(() => showNow(s, focus)).ready.catch(() => {}); // skipped: no glide, no harm
|
|
444
|
+
return undefined;
|
|
445
|
+
}
|
|
446
|
+
function showNow(s, focus) {
|
|
447
|
+
if (!SECTIONS.includes(s)) s = 'status';
|
|
448
|
+
current = s;
|
|
449
|
+
try { sessionStorage.setItem('keepfold.section', s); } catch (e) { /* storage off */ }
|
|
450
|
+
for (const x of SECTIONS) $('s-' + x).hidden = x !== s;
|
|
451
|
+
document.querySelectorAll('.side button').forEach((b) => b.setAttribute('aria-current', b.dataset.s === s ? 'page' : 'false'));
|
|
452
|
+
$('section-select').value = s;
|
|
453
|
+
if (location.hash !== '#' + s) history[focus ? 'pushState' : 'replaceState'](null, '', '#' + s); // a click is a Back step
|
|
454
|
+
load(s);
|
|
455
|
+
if (focus) { // focus on the heading (screen readers say where they are); the section lands below the sticky header (scroll-margin-top in app.css)
|
|
456
|
+
($('s-' + s).querySelector('h1') || $('s-' + s)).focus({ preventScroll: true });
|
|
457
|
+
$('s-' + s).scrollIntoView({ block: 'start' });
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
async function load(s, fresh) {
|
|
461
|
+
const box = $(s);
|
|
462
|
+
if (!box.firstChild) box.append(note('Loading…'));
|
|
463
|
+
else { // the old boards stay up, dimmed, until the new answer replaces them
|
|
464
|
+
box.classList.add('refreshing');
|
|
465
|
+
box.setAttribute('aria-busy', 'true');
|
|
466
|
+
}
|
|
467
|
+
try {
|
|
468
|
+
const d = await api('/api/' + s + (fresh ? '?fresh=1' : '')); // fresh: Status asks every probe again
|
|
469
|
+
if (current === s) RENDER[s](d);
|
|
470
|
+
} catch (e) {
|
|
471
|
+
if (!dead) fail(s, e.message);
|
|
472
|
+
} finally {
|
|
473
|
+
box.classList.remove('refreshing');
|
|
474
|
+
box.setAttribute('aria-busy', 'false');
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
// a redraw keeps keyboard focus that was inside the section: on the same control in the new
|
|
478
|
+
// boards (by id, a radio by name and value, else by tag and name), else on the section's heading
|
|
479
|
+
const focusKey = (e) => (e.id ? '#' + e.id : e.getAttribute('name') ? `${e.getAttribute('name')}=${e.value}`
|
|
480
|
+
: e.getAttribute('aria-label') || e.textContent);
|
|
481
|
+
function put(s, ...nodes) {
|
|
482
|
+
const box = $(s), a = document.activeElement;
|
|
483
|
+
const inside = !!a && a !== box && box.contains(a);
|
|
484
|
+
const like = (k) => [...box.querySelectorAll(a.tagName)].filter((e) => focusKey(e) === k);
|
|
485
|
+
const k = inside ? focusKey(a) : null, n = inside ? like(k).indexOf(a) : 0; // the nth of same-named controls
|
|
486
|
+
box.replaceChildren(...nodes.filter(Boolean), outputBoard(s) || '');
|
|
487
|
+
if (!inside) return;
|
|
488
|
+
const found = like(k);
|
|
489
|
+
(found[n] || found[0] || $('s-' + s).querySelector('h1') || $('s-' + s)).focus({ preventScroll: true });
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function renderStatus(d) {
|
|
493
|
+
if (landing) { // the first answer of a page opened with no section: the app's choice (Setup until it is done)
|
|
494
|
+
landing = false;
|
|
495
|
+
if (d.land !== 'status' && SECTIONS.includes(d.land)) { show(d.land); return; }
|
|
496
|
+
}
|
|
497
|
+
const rows = d.rows.map((r) => {
|
|
498
|
+
// at: a time the row names where "{ago}" stands, in words, the exact time in a title
|
|
499
|
+
const fill = (t) => (r.at ? String(t).replace('{ago}', daysAgo(r.at, true)) : t);
|
|
500
|
+
const title = r.at ? new Date(r.at).toLocaleString() : r.value;
|
|
501
|
+
return h('div', { class: 'brow srow' }, stateCell(r.state),
|
|
502
|
+
h('div', { class: 't' },
|
|
503
|
+
h('div', { class: 'line1' }, h('span', { class: 'ttl', text: r.label }), h('span', { class: 'val', text: fill(r.value), title })),
|
|
504
|
+
h('span', { class: 'sub', text: fill(r.detail) }),
|
|
505
|
+
r.login_hint ? h('span', { class: 'sub', text: LOGIN_HINT }) : null),
|
|
506
|
+
h('div', { class: 'acts' }, r.count != null ? noteCount(r.count) : null,
|
|
507
|
+
r.import && r.import.length ? btn('Import new history now', () => job('/api/browse/import', { sources: r.import, from: 'browse' }), 'btn lit') : null,
|
|
508
|
+
r.login_hint ? loginBtn() : null,
|
|
509
|
+
r.resume ? btn('Resume', () => post('/api/review/resume', { producer: r.resume }, () => { toast.ok('Resumed: Review offers these cards again.'); load('status'); }), 'btn lit', { 'aria-label': `Resume: ${r.value}` }) : null,
|
|
510
|
+
r.fix ? btn(r.fix.label, () => post(r.fix.post, {}, (d) => { toast.ok(d.say); load('status', true); }), 'btn lit', { 'aria-label': `${r.fix.label}: ${r.value}` }) : null,
|
|
511
|
+
r.install ? btn(r.install.label, () => job('/api/setup/git', { from: 'status' }), 'btn lit') : null,
|
|
512
|
+
r.install ? ext(r.install.license, 'License') : null,
|
|
513
|
+
r.page ? ext(r.page, 'Get Git') : null,
|
|
514
|
+
r.action ? btn(r.action.label, () => show(r.action.go, true)) : null));
|
|
515
|
+
});
|
|
516
|
+
const t = new Date(), hm = `${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}`;
|
|
517
|
+
const wn = d.whats_new || {};
|
|
518
|
+
put('status', wn.show && wn.show.length ? newsBoard(wn.show, true) : null,
|
|
519
|
+
board('This computer', { note: ['checked ', dm(hm, 2, hm)], btn: ['Check again', () => load('status', true)] },
|
|
520
|
+
...(rows.length ? rows : [note('Nothing to check yet. Check again in a moment.')])),
|
|
521
|
+
d.first_run ? null : chatImportBoard(d.chat_import !== false),
|
|
522
|
+
d.first_run ? null : quickCaptureBoard(),
|
|
523
|
+
d.update ? updatesBoard(d.update, wn.current) : null,
|
|
524
|
+
d.connects && d.connects.length ? h('details', { class: 'review-more' }, // collapsed, like Review's "More"
|
|
525
|
+
h('summary', { text: 'Where Keepfold connects' }),
|
|
526
|
+
h('ul', { class: 'pad' }, d.connects.map((t) => h('li', { text: t })))) : null,
|
|
527
|
+
d.issue_url ? reportBoard(d.issue_url) : null);
|
|
528
|
+
}
|
|
529
|
+
/* Something not working?: the details come from the server (no paths or notes); nothing is sent from here */
|
|
530
|
+
// the text is fetched with the board, so the click only writes the clipboard (a fetch first
|
|
531
|
+
// can lose the click's focus); a blocked copy shows the text selected for Ctrl+C
|
|
532
|
+
function reportBoard(url) {
|
|
533
|
+
let text = null;
|
|
534
|
+
const got = () => api('/api/status/report').then((r) => (text = r.text));
|
|
535
|
+
got().catch(() => {}); // the click asks again
|
|
536
|
+
const shown = h('div', { class: 'pad report-text' });
|
|
537
|
+
const fail = () => {
|
|
538
|
+
if (text == null) { toast.error('Copy failed: the details did not load. Try again.'); return; }
|
|
539
|
+
const area = h('textarea', { class: 'mono', readonly: true, rows: 8, 'aria-label': 'Problem report details' });
|
|
540
|
+
area.value = text;
|
|
541
|
+
shown.replaceChildren(h('p', { class: 'help', text: 'Select the text and press Ctrl+C.' }), area);
|
|
542
|
+
area.focus();
|
|
543
|
+
area.select();
|
|
544
|
+
};
|
|
545
|
+
return board('Something not working?', {},
|
|
546
|
+
row('Report a problem', null, 'Copy details, then paste them into the form. Nothing is sent until you submit it on GitHub.',
|
|
547
|
+
[copyBtn(() => text ?? got(), '', 'btn lit', false, fail, null, 'Copy details'),
|
|
548
|
+
ext(url, 'Report on GitHub')]), shown);
|
|
549
|
+
}
|
|
550
|
+
/* app.chat_import: past AI chats saved as chat pages every 5 minutes, no model (on by default) */
|
|
551
|
+
function chatImportBoard(on) {
|
|
552
|
+
const cb = h('input', { type: 'checkbox', id: 'chat-import', checked: on });
|
|
553
|
+
cb.addEventListener('change', () => post('/api/app/chat-import', { enabled: cb.checked }, () => savedMark(cb)));
|
|
554
|
+
return board('Past AI chats', {},
|
|
555
|
+
h('div', { class: 'field' }, h('label', { class: 'check', for: 'chat-import' }, cb, h('span', { text: 'Save new AI chats to your notes automatically' })),
|
|
556
|
+
h('p', { class: 'help', text: 'Every 5 minutes, your Claude Code, Codex, Gemini CLI and Copilot CLI sessions and the chats you imported become chat pages: your own messages only (a coding session as a short summary of files and commits, never code), with keys and passwords removed. No AI model is used. Chats in a category you set to skip are never saved.' })));
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/* app.hotkey: quick capture's key, desktop app only; `taken`: another app holds it */
|
|
560
|
+
function quickCaptureBoard() {
|
|
561
|
+
const field = h('div', { class: 'field', id: 'hotkey-field' }, h('span', { class: 'lbl', text: 'Quick capture key' }));
|
|
562
|
+
api('/api/app/hotkey').then((d) => {
|
|
563
|
+
if (!d.desktop) { field.append(h('p', { class: 'help', text: 'Only in the desktop app.' })); return; }
|
|
564
|
+
const sel = h('select', { id: 'hotkey' }, d.choices.map((c) => h('option', { value: c.key, text: c.label })));
|
|
565
|
+
sel.value = d.key;
|
|
566
|
+
const taken = h('p', { class: 'help taken', id: 'hotkey-taken', role: 'status' });
|
|
567
|
+
const say = (s) => {
|
|
568
|
+
const c = s.choices.find((x) => x.key === s.key);
|
|
569
|
+
taken.textContent = s.taken && c ? `${c.label} is taken by another app. Pick another.` : '';
|
|
570
|
+
};
|
|
571
|
+
sel.addEventListener('change', () => post('/api/app/hotkey', { hotkey: sel.value }, (s) => { say(s); savedMark(sel); }));
|
|
572
|
+
field.replaceChildren(h('label', { for: 'hotkey', text: 'Quick capture key' }), sel, taken);
|
|
573
|
+
say(d);
|
|
574
|
+
}).catch(() => { /* api() said why */ });
|
|
575
|
+
return board('Quick capture', {}, field);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/* What's new: shown once after an update (Got it records it), and any time from Updates */
|
|
579
|
+
function newsBoard(entries, pending) {
|
|
580
|
+
const hide = () => { b.remove(); ($('s-status').querySelector('h1') || $('s-status')).focus(); }; // focus stays on the page
|
|
581
|
+
const b = board(`What’s new in Keepfold ${entries[0].version}`, {
|
|
582
|
+
id: 'whats-new',
|
|
583
|
+
btn: pending ? ['Got it', () => post('/api/whats_new/seen', {}, () => { hide(); toast.ok('Read it again any time: Updates, What’s new.'); })]
|
|
584
|
+
: ['Close', hide],
|
|
585
|
+
}, ...entries.map((e) => h('div', { class: 'pad md' },
|
|
586
|
+
entries.length > 1 ? h('h3', { text: `Keepfold ${e.version}` }) : null,
|
|
587
|
+
h('ul', {}, e.items.map((t) => h('li', { text: t }))),
|
|
588
|
+
e.do && e.do.length ? [h('p', {}, h('b', { text: 'What to do' })), h('ol', { class: 'how' }, e.do.map((t) => h('li', { text: t })))] : null)));
|
|
589
|
+
b.querySelector('h2').setAttribute('tabindex', '-1');
|
|
590
|
+
return b;
|
|
591
|
+
}
|
|
592
|
+
function openNews(cur) {
|
|
593
|
+
let b = $('whats-new');
|
|
594
|
+
if (!b) {
|
|
595
|
+
b = newsBoard([cur], false);
|
|
596
|
+
$('status').replaceChildren(b, ...$('status').childNodes);
|
|
597
|
+
}
|
|
598
|
+
b.querySelector('h2').focus();
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/* Updates: the app checks GitHub every 6 hours and prepares a newer release (u.ready); it is
|
|
602
|
+
installed only on a click */
|
|
603
|
+
let upd = null; // the last check or update job
|
|
604
|
+
function updatesBoard(u, cur) {
|
|
605
|
+
const r = upd && upd.result;
|
|
606
|
+
const cmd = (c) => h('div', { class: 'pad' }, h('div', { class: 'token' }, h('code', { text: c }),
|
|
607
|
+
copyBtn(() => c, 'Copy failed; select the command and copy it.')));
|
|
608
|
+
const out = [row(`Keepfold ${u.current}`, null, null, [cur ? btn('What’s new', () => openNews(cur)) : null,
|
|
609
|
+
btn('Check for updates', () => { upd = null; return job('/api/update/check', {}); })])];
|
|
610
|
+
if (upd && upd.error) out.push(row('That did not work', null, upd.error, null));
|
|
611
|
+
else if (r && r.cancelled) out.push(row('Cancelled', null, 'Nothing was installed; update again any time.', null));
|
|
612
|
+
else if (r && !r.newer) out.push(row('You have the latest version', r.latest, null, null));
|
|
613
|
+
else if (r) {
|
|
614
|
+
const mb = r.size ? ` (about ${Math.max(1, Math.round(r.size / 2 ** 20))} MB)` : ''; // unknown when the API was busy
|
|
615
|
+
const now = () => confirmDialog('Update Keepfold?', 'Update now',
|
|
616
|
+
[h('p', { class: 'ink-2', text: `Keepfold will download the update${mb}, close, and reopen when it's done. AI apps connected to Keepfold may need a restart.` })],
|
|
617
|
+
() => job('/api/update/apply', {}));
|
|
618
|
+
out.push(row(`Keepfold ${r.latest} is available`, null, r.command ? 'Run this in a terminal to update:' : null,
|
|
619
|
+
[ext(r.notes_url, 'Release notes'), r.mode === 'installer' ? btn('Update now', now, 'btn lit') : null]));
|
|
620
|
+
if (r.command) out.push(cmd(r.command));
|
|
621
|
+
} else if (u.ready) { // found and prepared by the app's own check
|
|
622
|
+
out.push(row(`Keepfold ${u.ready.version} is ready`, null, u.ready.command ? 'Run this in a terminal to update:'
|
|
623
|
+
: 'Downloaded and checked. Keepfold closes, installs it and reopens.',
|
|
624
|
+
[ext(u.ready.notes_url, 'Release notes'), u.ready.command ? null : btn('Restart to update', () => job('/api/update/apply', {}), 'btn lit')]));
|
|
625
|
+
if (u.ready.command) out.push(cmd(u.ready.command));
|
|
626
|
+
}
|
|
627
|
+
// app.update_check: the quiet check (on by default); the buttons above work either way
|
|
628
|
+
const say = (on) => (on ? 'checked every 6 hours, installed only when you click' : 'checked only when you click');
|
|
629
|
+
const cb = h('input', { type: 'checkbox', id: 'update-check', checked: u.auto !== false });
|
|
630
|
+
out.push(h('div', { class: 'field' }, h('label', { class: 'check', for: 'update-check' }, cb, h('span', { text: 'Check for updates automatically' })),
|
|
631
|
+
h('p', { class: 'help', text: 'Asks GitHub for a new version a minute after the app starts and every 6 hours, and downloads it in the background. Nothing is installed until you click.' })));
|
|
632
|
+
const b = board('Updates', { note: say(u.auto !== false) }, ...out);
|
|
633
|
+
cb.addEventListener('change', () => post('/api/app/update-check', { enabled: cb.checked }, (s) => {
|
|
634
|
+
b.querySelector('.band-note').textContent = say(s && typeof s.enabled === 'boolean' ? s.enabled : cb.checked);
|
|
635
|
+
savedMark(cb);
|
|
636
|
+
}));
|
|
637
|
+
return b;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/* Chat: a model on this computer answers from your notes, saved chats and browsing; never a
|
|
641
|
+
cloud model. The answer streams as NDJSON from POST /api/chat and is rendered by a tiny
|
|
642
|
+
safe renderer (textContent only: paragraphs, lists, bold, code, [n] citations). */
|
|
643
|
+
const MISSING = { // [title, value, why, button]
|
|
644
|
+
embed: ['Search model', 'not downloaded', 'Finds the notes and pages that answer your question. A one-time download.', 'Set up the search model'],
|
|
645
|
+
llm: ['Local model', 'not running', 'Writes the answer on this computer, never in the cloud. Start Ollama or LM Studio, or set one up (a download of a few GB).', 'Set up a local model'],
|
|
646
|
+
};
|
|
647
|
+
const EXAMPLES = ['What did I decide about the payments retry?', 'Which papers did I read on contrastive learning?', 'What did I read about binary search?', 'Which sites did I visit yesterday?'];
|
|
648
|
+
// answered from Keepfold's own data, with no search model and no local model (chat.site_list, chat_study)
|
|
649
|
+
const DATA_EXAMPLES = ['Which sites did I visit yesterday?', 'What should I study today?', 'What is due for review?', 'Where am I weak?'];
|
|
650
|
+
const KIND = { note: 'note', chat: 'chat', browse: 'browsing', file: 'file' };
|
|
651
|
+
const chatS = { d: null, id: null, msgs: [], els: [], remembers: 0, draft: '', busy: null, setOpen: false, focus: false, follow: true, pill: null,
|
|
652
|
+
files: [], reading: null, fileErr: null, pages: [] };
|
|
653
|
+
const last = (e) => e.childNodes[e.childNodes.length - 1];
|
|
654
|
+
|
|
655
|
+
function inline(text, cite) { // **bold**, `code` and [n] citations; everything else is text
|
|
656
|
+
const out = [];
|
|
657
|
+
for (const part of String(text).split(/(\*\*[^*\n]+\*\*|`[^`\n]+`|\[\d+(?:\s*,\s*\d+)*\])/)) {
|
|
658
|
+
if (!part) continue;
|
|
659
|
+
if (part.startsWith('**') && part.length > 4) out.push(h('strong', { text: part.slice(2, -2) }));
|
|
660
|
+
else if (part.startsWith('`') && part.length > 2) out.push(h('code', { text: part.slice(1, -1) }));
|
|
661
|
+
else if (/^\[\d/.test(part)) {
|
|
662
|
+
for (const n of part.slice(1, -1).split(',').map((x) => x.trim())) {
|
|
663
|
+
out.push(h('button', { class: 'cite', type: 'button', text: n, 'aria-label': `Source ${n}`, onclick: () => cite(n) }));
|
|
664
|
+
}
|
|
665
|
+
} else out.push(part);
|
|
666
|
+
}
|
|
667
|
+
return out;
|
|
668
|
+
}
|
|
669
|
+
function md(text, cite) { // paragraphs, "- " and "1." lists; never HTML, links or images
|
|
670
|
+
const nodes = [];
|
|
671
|
+
let cur = null, kind = ''; // the open paragraph or list and its kind: p, ul or ol
|
|
672
|
+
for (const l of String(text).split('\n')) {
|
|
673
|
+
const k = !l.trim() ? '' : /^\s*[-*•]\s+/.test(l) ? 'ul' : /^\s*\d+[.)]\s+/.test(l) ? 'ol' : 'p';
|
|
674
|
+
if (k !== kind || !k) { cur = k ? h(k) : null; kind = k; if (cur) nodes.push(cur); }
|
|
675
|
+
if (k === 'p') { if (cur.childNodes.length) cur.append(h('br')); cur.append(...inline(l, cite)); }
|
|
676
|
+
else if (k) cur.append(h('li', {}, inline(l.replace(/^\s*(?:[-*•]|\d+[.)])\s+/, ''), cite)));
|
|
677
|
+
}
|
|
678
|
+
return nodes;
|
|
679
|
+
}
|
|
680
|
+
// hours: under a day in hours, then "n days ago" at any age (the caller titles the exact time)
|
|
681
|
+
function daysAgo(ts, hours) {
|
|
682
|
+
const d = new Date(ts);
|
|
683
|
+
if (isNaN(d)) return '';
|
|
684
|
+
const hr = Math.floor((Date.now() - d) / 36e5);
|
|
685
|
+
if (hours && hr < 24) return hr < 1 ? 'less than an hour ago' : `${hr} hour${hr === 1 ? '' : 's'} ago`;
|
|
686
|
+
const n = Math.round((new Date().setHours(0, 0, 0, 0) - new Date(d).setHours(0, 0, 0, 0)) / 864e5);
|
|
687
|
+
// the local date, as brain3d.js's isoDay: toISOString() alone gives the UTC one
|
|
688
|
+
const day = new Date(d.getTime() - d.getTimezoneOffset() * 6e4).toISOString().slice(0, 10);
|
|
689
|
+
return n <= 0 ? 'today' : n === 1 ? 'yesterday' : n < 7 || hours ? `${n} days ago` : day;
|
|
690
|
+
}
|
|
691
|
+
// each pill opens its passage (`open`); the pill of the open one is pressed
|
|
692
|
+
function sourceRow(sources, searched, open, shown) {
|
|
693
|
+
// an attached file's passage lives only in the app's memory: its pill names it, opens nothing
|
|
694
|
+
const pill = (s, label) => (s.kind === 'file' ? h('span', { class: 'chip', 'data-n': s.n },
|
|
695
|
+
h('span', { class: 'ct', text: label }), h('span', { class: 'tag', text: KIND.file }))
|
|
696
|
+
: h('button', { class: 'chip', type: 'button', 'data-n': s.n, 'aria-pressed': String(shown === s),
|
|
697
|
+
title: 'Show the passage', onclick: () => open(s) },
|
|
698
|
+
h('span', { class: 'ct', text: label }), h('span', { class: 'tag', text: KIND[s.kind] || s.kind })));
|
|
699
|
+
if ((!sources || !sources.length) && searched && searched.length) // the model cited nothing
|
|
700
|
+
return h('div', { class: 'chat-src' }, h('span', { class: 'ink-3 small', text: 'Searched, not cited' }),
|
|
701
|
+
searched.map((s) => pill(s, s.title || s.path)));
|
|
702
|
+
if (!sources || !sources.length) return null;
|
|
703
|
+
return h('div', { class: 'chat-src' }, h('span', { class: 'ink-3 small', text: 'Sources' }),
|
|
704
|
+
sources.map((s) => pill(s, `${s.n} · ${s.title || s.path}`)));
|
|
705
|
+
}
|
|
706
|
+
// the evidence line under the sources of a finished answer (certainty, the span of the data when
|
|
707
|
+
// thin or none) and a line for each page that replaced another; plain words, never colour alone
|
|
708
|
+
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
709
|
+
const monthYear = (ym) => { const [y, mo] = String(ym).split('-'); return MON[mo - 1] ? `${MON[mo - 1]} ${y}` : String(ym); };
|
|
710
|
+
const dayText = (d) => { const [y, mo, da] = String(d || '').split('-'); return MON[mo - 1] && da ? `${Number(da)} ${MON[mo - 1]} ${y}` : ''; };
|
|
711
|
+
function evidenceRows(m, live, pageLink) {
|
|
712
|
+
if (live || m.stopped || !m.certainty) return [];
|
|
713
|
+
const c = m.certainty, hz = m.horizon;
|
|
714
|
+
const head = c === 'exact' ? ['Exact: counted or quoted from your pages']
|
|
715
|
+
: c === 'grounded' ? [`From ${(m.sources || []).length} of your pages`]
|
|
716
|
+
: c === 'thin' ? [h('strong', { text: 'Thin' }), ': check the sources'] : ['Nothing on record'];
|
|
717
|
+
if ((c === 'thin' || c === 'none') && hz && hz.first && hz.last) head.push(` · Your data covers ${monthYear(hz.first)} to ${monthYear(hz.last)}`);
|
|
718
|
+
const day = (s) => (dayText(s.day) ? ` (${dayText(s.day)})` : '');
|
|
719
|
+
return [h('p', { class: 'chat-evidence' }, ...head),
|
|
720
|
+
...(m.conflicts || []).map((x) => h('p', { class: 'chat-evidence chat-conflict' }, 'Changed: ', pageLink(x.new),
|
|
721
|
+
`${day(x.new)} replaces `, pageLink(x.old), day(x.old)))];
|
|
722
|
+
}
|
|
723
|
+
// the facts Keepfold computed (chat_facts), above the model's words: exactly as counted
|
|
724
|
+
const FACT_NOUN = { notes: 'notes', chats: 'saved AI chats', journal: 'journal lines', browsing: 'visits', study: 'study events' };
|
|
725
|
+
const FACT_SRC = { notes: 'notes', chats: 'chats', journal: 'journal', browsing: 'browsing', study: 'study' };
|
|
726
|
+
const PAGE_KIND = { inventory: 'pages', schedule: 'coming up', decisions: 'decisions' };
|
|
727
|
+
function factsBox(f) {
|
|
728
|
+
const n = (x) => Number(x).toLocaleString();
|
|
729
|
+
const period = f.period ? (f.period[0] === f.period[1] ? f.period[0] : `${f.period[0]} to ${f.period[1]}`) : 'all time';
|
|
730
|
+
const big = (num, label) => [h('span', { class: 'fx-n', text: n(num) }), h('span', { text: label })];
|
|
731
|
+
let head;
|
|
732
|
+
if (f.kind === 'count') head = big(f.total, f.unit === 'days' ? 'days' : f.focus ? FACT_NOUN[f.focus] : 'mentions');
|
|
733
|
+
else if (f.kind === 'timeline') head = big(f.total, `items across ${n(f.rows.length + (f.more || 0))} ${f.unit}s`);
|
|
734
|
+
else if (f.kind === 'about' || f.kind === 'compare') head = big(f.total, 'mentions');
|
|
735
|
+
else if (f.kind === 'gaps') head = big(f.total, f.page ? `pages under ${f.page.title}` : 'topic pages found');
|
|
736
|
+
else if (PAGE_KIND[f.kind]) head = big(f.total, f.kind === 'inventory' ? f.query : PAGE_KIND[f.kind]);
|
|
737
|
+
else head = f.item ? [h('span', { class: 'fx-n', text: f.item.day }), h('span', { text: `${f.kind} time: ${f.item.title} (${FACT_SRC[f.item.source] || f.item.source})` })]
|
|
738
|
+
: big(0, 'matches');
|
|
739
|
+
const line = (text) => h('div', { class: 'fx-line', text });
|
|
740
|
+
let extra = f.kind === 'about' && f.first ? line(`First ${f.first.day}, last ${f.last.day}` + (f.page ? ` · page: ${f.page.title}` : '')) : '';
|
|
741
|
+
if (f.kind === 'compare') extra = (f.rows || []).map((r) => line(`${r.term}: ${n(r.total)}` + (r.page ? ` · most in ${r.page.title} (written ${r.page.day})` : '')));
|
|
742
|
+
if (f.kind === 'gaps') {
|
|
743
|
+
extra = (f.rows || []).slice(0, 10).map((r) => line(`${r.title} · last changed ${r.day}`));
|
|
744
|
+
if (f.unopened && f.unopened.length) extra.push(line(`Searched, opened nothing: ${f.unopened.join('; ')}`));
|
|
745
|
+
}
|
|
746
|
+
if (PAGE_KIND[f.kind]) { // chat_pages: rows {title, day} and, for a decision, what replaced it
|
|
747
|
+
extra = (f.rows || []).slice(0, 10).map((r) => line(`${r.day || 'undated'} · ${r.title}`
|
|
748
|
+
+ (r.replaced_by ? ` · replaced by ${r.replaced_by}` : r.replaced ? ` · ${r.status}` : '')));
|
|
749
|
+
if (f.total > extra.length) extra.push(line(`and ${n(f.total - extra.length)} more`));
|
|
750
|
+
}
|
|
751
|
+
const cov = f.coverage || {};
|
|
752
|
+
return h('div', { class: 'facts', role: 'group', 'aria-label': 'Facts computed by Keepfold' },
|
|
753
|
+
h('div', { class: 'fx-top' }, h('span', { class: 'fx-ttl', text: 'Computed from your data' }), h('span', { class: 'ink-3', text: period + (f.query ? ` · “${f.query}”` : '') })),
|
|
754
|
+
h('div', { class: 'fx-head' }, ...head), extra,
|
|
755
|
+
Object.keys(f.sources || {}).length ? h('div', { class: 'fx-src' }, Object.entries(f.sources).map(([s, c]) =>
|
|
756
|
+
h('span', { class: 'fx-chip' }, h('span', { class: 'tag', text: FACT_SRC[s] || s }), h('span', { text: n(c) })))) : '',
|
|
757
|
+
cov.read != null ? h('div', { class: 'fx-cov', text: `Counted all ${n(cov.matched)} matches in ${n(cov.read)} items read`
|
|
758
|
+
+ (cov.off && cov.off.length ? ` · switched off: ${cov.off.join(', ')}` : '') }) : '');
|
|
759
|
+
}
|
|
760
|
+
// the exact passage a source stands for (GET /api/chat/passage, under the switches of now)
|
|
761
|
+
function passageView(s, p, close) {
|
|
762
|
+
const kids = p.error ? [h('p', { class: 'ink-3 small', text: p.error })]
|
|
763
|
+
: !p.data ? [h('p', { class: 'thinking', text: 'Opening the passage…' })]
|
|
764
|
+
: [h('div', { class: 'pv-where' }, h('span', { class: 'tag', text: KIND[p.data.kind] || p.data.kind }),
|
|
765
|
+
h('strong', { text: p.data.title || s.path }), p.data.heading ? h('span', { class: 'ink-3', text: `› ${p.data.heading}` }) : ''),
|
|
766
|
+
h('div', { class: 'pv-text', text: p.data.text || '(this part of the page is empty now)' })];
|
|
767
|
+
return h('div', { class: 'passage', role: 'region', 'aria-label': `Passage ${s.n || ''}`.trim() }, ...kids,
|
|
768
|
+
h('div', { class: 'msg-acts' }, btn('Open the page in Obsidian', () => post('/api/open', { what: 'page', path: s.path }), 'btn quiet'),
|
|
769
|
+
btn('Close', close, 'btn quiet')));
|
|
770
|
+
}
|
|
771
|
+
function botMsg(m) { // {text, sources, searched, model, stopped, facts, coverage, unquoted}; returns the element and its updater
|
|
772
|
+
const body = h('div', { class: 'md' }), el = h('div', { class: 'msg bot' }), who = h('div', { class: 'who' });
|
|
773
|
+
let live = false, shown = null, p = null; // the source whose passage is open, and its fetch
|
|
774
|
+
const extra = {}; // a conflict's page that is not one of the sources, by path
|
|
775
|
+
const open = async (s) => {
|
|
776
|
+
if (s.kind === 'file') return; // its text is not kept: the pill names the page
|
|
777
|
+
if (shown === s) { shown = p = null; draw(live); return; }
|
|
778
|
+
shown = s; p = {};
|
|
779
|
+
draw(live);
|
|
780
|
+
const mine = p;
|
|
781
|
+
try {
|
|
782
|
+
mine.data = await api(`/api/chat/passage?path=${encodeURIComponent(s.path)}&at=${s.at || 0}&len=${s.len || 0}`);
|
|
783
|
+
} catch (e) { mine.error = e.message; }
|
|
784
|
+
if (p === mine) draw(live);
|
|
785
|
+
};
|
|
786
|
+
const cite = (n) => {
|
|
787
|
+
const s = (m.sources || []).find((x) => String(x.n) === String(n));
|
|
788
|
+
if (s) open(s);
|
|
789
|
+
};
|
|
790
|
+
const draw = (streaming) => {
|
|
791
|
+
live = streaming;
|
|
792
|
+
who.textContent = 'Keepfold' + (m.model === 'Keepfold' ? ' · from your data' : m.model ? ` · ${m.model}` : '') + (!streaming && m.seconds ? ` · ${Math.round(m.seconds)} s` : '');
|
|
793
|
+
if (streaming && !m.text) { // each stage with a live count, so a slow one never looks frozen
|
|
794
|
+
const secs = Math.floor((Date.now() - m.t0) / 1000);
|
|
795
|
+
body.replaceChildren(h('span', { class: 'thinking', text: `${m.thinking ? 'Thinking' : m.step || 'Sending your question'}… ${secs} s` }));
|
|
796
|
+
} else if (m.thinking && !m.text) body.replaceChildren(h('span', { class: 'thinking', text: 'thinking…' }));
|
|
797
|
+
else body.replaceChildren(...md(m.text, cite));
|
|
798
|
+
if (streaming) {
|
|
799
|
+
let at = last(body) || body;
|
|
800
|
+
if (at.tagName === 'UL' || at.tagName === 'OL') at = last(at);
|
|
801
|
+
if (!at || at.tagName === 'SPAN') at = body;
|
|
802
|
+
at.append(h('span', { class: 'caret', 'aria-hidden': 'true' }));
|
|
803
|
+
}
|
|
804
|
+
// a finished answer gets Copy: its text without the [n] markers; the sources stay out
|
|
805
|
+
const copy = !streaming && m.text ? h('div', { class: 'msg-acts' }, copyBtn(() => m.text.replace(/\s*\[\d+(?:\s*,\s*\d+)*\]/g, ''),
|
|
806
|
+
'Copy failed; select the answer and copy it.', 'btn quiet', true)) : '';
|
|
807
|
+
const cov = m.coverage; // what the model read of what the search found
|
|
808
|
+
// a conflict's page opens as a source pill does (the same object when it is one)
|
|
809
|
+
const pageLink = (x) => {
|
|
810
|
+
const s = [...(m.sources || []), ...(m.searched || [])].find((y) => y.path === x.path)
|
|
811
|
+
|| (extra[x.path] = extra[x.path] || { path: x.path, kind: 'note', at: 0, len: 0 });
|
|
812
|
+
return h('button', { class: 'linkbtn', type: 'button', 'aria-pressed': String(shown === s), text: x.title || x.path, onclick: () => open(s) });
|
|
813
|
+
};
|
|
814
|
+
el.replaceChildren(who, m.facts ? factsBox(m.facts) : '', body, copy, sourceRow(m.sources, m.searched, open, shown) || '',
|
|
815
|
+
...evidenceRows(m, streaming, pageLink),
|
|
816
|
+
shown ? passageView(shown, p, () => open(shown)) : '',
|
|
817
|
+
cov && !streaming ? h('p', { class: 'ink-3 small cov', text: `Read ${cov.read} of ${cov.matched}${cov.more ? '+' : ''} match${cov.matched === 1 && !cov.more ? '' : 'es'}`
|
|
818
|
+
+ (cov.also && cov.also.length ? ` · also searched: ${cov.also.join(', ')}` : '') }) : '',
|
|
819
|
+
// quotes no cited passage holds: the model may have made them up
|
|
820
|
+
m.unquoted && m.unquoted.length && !streaming ? h('p', { class: 'ink-3 small cov qflag',
|
|
821
|
+
text: `Quote not found in a cited passage: ${m.unquoted.map((q) => `“${q}”`).join(', ')}` }) : '',
|
|
822
|
+
m.stopped ? h('p', { class: 'ink-3 small', text: 'Stopped before the end.' }) : '');
|
|
823
|
+
};
|
|
824
|
+
draw(false);
|
|
825
|
+
return { el, draw };
|
|
826
|
+
}
|
|
827
|
+
function userMsg(m) {
|
|
828
|
+
return h('div', { class: 'msg you' }, h('div', { class: 'who', text: 'You' }), h('div', { class: 'md' }, ...md(m.text, () => {})));
|
|
829
|
+
}
|
|
830
|
+
// a thin line above the oldest message the local model still gets (the server's chat.remembers);
|
|
831
|
+
// none while it gets them all. chatS.els holds each message's element, as chatS.msgs
|
|
832
|
+
function memLine(log) {
|
|
833
|
+
const old = log.querySelector('.chat-mem');
|
|
834
|
+
if (old) old.remove();
|
|
835
|
+
const i = chatS.remembers || 0, at = chatS.els[Math.min(i, chatS.els.length) - 1];
|
|
836
|
+
if (i > 0 && at && log.contains(at)) at.after(h('div', { class: 'chat-mem', text: 'The model remembers from here' }));
|
|
837
|
+
}
|
|
838
|
+
function missingRows(keys, why) {
|
|
839
|
+
return h('div', { class: 'board' }, note(why || 'Chat needs two things on this computer. Still missing:'),
|
|
840
|
+
keys.map((k) => {
|
|
841
|
+
const [title, value, help, label] = MISSING[k];
|
|
842
|
+
return row(title, value, help, [btn(label, () => { opened.add(k); show('setup', true); }, 'btn lit')]);
|
|
843
|
+
}));
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// C1: files attached to the chat (the server's askfile): sent through Setup's upload route,
|
|
847
|
+
// read into the app's memory only, saved to the vault only on Save to your brain
|
|
848
|
+
const FILE_MAX = { '.pdf': 200, '.docx': 200, '.txt': 5, '.md': 5 }; // MB, as askfile.LIMIT
|
|
849
|
+
function fileLine(f) {
|
|
850
|
+
const n = f.count.toLocaleString();
|
|
851
|
+
const what = `${f.name}, ${n} ${f.unit}${f.count === 1 ? '' : 's'}` + (!f.cut ? ''
|
|
852
|
+
: f.unit === 'page' ? ` (searched up to page ${f.cut})` : ` (the first ${f.cut.toLocaleString()} are searched)`)
|
|
853
|
+
+ (f.scan ? ' (read from a scan)' : '');
|
|
854
|
+
const done = (r) => { chatS.files = r.files; drawFiles(); };
|
|
855
|
+
return h('p', { class: 'help chat-file' }, h('span', { text: what }), ' ',
|
|
856
|
+
...(f.saved ? [h('span', { text: `Saved as ${f.saved.title} ` }),
|
|
857
|
+
btn('Open the page in Obsidian', () => post('/api/open', { what: 'page', path: f.saved.path }), 'btn quiet')]
|
|
858
|
+
: [btn('Save to your brain', () => post('/api/chat/file/save', { id: f.id }, done), 'btn quiet')]),
|
|
859
|
+
btn('Remove', () => post('/api/chat/file/remove', { id: f.id }, done), 'btn quiet', { 'aria-label': `Remove ${f.name}` }));
|
|
860
|
+
}
|
|
861
|
+
function drawFiles() { // the attached files' lines above the message box, redrawn in place
|
|
862
|
+
const box = $('chat-files');
|
|
863
|
+
if (chatS.d) chatS.d.files = chatS.files;
|
|
864
|
+
if (!box) return;
|
|
865
|
+
box.replaceChildren(...chatS.files.map(fileLine), ...chatS.pages.map(pageLine),
|
|
866
|
+
chatS.reading ? h('p', { class: 'help', text: `Reading ${chatS.reading}…` }) : '',
|
|
867
|
+
chatS.fileErr ? h('p', { class: 'help', role: 'alert', text: chatS.fileErr }) : '');
|
|
868
|
+
}
|
|
869
|
+
// UX-B: "#" in the message box lists pages to hand Chat (the server's chat.pick_list); a
|
|
870
|
+
// picked page is a line beside the files' and goes with the next message as `pages`
|
|
871
|
+
const PAGES_MAX = 3;
|
|
872
|
+
const pk = { open: false, rows: [], at: 0, start: -1, shut: -1, timer: null, seq: 0 };
|
|
873
|
+
function pageLine(p) {
|
|
874
|
+
return h('p', { class: 'help chat-file' }, h('span', { text: p.title }), ' ',
|
|
875
|
+
btn('Remove', () => { chatS.pages = chatS.pages.filter((x) => x !== p); drawFiles(); }, 'btn quiet', { 'aria-label': `Remove ${p.title}` }));
|
|
876
|
+
}
|
|
877
|
+
function hashAt(ta) { // the "#words" just before the caret: at the start or after a space
|
|
878
|
+
const end = ta.selectionStart == null ? ta.value.length : ta.selectionStart;
|
|
879
|
+
const m = /(^|\s)#([^#\n]{0,60})$/.exec(ta.value.slice(0, end));
|
|
880
|
+
return m ? { start: m.index + m[1].length, end, q: m[2] } : null;
|
|
881
|
+
}
|
|
882
|
+
function pkDraw(ta) {
|
|
883
|
+
const list = $('chat-pk');
|
|
884
|
+
if (!list) return;
|
|
885
|
+
pk.open = pk.rows.length > 0;
|
|
886
|
+
list.hidden = !pk.open;
|
|
887
|
+
ta.setAttribute('aria-expanded', String(pk.open));
|
|
888
|
+
list.replaceChildren(...pk.rows.map((r, i) => h('li', { id: 'chat-pk-' + i, role: 'option', class: 'pk-row', 'aria-selected': String(i === pk.at),
|
|
889
|
+
onmousedown: (e) => e.preventDefault(), onclick: () => pkPick(ta, i) }, // the box keeps focus
|
|
890
|
+
h('span', { class: 'pk-t', text: r.title }), h('span', { class: 'pk-k', text: r.kind }))));
|
|
891
|
+
if (pk.open) ta.setAttribute('aria-activedescendant', 'chat-pk-' + pk.at);
|
|
892
|
+
else ta.removeAttribute('aria-activedescendant');
|
|
893
|
+
if (pk.open && ta.getBoundingClientRect) { // under the box; above it when the window has no room below
|
|
894
|
+
const room = window.innerHeight - ta.getBoundingClientRect().bottom;
|
|
895
|
+
list.classList[room < pk.rows.length * 34 + 12 ? 'add' : 'remove']('up');
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
function pkClose(ta) {
|
|
899
|
+
pk.seq += 1; // a search still on its way is dropped
|
|
900
|
+
clearTimeout(pk.timer);
|
|
901
|
+
pk.rows = [];
|
|
902
|
+
pkDraw(ta);
|
|
903
|
+
}
|
|
904
|
+
function pkInput(ta) {
|
|
905
|
+
const at = hashAt(ta);
|
|
906
|
+
if (!at) pk.shut = -1;
|
|
907
|
+
if (!at || at.start === pk.shut) { pkClose(ta); return; } // Esc closed this "#" for good
|
|
908
|
+
clearTimeout(pk.timer);
|
|
909
|
+
const seq = ++pk.seq;
|
|
910
|
+
pk.timer = setTimeout(async () => {
|
|
911
|
+
let rows = [];
|
|
912
|
+
try { rows = (await api('/api/chat/pages?q=' + encodeURIComponent(at.q))).pages || []; } catch (e) { /* no list */ }
|
|
913
|
+
if (seq !== pk.seq) return; // typed on, or closed, meanwhile
|
|
914
|
+
Object.assign(pk, { rows: rows.slice(0, 8), at: 0, start: at.start });
|
|
915
|
+
pkDraw(ta);
|
|
916
|
+
}, 120);
|
|
917
|
+
}
|
|
918
|
+
function pkPick(ta, i) {
|
|
919
|
+
const r = pk.rows[i], at = hashAt(ta);
|
|
920
|
+
pkClose(ta);
|
|
921
|
+
pk.shut = -1;
|
|
922
|
+
if (!r) return;
|
|
923
|
+
if (!chatS.pages.some((p) => p.id === r.id)) {
|
|
924
|
+
if (chatS.pages.length >= PAGES_MAX) { toast('Up to 3 pages'); return; }
|
|
925
|
+
chatS.pages = [...chatS.pages, { id: r.id, title: r.title }];
|
|
926
|
+
}
|
|
927
|
+
if (at) { // the "#words" go; the page is a line above the box instead
|
|
928
|
+
ta.value = chatS.draft = ta.value.slice(0, at.start) + ta.value.slice(at.end);
|
|
929
|
+
if (ta.setSelectionRange) ta.setSelectionRange(at.start, at.start);
|
|
930
|
+
}
|
|
931
|
+
drawFiles();
|
|
932
|
+
ta.focus();
|
|
933
|
+
}
|
|
934
|
+
function pkKey(e, ta) { // true: the open list took the key (Enter never sends then)
|
|
935
|
+
if (!pk.open || e.isComposing) return false;
|
|
936
|
+
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
|
937
|
+
pk.at = (pk.at + (e.key === 'ArrowDown' ? 1 : -1) + pk.rows.length) % pk.rows.length;
|
|
938
|
+
pkDraw(ta);
|
|
939
|
+
} else if (e.key === 'Enter' || e.key === 'Tab') pkPick(ta, pk.at);
|
|
940
|
+
else if (e.key === 'Escape') { // the text stays as typed; an answer streaming goes on
|
|
941
|
+
pk.shut = pk.start;
|
|
942
|
+
pkClose(ta);
|
|
943
|
+
if (e.stopPropagation) e.stopPropagation();
|
|
944
|
+
} else return false;
|
|
945
|
+
e.preventDefault();
|
|
946
|
+
return true;
|
|
947
|
+
}
|
|
948
|
+
function dropFiles() { // the chat is cleared: its files leave the app's memory too
|
|
949
|
+
if (!chatS.files.length) return;
|
|
950
|
+
chatS.files = [];
|
|
951
|
+
if (chatS.d) chatS.d.files = [];
|
|
952
|
+
post('/api/chat/file/remove', { all: true });
|
|
953
|
+
}
|
|
954
|
+
async function attachFile(f) {
|
|
955
|
+
if (!f || chatS.reading) return;
|
|
956
|
+
const ext = (/\.[^.]+$/.exec(f.name) || [''])[0].toLowerCase();
|
|
957
|
+
chatS.fileErr = !(ext in FILE_MAX) ? 'Attach a .pdf, .docx, .txt or .md file.'
|
|
958
|
+
: f.size > FILE_MAX[ext] * 2 ** 20 ? `This file is over ${FILE_MAX[ext]} MB, the most Keepfold reads from one ${ext} file.` : null;
|
|
959
|
+
if (!chatS.fileErr) chatS.reading = f.name;
|
|
960
|
+
drawFiles();
|
|
961
|
+
if (chatS.fileErr) return;
|
|
962
|
+
try {
|
|
963
|
+
const x = await new Promise((resolve, reject) => { // the upload route Setup uses, with its checks
|
|
964
|
+
const r = new XMLHttpRequest();
|
|
965
|
+
r.open('POST', '/api/import/upload');
|
|
966
|
+
r.setRequestHeader('X-Keepfold-Token', T);
|
|
967
|
+
r.setRequestHeader('Content-Type', 'application/octet-stream');
|
|
968
|
+
r.setRequestHeader('X-Keepfold-Name', encodeURIComponent(f.name));
|
|
969
|
+
r.onload = () => resolve(r);
|
|
970
|
+
r.onerror = () => reject(new Error('The app is not answering.'));
|
|
971
|
+
r.send(f);
|
|
972
|
+
});
|
|
973
|
+
let data = {};
|
|
974
|
+
try { data = JSON.parse(x.responseText); } catch (e) { /* no body */ }
|
|
975
|
+
if (x.status < 200 || x.status > 299) throw new Error(data.error || `The app answered ${x.status}.`);
|
|
976
|
+
const got = await api('/api/chat/attach', { upload: data.upload, name: f.name });
|
|
977
|
+
chatS.files = [...chatS.files, got].slice(-3); // the server keeps 3: the oldest drops
|
|
978
|
+
} catch (e) { chatS.fileErr = e.message; }
|
|
979
|
+
chatS.reading = null;
|
|
980
|
+
drawFiles();
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
async function openChat(id) {
|
|
984
|
+
if (chatS.busy) return;
|
|
985
|
+
if (!id) { dropFiles(); Object.assign(chatS, { id: null, msgs: [], remembers: 0, pages: [] }); }
|
|
986
|
+
else {
|
|
987
|
+
try {
|
|
988
|
+
const r = await api('/api/chat/get?id=' + encodeURIComponent(id));
|
|
989
|
+
Object.assign(chatS, { id, msgs: r.messages, remembers: r.remembers || 0 });
|
|
990
|
+
} catch (e) { toast.error(e.message); return; }
|
|
991
|
+
}
|
|
992
|
+
chatS.focus = true;
|
|
993
|
+
renderChat(chatS.d);
|
|
994
|
+
}
|
|
995
|
+
async function reloadChats() {
|
|
996
|
+
try { chatS.d.chats = (await api('/api/chat/list')).chats; } catch (e) { /* the page says so */ }
|
|
997
|
+
}
|
|
998
|
+
function saveSetting(body, ctrl) { // on change: a Saved mark beside the control
|
|
999
|
+
return post('/api/chat/settings', body, (s) => { chatS.d.settings = s; savedMark(ctrl); });
|
|
1000
|
+
}
|
|
1001
|
+
function settingsPanel(s) {
|
|
1002
|
+
const length = h('select', { id: 'chat-length' }, ['short', 'normal', 'long'].map((v) => h('option', { value: v, text: v[0].toUpperCase() + v.slice(1) })));
|
|
1003
|
+
length.value = s.length;
|
|
1004
|
+
length.addEventListener('change', () => saveSetting({ length: length.value }, length));
|
|
1005
|
+
const temp = h('input', { type: 'range', id: 'chat-temp', min: '0', max: '1', step: '0.1', value: String(s.temperature) });
|
|
1006
|
+
temp.addEventListener('change', () => saveSetting({ temperature: Number(temp.value) }, temp));
|
|
1007
|
+
const k = h('select', { id: 'chat-k' }, [4, 5, 6, 7, 8, 9, 10, 11, 12].map((n) => h('option', { value: String(n), text: String(n) })));
|
|
1008
|
+
k.value = String(s.passages);
|
|
1009
|
+
k.addEventListener('change', () => saveSetting({ passages: Number(k.value) }, k));
|
|
1010
|
+
const srcNames = { notes: 'Notes and mistakes', chats: 'Saved AI chats', browsing: 'Browsing', private: 'Private notes and browsing' };
|
|
1011
|
+
const srcs = Object.entries(srcNames).map(([key, label]) => {
|
|
1012
|
+
const cb = h('input', { type: 'checkbox', id: 'chat-src-' + key, checked: s.sources[key] });
|
|
1013
|
+
cb.addEventListener('change', () => saveSetting({ sources: { [key]: cb.checked } }, cb));
|
|
1014
|
+
return h('label', { class: 'check', for: 'chat-src-' + key }, cb, h('span', { text: label }));
|
|
1015
|
+
});
|
|
1016
|
+
const keep = h('input', { type: 'checkbox', id: 'chat-keep', checked: s.history });
|
|
1017
|
+
keep.addEventListener('change', () => saveSetting({ history: keep.checked }, keep));
|
|
1018
|
+
const wipe = () => confirmDialog('Delete all chats?', 'Delete',
|
|
1019
|
+
[h('p', { class: 'ink-2', text: 'Every saved chat is deleted from this computer. This cannot be undone.' })],
|
|
1020
|
+
() => post('/api/chat/delete', { all: true }, (r) => {
|
|
1021
|
+
toast.ok(`Deleted ${r.deleted} chat${r.deleted === 1 ? '' : 's'}.`);
|
|
1022
|
+
Object.assign(chatS, { id: null, msgs: [], remembers: 0 });
|
|
1023
|
+
load('chat');
|
|
1024
|
+
}));
|
|
1025
|
+
const det = h('details', { class: 'chat-set', open: chatS.setOpen },
|
|
1026
|
+
h('summary', { text: 'Chat settings' }),
|
|
1027
|
+
h('div', { class: 'set-panel' },
|
|
1028
|
+
h('div', { class: 'field' }, h('label', { for: 'chat-length', text: 'Answer length' }), length),
|
|
1029
|
+
h('div', { class: 'field' }, h('label', { for: 'chat-temp', text: 'Creativity' }), temp,
|
|
1030
|
+
h('p', { class: 'help', text: 'Left: sticks closely to your pages. Right: freer wording.' })),
|
|
1031
|
+
h('div', { class: 'field' }, h('label', { for: 'chat-k', text: 'Pages read per answer' }), k),
|
|
1032
|
+
h('div', { class: 'field' }, h('span', { class: 'lbl', text: 'Search in' }), ...srcs),
|
|
1033
|
+
h('div', { class: 'field' }, h('label', { class: 'check', for: 'chat-keep' }, keep, h('span', { text: 'Keep chat history' })),
|
|
1034
|
+
h('p', { class: 'help', text: 'Off: new chats are forgotten when the app stops; nothing is written.' })),
|
|
1035
|
+
h('div', { class: 'field' }, btn('Delete all chats', wipe)),
|
|
1036
|
+
h('div', { class: 'field' }, btn('Run Chat test', () => job('/api/chat/eval', {})),
|
|
1037
|
+
h('p', { class: 'help', text: 'Asks Chat 40 questions about a made-up vault and scores the answers. Your own notes and browsing are not used.' }),
|
|
1038
|
+
...(outputs.chat ? outputs.chat.nodes : []))));
|
|
1039
|
+
det.addEventListener('toggle', () => { chatS.setOpen = det.open; });
|
|
1040
|
+
return det;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
function drawSide() { // the past chats, wide (a list) and narrow (a select); redrawn in place
|
|
1044
|
+
const side = $('chat-side'), pick = $('chat-pick');
|
|
1045
|
+
if (!side || !pick) return;
|
|
1046
|
+
const chats = chatS.d.chats || [];
|
|
1047
|
+
const list = h('ul', { class: 'chat-list', 'aria-label': 'Past chats' }, chats.map((c) => h('li', { class: 'chat-item' + (c.id === chatS.id ? ' on' : '') },
|
|
1048
|
+
h('button', { class: 'chat-open', type: 'button', 'aria-current': c.id === chatS.id ? 'true' : null, onclick: () => openChat(c.id) },
|
|
1049
|
+
h('span', { class: 't', text: c.title }), h('span', { class: 'd', text: daysAgo(c.updated) })),
|
|
1050
|
+
btn('Delete', () => post('/api/chat/delete', { id: c.id }, () => {
|
|
1051
|
+
if (chatS.id === c.id) { dropFiles(); Object.assign(chatS, { id: null, msgs: [], remembers: 0 }); }
|
|
1052
|
+
load('chat');
|
|
1053
|
+
}), 'chat-del', { 'aria-label': `Delete chat: ${c.title}` }))));
|
|
1054
|
+
side.replaceChildren(btn('New chat', () => openChat(null), 'btn lit chat-new'),
|
|
1055
|
+
chats.length ? list : h('p', { class: 'ink-3 small', text: 'No chats yet. Ask something to start one.' }));
|
|
1056
|
+
pick.replaceChildren(h('option', { value: '', text: 'New chat' }),
|
|
1057
|
+
...chats.map((c) => h('option', { value: c.id, text: `${c.title} · ${daysAgo(c.updated)}` })));
|
|
1058
|
+
pick.value = chatS.id || '';
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
function renderChat(d) {
|
|
1062
|
+
chatS.d = d;
|
|
1063
|
+
if (chatS.busy) return; // never rebuild under a streaming answer
|
|
1064
|
+
if (!d.vault) {
|
|
1065
|
+
chatS.ask = false;
|
|
1066
|
+
$('chat').replaceChildren(board('Chat', {}, row('No vault yet', null, 'Set one up first.', [btn('Open Setup', () => show('setup', true))])));
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
const pick = h('select', { class: 'chat-pick', id: 'chat-pick', 'aria-label': 'Chat' });
|
|
1070
|
+
pick.addEventListener('change', () => openChat(pick.value || null));
|
|
1071
|
+
const side = h('div', { class: 'chat-side', id: 'chat-side' });
|
|
1072
|
+
|
|
1073
|
+
const log = h('div', { class: 'chat-log', id: 'chat-log', role: 'log', 'aria-live': 'polite', 'aria-label': 'Conversation' });
|
|
1074
|
+
chatS.files = d.files || [];
|
|
1075
|
+
log.addEventListener('dragover', (e) => e.preventDefault()); // a file dropped here is attached
|
|
1076
|
+
log.addEventListener('drop', (e) => { e.preventDefault(); attachFile(e.dataTransfer && e.dataTransfer.files[0]); });
|
|
1077
|
+
chatS.els = chatS.msgs.map((m) => (m.role === 'user' ? userMsg(m) : botMsg(m).el));
|
|
1078
|
+
log.append(...chatS.els);
|
|
1079
|
+
memLine(log);
|
|
1080
|
+
const missing = d.missing || [];
|
|
1081
|
+
if (!chatS.msgs.length) { // the examples fill the message box
|
|
1082
|
+
log.append(h('div', { class: 'chat-empty' }, h('p', { text: 'Ask about anything you\'ve saved or browsed.' }),
|
|
1083
|
+
missing.length ? h('p', { text: 'Until then, Chat can still answer questions like these from what Keepfold already has:' }) : null,
|
|
1084
|
+
h('div', { class: 'inline' }, (missing.length ? DATA_EXAMPLES : EXAMPLES).map((x) => btn(x, () => { chatS.draft = x; chatS.focus = true; renderChat(chatS.d); })))));
|
|
1085
|
+
}
|
|
1086
|
+
// something missing: what to set up, above the message box (site and study questions still work)
|
|
1087
|
+
const need = missing.length ? missingRows(missing, d.llm_error ? `The local model is not used: ${d.llm_error}` : null) : null;
|
|
1088
|
+
let foot;
|
|
1089
|
+
{
|
|
1090
|
+
const ta = h('textarea', { id: 'chat-input', rows: '1', value: chatS.draft, placeholder: 'Message Keepfold', 'aria-label': 'Message', spellcheck: 'true',
|
|
1091
|
+
'aria-controls': 'chat-pk', 'aria-expanded': 'false' });
|
|
1092
|
+
const grow = () => { ta.rows = String(Math.min(6, Math.max(1, ta.value.split('\n').length))); };
|
|
1093
|
+
grow();
|
|
1094
|
+
ta.addEventListener('input', () => { chatS.draft = ta.value; grow(); pkInput(ta); });
|
|
1095
|
+
ta.addEventListener('blur', () => pkClose(ta));
|
|
1096
|
+
const go = h('button', { class: 'btn lit chat-send', type: 'button', id: 'chat-send', text: 'Send' });
|
|
1097
|
+
// a Stop within 400 ms of sending is a double click on Send, not a Stop (Esc still stops)
|
|
1098
|
+
go.addEventListener('click', () => (!chatS.busy ? send(ta, go, log) : Date.now() - chatS.busy.t0 > 400 ? chatS.busy.ctrl.abort() : null));
|
|
1099
|
+
ta.addEventListener('keydown', (e) => {
|
|
1100
|
+
if (pkKey(e, ta)) return;
|
|
1101
|
+
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); if (!chatS.busy) send(ta, go, log); }
|
|
1102
|
+
});
|
|
1103
|
+
// shown while an answer streams and the reader has scrolled up: jumps to the end
|
|
1104
|
+
chatS.pill = h('button', { class: 'btn new-text', type: 'button', hidden: true, onclick: () => { chatS.follow = true; chatS.pill.hidden = true; toEnd(); } }, '↓ New text');
|
|
1105
|
+
const pickF = h('input', { type: 'file', id: 'chat-file', accept: '.pdf,.docx,.txt,.md', hidden: true });
|
|
1106
|
+
pickF.addEventListener('change', () => { const f = pickF.files && pickF.files[0]; pickF.value = ''; attachFile(f); });
|
|
1107
|
+
foot = h('div', { class: 'composer' }, chatS.pill, h('div', { id: 'chat-files' }),
|
|
1108
|
+
h('div', { class: 'crow' }, ta, btn('Attach a file', () => pickF.click()), go, pickF,
|
|
1109
|
+
h('ul', { id: 'chat-pk', class: 'pk-list', role: 'listbox', 'aria-label': 'Pages to attach', hidden: true })),
|
|
1110
|
+
h('p', { class: 'help', text: missing.length ? 'Runs on this computer. Nothing leaves it.' : `Runs on this computer with ${d.model || 'your local model'}. Nothing leaves it.` }));
|
|
1111
|
+
}
|
|
1112
|
+
const main = h('div', { class: 'chat-main' }, h('div', { class: 'chat-bar' }, pick, settingsPanel(d.settings)), need, log, foot);
|
|
1113
|
+
$('chat').replaceChildren(h('div', { class: 'chat' }, side, main));
|
|
1114
|
+
drawSide();
|
|
1115
|
+
drawFiles();
|
|
1116
|
+
if (chatS.focus && $('chat-input')) $('chat-input').focus();
|
|
1117
|
+
chatS.focus = false;
|
|
1118
|
+
if (chatS.ask) { // the welcome guide's question: sent as Enter sends it
|
|
1119
|
+
chatS.ask = false;
|
|
1120
|
+
send($('chat-input'), $('chat-send'), log);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
// the page follows a streaming answer only while the reader is at the bottom; scrolled up,
|
|
1125
|
+
// it stays put and the New text pill offers the jump
|
|
1126
|
+
const toEnd = () => window.scrollTo(0, document.documentElement.scrollHeight);
|
|
1127
|
+
const atEnd = () => window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 48;
|
|
1128
|
+
function followEnd() {
|
|
1129
|
+
if (chatS.follow) toEnd();
|
|
1130
|
+
else if (chatS.pill) chatS.pill.hidden = false;
|
|
1131
|
+
}
|
|
1132
|
+
window.addEventListener('scroll', () => {
|
|
1133
|
+
const end = atEnd();
|
|
1134
|
+
if (chatS.busy) chatS.follow = end;
|
|
1135
|
+
if (end && chatS.pill) chatS.pill.hidden = true;
|
|
1136
|
+
}, { passive: true });
|
|
1137
|
+
// Esc stops a streaming answer, like Stop
|
|
1138
|
+
$('chat').addEventListener('keydown', (e) => {
|
|
1139
|
+
if (e.key === 'Escape' && chatS.busy) { e.preventDefault(); chatS.busy.ctrl.abort(); }
|
|
1140
|
+
});
|
|
1141
|
+
|
|
1142
|
+
async function send(ta, go, log) {
|
|
1143
|
+
const text = ta.value.trim();
|
|
1144
|
+
if (!text) { toast('Type a message first.'); return; }
|
|
1145
|
+
const ctrl = new AbortController();
|
|
1146
|
+
chatS.busy = { ctrl, t0: Date.now() };
|
|
1147
|
+
const empty = log.querySelector('.chat-empty');
|
|
1148
|
+
if (empty) log.replaceChildren(); // the examples go once a chat starts
|
|
1149
|
+
chatS.msgs.push({ role: 'user', text });
|
|
1150
|
+
chatS.els.push(userMsg({ text }));
|
|
1151
|
+
log.append(chatS.els[chatS.els.length - 1]);
|
|
1152
|
+
const m = { role: 'assistant', text: '', sources: [], model: chatS.d.model, t0: Date.now() };
|
|
1153
|
+
const bot = botMsg(m);
|
|
1154
|
+
bot.draw(true);
|
|
1155
|
+
const tick = setInterval(() => { if (!m.text) bot.draw(true); }, 1000);
|
|
1156
|
+
log.append(bot.el);
|
|
1157
|
+
log.setAttribute('aria-busy', 'true'); // a screen reader hears the answer once, when it is done
|
|
1158
|
+
chatS.follow = true;
|
|
1159
|
+
if (chatS.pill) chatS.pill.hidden = true;
|
|
1160
|
+
toEnd();
|
|
1161
|
+
ta.value = chatS.draft = '';
|
|
1162
|
+
ta.rows = '1';
|
|
1163
|
+
ta.focus();
|
|
1164
|
+
pkClose(ta);
|
|
1165
|
+
pk.shut = -1;
|
|
1166
|
+
const pages = chatS.pages; // the picked pages go with this message only
|
|
1167
|
+
chatS.pages = [];
|
|
1168
|
+
drawFiles();
|
|
1169
|
+
go.textContent = 'Stop';
|
|
1170
|
+
go.setAttribute('aria-label', 'Stop the answer');
|
|
1171
|
+
let failed = null;
|
|
1172
|
+
try {
|
|
1173
|
+
const r = await fetch('/api/chat', {
|
|
1174
|
+
method: 'POST', headers: { 'X-Keepfold-Token': T, 'Content-Type': 'application/json' },
|
|
1175
|
+
body: JSON.stringify({ id: chatS.id, text, ...(chatS.files.length ? { files: chatS.files.map((f) => f.id) } : {}),
|
|
1176
|
+
...(pages.length ? { pages: pages.map((p) => p.id) } : {}) }), signal: ctrl.signal,
|
|
1177
|
+
});
|
|
1178
|
+
if (!r.ok) {
|
|
1179
|
+
let data = {};
|
|
1180
|
+
try { data = await r.json(); } catch (e) { /* no body */ }
|
|
1181
|
+
if (r.status === 401) gone('This page lost its key. ' + REOPEN);
|
|
1182
|
+
throw new Error(data.error || `The app answered ${r.status}.`);
|
|
1183
|
+
}
|
|
1184
|
+
const reader = r.body.getReader(), dec = new TextDecoder();
|
|
1185
|
+
let buf = '';
|
|
1186
|
+
for (;;) {
|
|
1187
|
+
const { value, done } = await reader.read();
|
|
1188
|
+
if (done) break;
|
|
1189
|
+
buf += dec.decode(value, { stream: true });
|
|
1190
|
+
let i;
|
|
1191
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
1192
|
+
const line = buf.slice(0, i).trim();
|
|
1193
|
+
buf = buf.slice(i + 1);
|
|
1194
|
+
if (!line) continue;
|
|
1195
|
+
const ev = JSON.parse(line);
|
|
1196
|
+
if (ev.t === 'wait') continue; // the server's keepalive while the model is quiet
|
|
1197
|
+
if (ev.id) chatS.id = ev.id;
|
|
1198
|
+
if (ev.t === 'start') m.model = ev.model;
|
|
1199
|
+
else if (ev.t === 'step') m.step = ev.s;
|
|
1200
|
+
else if (ev.t === 'done') { m.seconds = ev.seconds; if (ev.remembers != null) chatS.remembers = ev.remembers; }
|
|
1201
|
+
else if (ev.t === 'think') m.thinking = true;
|
|
1202
|
+
else if (ev.t === 'tok') m.text += ev.s;
|
|
1203
|
+
else if (ev.t === 'text') m.text = ev.s;
|
|
1204
|
+
else if (ev.t === 'facts') m.facts = ev.facts;
|
|
1205
|
+
else if (ev.t === 'src') {
|
|
1206
|
+
m.sources = ev.sources; m.searched = ev.searched || []; m.coverage = ev.coverage; m.unquoted = ev.unquoted || [];
|
|
1207
|
+
m.certainty = ev.certainty; m.horizon = ev.horizon; m.conflicts = ev.conflicts || [];
|
|
1208
|
+
}
|
|
1209
|
+
else if (ev.t === 'err') failed = ev;
|
|
1210
|
+
if (ev.t !== 'err') { bot.draw(ev.t !== 'done'); followEnd(); }
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
} catch (e) {
|
|
1214
|
+
if (e.name === 'AbortError') m.stopped = true;
|
|
1215
|
+
else failed = { code: 'app', message: e.name === 'TypeError' ? 'The app is not answering.' : e.message };
|
|
1216
|
+
}
|
|
1217
|
+
clearInterval(tick);
|
|
1218
|
+
chatS.busy = null;
|
|
1219
|
+
log.setAttribute('aria-busy', 'false');
|
|
1220
|
+
go.textContent = 'Send';
|
|
1221
|
+
go.setAttribute('aria-label', 'Send');
|
|
1222
|
+
if (failed) {
|
|
1223
|
+
if (failed.code === 'not_set_up' || failed.code === 'no_local_model') {
|
|
1224
|
+
bot.el.replaceChildren(missingRows([failed.code === 'not_set_up' ? 'embed' : 'llm'], failed.message));
|
|
1225
|
+
} else bot.el.replaceChildren(h('div', { class: 'board' }, row('No answer', null, failed.message, null)));
|
|
1226
|
+
if (['app', 'not_set_up', 'no_local_model'].includes(failed.code)) { // the question was not kept
|
|
1227
|
+
chatS.msgs.pop();
|
|
1228
|
+
chatS.els.pop();
|
|
1229
|
+
ta.value = chatS.draft = text;
|
|
1230
|
+
chatS.pages = pages; // and its pages, to send again
|
|
1231
|
+
drawFiles();
|
|
1232
|
+
}
|
|
1233
|
+
ta.focus({ preventScroll: true });
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
if (m.text || m.stopped) { chatS.msgs.push(m); chatS.els.push(bot.el); }
|
|
1237
|
+
memLine(log);
|
|
1238
|
+
bot.draw(false);
|
|
1239
|
+
followEnd();
|
|
1240
|
+
ta.focus({ preventScroll: true });
|
|
1241
|
+
await reloadChats();
|
|
1242
|
+
drawSide();
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
/* Connect AI apps */
|
|
1246
|
+
function renderConnect(d) {
|
|
1247
|
+
const boxes = [];
|
|
1248
|
+
const here = (t) => (t.detected || t.connected ? 0 : 1); // apps on this computer first
|
|
1249
|
+
const rows = [...d.targets].sort((a, b) => here(a) - here(b)).map((t) => {
|
|
1250
|
+
const cb = h('input', { type: 'checkbox', id: 'cb-' + t.id, checked: t.connected, disabled: !t.detected && !t.connected });
|
|
1251
|
+
cb.dataset.id = t.id;
|
|
1252
|
+
boxes.push(cb);
|
|
1253
|
+
// LM Studio only, while Local AI access (Browsing) is on: the --private opt-in
|
|
1254
|
+
const priv = t.private_offer ? h('input', { type: 'checkbox', id: 'pv-' + t.id, checked: t.private }) : null;
|
|
1255
|
+
if (priv) cb.priv = priv;
|
|
1256
|
+
const sub = !t.detected && !t.connected ? 'Not found on this computer.'
|
|
1257
|
+
: t.stale ? 'Its Keepfold entry is out of date (another folder or program). Apply updates it.'
|
|
1258
|
+
: t.connected ? 'Keepfold is connected.' : 'Found on this computer; not connected.';
|
|
1259
|
+
const what = h('details', { class: 'what' }, h('summary', { text: 'What this changes' }),
|
|
1260
|
+
t.files.length ? [h('p', { text: 'Files:' }), h('ul', { class: 'files' }, t.files.map((f) => h('li', { class: 'mono', text: f })))] : null,
|
|
1261
|
+
t.snippet ? [h('p', { text: t.commands ? 'Commands Keepfold runs:' : 'The entry Keepfold adds:' }), h('pre', { text: t.snippet })]
|
|
1262
|
+
: h('p', { text: 'Set up a vault first; the entry points at it.' }),
|
|
1263
|
+
t.note ? h('p', { text: t.note }) : null);
|
|
1264
|
+
// apps whose own instructions Keepfold cannot write: the "use Keepfold every time" text to paste
|
|
1265
|
+
const paste = t.paste && (t.detected || t.connected);
|
|
1266
|
+
return h('div', { class: 'brow trow' + (t.detected || t.connected ? '' : ' off') }, cb,
|
|
1267
|
+
h('div', { class: 't' },
|
|
1268
|
+
h('div', { class: 'line1' }, h('label', { class: 'ttl', for: 'cb-' + t.id, text: t.label }),
|
|
1269
|
+
t.stale ? h('span', { class: 'code-tag warn', text: 'Out of date' })
|
|
1270
|
+
: t.connected ? h('span', { class: 'code-tag', text: 'Connected' }) : null),
|
|
1271
|
+
h('span', { class: 'sub', text: sub + (t.error ? ` ${t.error}` : '') }),
|
|
1272
|
+
paste ? h('span', { class: 'sub', text: t.paste }) : null,
|
|
1273
|
+
priv ? h('label', { class: 'check' }, priv, h('span', { text: 'Include private browsing search (this computer only)' })) : null,
|
|
1274
|
+
what),
|
|
1275
|
+
paste ? h('div', { class: 'acts' }, copyBtn(() => d.instructions, 'Copy failed; the text is in docs/CONNECT.md, and `keepfold setup` prints it.', null, true, null, null, 'Copy instructions')) : null);
|
|
1276
|
+
});
|
|
1277
|
+
const found = d.targets.filter((t) => t.detected).length, on = d.targets.filter((t) => t.connected).length;
|
|
1278
|
+
const apply = () => {
|
|
1279
|
+
const want = {};
|
|
1280
|
+
for (const b of boxes) if (!b.disabled) want[b.dataset.id] = b.checked && b.priv && b.priv.checked ? 'private' : b.checked;
|
|
1281
|
+
return post('/api/connect/plan', { want }, (p) => {
|
|
1282
|
+
if (!p.rows.length) { toast('Nothing to change.'); return; }
|
|
1283
|
+
confirmChanges(p.rows, () => job('/api/connect/apply', { want }));
|
|
1284
|
+
});
|
|
1285
|
+
};
|
|
1286
|
+
const skill = board('Claude Desktop skill', {},
|
|
1287
|
+
row('keepfold-skill.zip', d.skill_zip_found ? d.skill_zip : null, 'Skills cannot be installed by file. In Claude Desktop, open Settings → Capabilities. First turn on Code execution and file creation on that page, then upload this zip under Skills; /keepfold then works in Chat.',
|
|
1288
|
+
d.skill_zip_found ? [btn('Open folder', () => post('/api/open', { what: 'skill_zip' }), null, { 'aria-label': 'Open folder: Claude Desktop skill' }),
|
|
1289
|
+
copyBtn(() => d.skill_zip, 'Copy failed; select the path and copy it.')] : [ext(d.skill_url, 'Download keepfold-skill.zip')]));
|
|
1290
|
+
put('connect', board('AI apps', { note: `${found} found · ${on} connected`, btn: ['Apply…', apply] }, ...rows,
|
|
1291
|
+
h('div', { class: 'foot', text: d.vault ? 'Apply shows the exact files first. Backups are named <file>.keepfold-<date>.bak, next to each file.' : 'Set up a vault first (Setup); each entry points at it.' })), skill,
|
|
1292
|
+
d.packs ? packsBoard(d.packs) : null, d.profiles ? profilesBoard(d.profiles, d.scopes) : null);
|
|
1293
|
+
}
|
|
1294
|
+
// plan v9 item 8: context packs for web chats with no MCP; Copy, else the text is selected
|
|
1295
|
+
const PACK_NAMES = { general: 'General', coding: 'Coding', writing: 'Writing', interview: 'Interview', research: 'Research', review: 'Review' };
|
|
1296
|
+
// R32a: role packs say what they hold; the others name their own preferences
|
|
1297
|
+
const PACK_PREFS = { interview: 'career and communication preferences, for a job interview practice chat',
|
|
1298
|
+
research: 'learning, project and communication preferences, for a research collaboration chat',
|
|
1299
|
+
review: 'coding and communication preferences, for a code review chat' };
|
|
1300
|
+
function packsBoard(packs) {
|
|
1301
|
+
return board('Context packs', { note: 'for ChatGPT, Gemini and other web chats' }, ...packs.map((p) => {
|
|
1302
|
+
const name = PACK_NAMES[p.id] || p.id;
|
|
1303
|
+
if (!p.sizes.some((s) => s.text)) return row(name, null, 'Nothing to pack yet: add lines to me/core.md or me/preferences.md.');
|
|
1304
|
+
let cur = p.sizes[0]; // 1,500 characters each time the page opens
|
|
1305
|
+
const area = h('textarea', { class: 'mono', readonly: true, rows: 8, 'aria-label': `${name} pack text` });
|
|
1306
|
+
const count = h('span', { class: 'val' });
|
|
1307
|
+
const stale = h('span', { class: 'sub stale' }, h('span', { class: 'stale-dot', 'aria-hidden': 'true' }), 'Changed since your last copy');
|
|
1308
|
+
const sizeBtns = p.sizes.map((s) => {
|
|
1309
|
+
const b = h('button', { class: 'chip', type: 'button' }, s.chars.toLocaleString('en-US'), h('span', { class: 'sr-only', text: ' characters' }));
|
|
1310
|
+
b.addEventListener('click', () => { cur = s; show(); });
|
|
1311
|
+
return b;
|
|
1312
|
+
});
|
|
1313
|
+
const show = () => {
|
|
1314
|
+
area.value = cur.text;
|
|
1315
|
+
count.textContent = `${cur.text.length.toLocaleString('en-US')} characters`;
|
|
1316
|
+
stale.hidden = !cur.changed;
|
|
1317
|
+
sizeBtns.forEach((b, i) => b.setAttribute('aria-pressed', String(p.sizes[i] === cur)));
|
|
1318
|
+
};
|
|
1319
|
+
show();
|
|
1320
|
+
const what = h('details', { class: 'what' }, h('summary', { text: 'Show the text' }), area);
|
|
1321
|
+
const select = () => { what.open = true; area.focus(); area.select(); toast('Copy is blocked here; the text is selected, press Ctrl+C.'); };
|
|
1322
|
+
const copied = () => { const s = cur; post('/api/connect/copied', { pack: p.id, chars: s.chars, hash: s.hash }, () => { s.changed = false; show(); }); };
|
|
1323
|
+
return h('div', { class: 'brow' },
|
|
1324
|
+
h('div', { class: 't' },
|
|
1325
|
+
h('div', { class: 'line1' }, h('span', { class: 'ttl', text: name }), count),
|
|
1326
|
+
h('span', { class: 'sub', text: 'Your pinned core, then your ' + (PACK_PREFS[p.id] || (p.id === 'general' ? 'preferences' : name.toLowerCase() + ' preferences')) + '. Paste it at the start of a chat. Private pages are never in it.' }),
|
|
1327
|
+
stale,
|
|
1328
|
+
h('div', { class: 'pack-size', role: 'group', 'aria-label': `${name} pack size` }, ...sizeBtns),
|
|
1329
|
+
what),
|
|
1330
|
+
h('div', { class: 'acts' }, copyBtn(() => cur.text, '', null, true, select, copied)));
|
|
1331
|
+
}));
|
|
1332
|
+
}
|
|
1333
|
+
// plan v9 item 8: which scopes each AI app gets over MCP; saved at once, from this page only
|
|
1334
|
+
function profilesBoard(profiles, scopes) {
|
|
1335
|
+
const data = { profiles: profiles.profiles.map((p) => ({ ...p, scopes: [...p.scopes] })), unknown: [...profiles.unknown] };
|
|
1336
|
+
const checks = (list, label, key) => h('div', { class: 'sub' }, scopes.map((s) => {
|
|
1337
|
+
const name = s === 'all' ? 'everything except private' : s;
|
|
1338
|
+
const cb = h('input', { type: 'checkbox', id: `pf-${key}-${s}`, checked: list.includes(s), 'aria-label': `${label}: ${name}` });
|
|
1339
|
+
cb.addEventListener('change', () => {
|
|
1340
|
+
const i = list.indexOf(s);
|
|
1341
|
+
if (cb.checked && i < 0) list.push(s);
|
|
1342
|
+
if (!cb.checked && i >= 0) list.splice(i, 1);
|
|
1343
|
+
post('/api/profiles', data, () => savedMark(cb));
|
|
1344
|
+
});
|
|
1345
|
+
return h('label', { class: 'check' }, cb, h('span', { text: name }));
|
|
1346
|
+
}));
|
|
1347
|
+
const prow = (title, sub, list, key) => h('div', { class: 'brow' },
|
|
1348
|
+
h('div', { class: 't' }, h('div', { class: 'line1' }, h('span', { class: 'ttl', text: title })),
|
|
1349
|
+
h('span', { class: 'sub', text: sub }), checks(list, title, key)));
|
|
1350
|
+
return board('Agent profiles', { note: 'what each AI app may read' },
|
|
1351
|
+
...data.profiles.map((p, i) => prow(`Apps whose name contains “${p.match}”`,'The first name that matches the app wins.', p.scopes, i)),
|
|
1352
|
+
prow('Any other app', 'Apps no name above matches.', data.unknown, 'other'),
|
|
1353
|
+
h('div', { class: 'foot', text: 'core: your pinned lines. projects: your project pages. learning: also the teaching contract. Each other scope: that section of your preferences. personal: your profile, goals, journal, people and past chats.' }),
|
|
1354
|
+
h('div', { class: 'foot', text: 'Private pages never go to an AI app over MCP, under any profile.' }));
|
|
1355
|
+
}
|
|
1356
|
+
function confirmDialog(title, okText, body, ok) { // the page's one confirm dialog
|
|
1357
|
+
const dlg = $('confirm');
|
|
1358
|
+
$('confirm-title').textContent = title;
|
|
1359
|
+
$('confirm-ok').textContent = okText;
|
|
1360
|
+
$('confirm-body').replaceChildren(...body);
|
|
1361
|
+
$('confirm-ok').onclick = () => { dlg.close(); ok(); };
|
|
1362
|
+
$('confirm-no').onclick = () => dlg.close();
|
|
1363
|
+
dlg.showModal();
|
|
1364
|
+
}
|
|
1365
|
+
const confirmChanges = (rows, ok) => confirmDialog('Apply these changes?', 'Apply',
|
|
1366
|
+
[h('p', { class: 'ink-2', text: 'Keepfold will change these files, backing each one up first:' }), changeList(rows)], ok);
|
|
1367
|
+
|
|
1368
|
+
/* Local model */
|
|
1369
|
+
const gb = (b) => (b ? `${(b / 1e9).toFixed(1)} GB` : '');
|
|
1370
|
+
// a runner's state in the same words on this page and in Setup (wizard.runner_state)
|
|
1371
|
+
const RSTATE = { running: 'running', stopped: 'installed, not running', not_installed: 'not installed' };
|
|
1372
|
+
function renderLlm(d) {
|
|
1373
|
+
if (!d.available) { put('llm', board('Local model', {}, note('Not available in this version yet.'))); return; }
|
|
1374
|
+
const runner = board('Runner', {},
|
|
1375
|
+
row('Ollama', d.ollama === null ? RSTATE[d.ollama_state] : `${d.ollama.length} models`, 'Recommended. Keepfold uses it whenever it answers on this computer; set it up under Setup → Local model.'),
|
|
1376
|
+
row('LM Studio', d.lms ? 'found' : 'not found', d.lms || 'The alternative runner, with its own model library.',
|
|
1377
|
+
d.lms ? null : [ext('https://lmstudio.ai/download', 'Get LM Studio')]),
|
|
1378
|
+
row('LM Studio server', d.server_port ? `on, port ${d.server_port}` : 'off', 'Starts by itself when a model loads.'),
|
|
1379
|
+
row('Loaded now', d.loaded.length ? d.loaded.join(', ') : 'nothing', 'LM Studio unloads a model after 10 idle minutes.'));
|
|
1380
|
+
// every chat model already installed, in either runner (embedding models left out by the server)
|
|
1381
|
+
const ollama = d.ollama || [];
|
|
1382
|
+
const choices = [...ollama.map((n) => ({ model: n, runner: 'ollama' })), ...d.models.map((m) => ({ model: m.key, runner: 'lmstudio' }))];
|
|
1383
|
+
const opt = (i, text) => h('option', { value: String(i), text });
|
|
1384
|
+
const sel = h('select', { id: 'llm-model', 'aria-label': 'Model' },
|
|
1385
|
+
h('option', { value: '', text: choices.length ? 'Choose a model' : 'No models yet' }),
|
|
1386
|
+
ollama.length ? h('optgroup', { label: 'Ollama' }, ollama.map((n, i) => opt(i, n))) : null,
|
|
1387
|
+
d.models.length ? h('optgroup', { label: 'LM Studio' }, d.models.map((m, i) => opt(ollama.length + i, [m.name, m.params, gb(m.size)].filter(Boolean).join(' · ')))) : null);
|
|
1388
|
+
let at = choices.findIndex((c) => c.model === d.model && c.runner === d.runner);
|
|
1389
|
+
if (at < 0) at = choices.findIndex((c) => c.model === d.model);
|
|
1390
|
+
sel.value = at < 0 ? '' : String(at);
|
|
1391
|
+
const chosen = () => (sel.value === '' ? null : choices[Number(sel.value)] || null);
|
|
1392
|
+
const loadBtn = btn('Load', () => job('/api/llm/load', { model: chosen().model }));
|
|
1393
|
+
const save = () => { const c = chosen(); return post('/api/llm/settings', { model: c.model, runner: c.runner }, () => { toast.ok('Saved.'); load('llm'); }); };
|
|
1394
|
+
const saveBtn = btn('Save choice', save), testBtn = btn('Test', () => job('/api/llm/test', {}));
|
|
1395
|
+
const sync = () => { // nothing chosen: nothing to save, load or test
|
|
1396
|
+
const c = chosen();
|
|
1397
|
+
saveBtn.disabled = testBtn.disabled = !c;
|
|
1398
|
+
loadBtn.disabled = !c || c.runner !== 'lmstudio';
|
|
1399
|
+
};
|
|
1400
|
+
sel.addEventListener('change', sync);
|
|
1401
|
+
sync();
|
|
1402
|
+
// an optional second model for imports and site descriptions, which run while you are away
|
|
1403
|
+
const bgSel = h('select', { id: 'llm-bg', 'aria-label': 'Model for background work' },
|
|
1404
|
+
h('option', { value: '', text: 'Same as the model above' }),
|
|
1405
|
+
choices.map((c) => h('option', { value: c.model, text: c.model, selected: c.model === d.background_model })));
|
|
1406
|
+
if (d.background_model && !choices.some((c) => c.model === d.background_model)) bgSel.append(h('option', { value: d.background_model, text: `${d.background_model} (not found now)`, selected: true }));
|
|
1407
|
+
const bgSave = btn('Save', () => post('/api/llm/settings', { background_model: bgSel.value }, () => { toast.ok('Saved.'); load('llm'); }),
|
|
1408
|
+
null, { 'aria-label': 'Save: Model for background work' });
|
|
1409
|
+
const enabled = h('input', { type: 'checkbox', id: 'llm-on', checked: d.enabled });
|
|
1410
|
+
enabled.addEventListener('change', () => post('/api/llm/settings', { enabled: enabled.checked }, () => { toast.ok(enabled.checked ? 'Local model on.' : 'Local model off.'); load('llm'); }));
|
|
1411
|
+
const model = board('Model', { note: d.model ? `chosen: ${d.model}` : 'none chosen' },
|
|
1412
|
+
d.error ? note(`Not used: ${d.error}`) : null,
|
|
1413
|
+
choices.length ? null : note('No models installed yet. Download an Ollama model below, or set one up under Setup → Local model.'),
|
|
1414
|
+
h('div', { class: 'field' }, h('label', { for: 'llm-model', text: 'Model (installed in Ollama or LM Studio)' }),
|
|
1415
|
+
h('div', { class: 'inline' }, sel, saveBtn, loadBtn, testBtn),
|
|
1416
|
+
h('p', { class: 'help' }, 'Load is for LM Studio models: it starts LM Studio and loads the model. Ollama loads its models by itself. Test sends one made-up sentence and shows the answer and time. ',
|
|
1417
|
+
ext('https://lmstudio.ai/models', 'Get models'), ' in LM Studio, or download an Ollama model below.')),
|
|
1418
|
+
h('div', { class: 'field' }, h('label', { class: 'check' }, enabled, h('span', { text: 'Use the local model' })),
|
|
1419
|
+
h('p', { class: 'help', text: 'On: Keepfold may start LM Studio and load the chosen model, and the browse import asks it for short summaries of your private pages. Off: the browse import uses rules and the search model only; Chat still uses a model that is already running.' })),
|
|
1420
|
+
h('div', { class: 'field' }, h('label', { for: 'llm-bg', text: 'Model for background work (optional)' }),
|
|
1421
|
+
h('div', { class: 'inline' }, bgSel, bgSave),
|
|
1422
|
+
h('p', { class: 'help', text: 'Browsing imports and site descriptions run while you are away, so a larger, slower model can do them better (for example a 9B model while Chat uses a 2B one). If it does not answer, the model above is used. Two models can sit in memory at once, so with 8 GB of graphics memory or less, leave this as the same model.' })));
|
|
1423
|
+
// download another Ollama model by name; the list above reloads when the job ends
|
|
1424
|
+
const name = h('input', { type: 'text', id: 'llm-pull', placeholder: 'qwen3.5:4b', spellcheck: 'false', autocomplete: 'off' });
|
|
1425
|
+
const pull = () => {
|
|
1426
|
+
const v = name.value.trim();
|
|
1427
|
+
if (!v) { toast('Type a model name first.'); return null; }
|
|
1428
|
+
return post('/api/llm/size', { name: v }, (r) => confirmDialog(`Download ${r.name}?`, 'Download',
|
|
1429
|
+
[h('p', { class: 'ink-2', text: `${r.size}, from ${r.source}.` })],
|
|
1430
|
+
() => job('/api/llm/pull', { name: r.name })));
|
|
1431
|
+
};
|
|
1432
|
+
const rec = d.recommend, hw = d.hardware;
|
|
1433
|
+
const download = board('Download an Ollama model', {},
|
|
1434
|
+
hw && rec ? row('This computer', `${hw.label} → ${rec.label} suits it`, null,
|
|
1435
|
+
[btn(`Use ${rec.ollama} (${rec.size})`, () => { name.value = rec.ollama; name.focus(); })]) : null,
|
|
1436
|
+
h('div', { class: 'field' }, h('label', { for: 'llm-pull', text: 'Model name' }),
|
|
1437
|
+
h('div', { class: 'inline' }, name, btn('Download', pull)),
|
|
1438
|
+
h('p', { class: 'help' }, 'A name from ', ext('https://ollama.com/library', 'ollama.com/library'), ', like qwen3.5:4b. Ollama must be running. Cloud models are refused.')));
|
|
1439
|
+
put('llm', runner, model, download);
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/* Past history: one list for the Setup step and the Browsing section */
|
|
1443
|
+
const BROWSERS = { chrome: 'Chrome', edge: 'Edge', brave: 'Brave', comet: 'Comet', firefox: 'Firefox' };
|
|
1444
|
+
const untick = new Set(), seeded = new Set();
|
|
1445
|
+
function seedUntick(hist) { // browse.skip_profiles starts unticked; the user's clicks win after
|
|
1446
|
+
for (const s of hist.sources) if (!seeded.has(s.key)) { seeded.add(s.key); if (s.skip) untick.add(s.key); }
|
|
1447
|
+
}
|
|
1448
|
+
function importTicked(hist, from) { // only new visits: the import skips the days it has
|
|
1449
|
+
seedUntick(hist);
|
|
1450
|
+
const all = hist.sources.map((s) => s.key), keys = all.filter((k) => !untick.has(k));
|
|
1451
|
+
if (!keys.length) { toast('Tick at least one browser.'); return; }
|
|
1452
|
+
return job('/api/browse/import', { sources: keys, skip: all.filter((k) => untick.has(k)), from });
|
|
1453
|
+
}
|
|
1454
|
+
/* The Browsing section's last import and browse.auto_import_hours (0 = off) */
|
|
1455
|
+
// shown while automatic import is on and the receiver does not start at login (Status, Browsing)
|
|
1456
|
+
const LOGIN_HINT = 'New history comes in only while Keepfold runs. Start the receiver at login to keep it going in the background.';
|
|
1457
|
+
const loginBtn = () => btn('Start at login', () => job('/api/browse/login', { on: true }));
|
|
1458
|
+
function autoImportRows(hist, s, login) {
|
|
1459
|
+
if (!hist || !hist.available || !hist.sources.length) return [];
|
|
1460
|
+
const at = hist.imported ? new Date(hist.imported) : null, ok = at && !isNaN(at);
|
|
1461
|
+
const hours = h('input', { type: 'number', id: 'b-auto', min: 0, max: 168, step: 1, value: String(s.auto_import_hours ?? 6) });
|
|
1462
|
+
hours.addEventListener('change', () => {
|
|
1463
|
+
const v = hours.value.trim() === '' ? NaN : Number(hours.value); // empty is not 0: it never turns import off
|
|
1464
|
+
if (!(v >= 0 && v <= 168)) { toast('Enter hours from 0 to 168; 0 turns it off.'); return null; }
|
|
1465
|
+
return post('/api/browse/auto', { hours: v }, () => (v ? savedMark(hours) : toast.ok('Saved: automatic import is off.')));
|
|
1466
|
+
});
|
|
1467
|
+
return [
|
|
1468
|
+
h('div', { class: 'brow' }, h('div', { class: 't' }, h('div', { class: 'line1' }, h('span', { class: 'ttl', text: 'Last import' }),
|
|
1469
|
+
h('span', { class: 'val', text: ok ? daysAgo(at, true) : 'never', title: ok ? at.toLocaleString() : null }))),
|
|
1470
|
+
h('div', { class: 'acts' }, btn('Import new history now', () => importTicked(hist, 'browse')))),
|
|
1471
|
+
h('div', { class: 'field' }, h('label', { for: 'b-auto', text: 'Import new history automatically' }),
|
|
1472
|
+
h('div', { class: 'inline' }, h('span', { text: 'every' }), hours, h('span', { text: 'hours while Keepfold runs (0 = off)' })),
|
|
1473
|
+
h('p', { class: 'help', text: 'Browsers keep about 90 days of history; days not imported by then are gone.' })),
|
|
1474
|
+
s.auto_import_hours && login && login.supported && !login.exists
|
|
1475
|
+
? h('div', { class: 'brow' }, h('div', { class: 't' }, h('span', { class: 'sub', text: LOGIN_HINT })), h('div', { class: 'acts' }, loginBtn())) : null].filter(Boolean);
|
|
1476
|
+
}
|
|
1477
|
+
function historyRows(hist, from) {
|
|
1478
|
+
if (!hist || !hist.available) return [note('Not available in this version yet.')];
|
|
1479
|
+
const intro = h('p', { class: 'pad ink-2', text: 'Keepfold can read the history your browsers already keep, on this computer only, and turn it into private day pages. The first time can take a while. If the local model is on, it writes the day summaries; when its time budget runs out, later days get simple rule-made lines.' });
|
|
1480
|
+
if (!hist.sources.length) return [intro, note('No browser history found on this computer (looked for Comet, Chrome, Edge, Brave and Firefox).')];
|
|
1481
|
+
seedUntick(hist);
|
|
1482
|
+
const rows = hist.sources.map((s) => {
|
|
1483
|
+
const id = `h-${from}-${s.key.replace(/[^A-Za-z0-9]/g, '_')}`;
|
|
1484
|
+
const cb = h('input', { type: 'checkbox', id, checked: !untick.has(s.key) });
|
|
1485
|
+
cb.addEventListener('change', () => { if (cb.checked) untick.delete(s.key); else untick.add(s.key); });
|
|
1486
|
+
const counted = s.visits != null;
|
|
1487
|
+
const sub = s.error ? 'Could not be read; close that browser and scan again.'
|
|
1488
|
+
: !counted ? 'Not counted yet: Scan reads the counts only.'
|
|
1489
|
+
: s.first ? `From ${s.first} to ${s.last}. The privacy filter would leave out ${s.dropped} and keep ${s.private} private.` : 'No visits.';
|
|
1490
|
+
return h('div', { class: 'brow trow' }, cb, h('div', { class: 't' },
|
|
1491
|
+
h('div', { class: 'line1' }, h('label', { class: 'ttl', for: id, text: `${BROWSERS[s.browser] || s.browser} · ${s.profile}` }),
|
|
1492
|
+
counted ? h('span', { class: 'val', text: `${s.visits.toLocaleString()} visits` }) : null),
|
|
1493
|
+
h('span', { class: 'sub', text: sub })));
|
|
1494
|
+
});
|
|
1495
|
+
return [intro, ...rows, h('p', { class: 'help', text: 'Unticked profiles are also left out of the automatic imports.' }), h('div', { class: 'foot' }, h('div', { class: 'inline' },
|
|
1496
|
+
btn('Scan (counts only)', () => job('/api/browse/scan', { from })),
|
|
1497
|
+
btn('Import my past history', () => importTicked(hist, from), 'btn lit'),
|
|
1498
|
+
h('span', { class: 'sub', text: hist.imported ? `Last import ${hist.imported}.` : 'Never imported.' })))];
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
/* Add your history: one card per source; each export source opens a three-step guide */
|
|
1502
|
+
const CARDS = ['claude', 'chatgpt', 'gemini', 'perplexity', 'google-activity', 'notes', 'calendar', 'docs', 'repos', 'highlights', 'mail', 'selfchat', 'location', 'photos', 'spotify', 'voice-memos', 'anki', 'browser'];
|
|
1503
|
+
const CARD = {
|
|
1504
|
+
claude: 'Your claude.ai chats.', chatgpt: 'Your ChatGPT chats.', gemini: 'Your Gemini prompts, from Google Takeout.',
|
|
1505
|
+
perplexity: 'Perplexity threads, exported as Markdown.',
|
|
1506
|
+
'google-activity': 'Searches, YouTube and Chrome activity, from Google Takeout: My Activity, or YouTube\'s own watch and search history.',
|
|
1507
|
+
notes: 'An Obsidian vault, a Notion export or a folder of .md and .txt notes.',
|
|
1508
|
+
calendar: 'Your events, from an .ics calendar file.',
|
|
1509
|
+
docs: 'A folder of PDFs, Word documents and text files.',
|
|
1510
|
+
repos: 'Your own git projects: READMEs, languages and your commit messages, never the code.',
|
|
1511
|
+
highlights: 'Kindle clippings, a Readwise export or a Pocket list.',
|
|
1512
|
+
mail: 'The mail you sent, from an .mbox file: your own words, never addresses.',
|
|
1513
|
+
selfchat: 'Notes you sent yourself: a WhatsApp chat with yourself or Telegram Saved Messages.',
|
|
1514
|
+
location: 'Where you were: one city per day from your Google Timeline, never an address.',
|
|
1515
|
+
photos: 'When you took photos, and in which albums: dates and folder names only, never the images.',
|
|
1516
|
+
spotify: 'Your Spotify years: hours, top artists, tracks and podcasts; nothing per play.',
|
|
1517
|
+
'voice-memos': 'Your recordings, transcribed on this computer; the audio never leaves it.',
|
|
1518
|
+
anki: 'Your Anki decks: cards, reviews, how much you recall and the cards you keep forgetting.',
|
|
1519
|
+
browser: ['Browser history', 'The history your browsers keep on this computer.'],
|
|
1520
|
+
};
|
|
1521
|
+
const MAX_UPLOAD = 4 * 2 ** 30;
|
|
1522
|
+
let guide = null; // {source, step, upload, path, busy, wait, preview, tier, done, error}
|
|
1523
|
+
const guideSrc = () => ({ source: guide.source, ...(guide.upload ? { upload: guide.upload } : { path: guide.path }) });
|
|
1524
|
+
async function guided(path, wait, extra) {
|
|
1525
|
+
Object.assign(guide, { error: null, wait });
|
|
1526
|
+
try { await api(path, { ...guideSrc(), ...extra }); poll(); } catch (e) { Object.assign(guide, { wait: null, error: e.message }); }
|
|
1527
|
+
load('setup');
|
|
1528
|
+
}
|
|
1529
|
+
function check() {
|
|
1530
|
+
Object.assign(guide, { step: 3, preview: null, done: null });
|
|
1531
|
+
return guided('/api/import/preview', 'preview');
|
|
1532
|
+
}
|
|
1533
|
+
const mb = (n) => (n / 2 ** 20).toFixed(1);
|
|
1534
|
+
const sentText = (s) => `${Math.floor(100 * s.loaded / (s.total || 1))}% · ${mb(s.loaded)} of ${mb(s.total)} MB`;
|
|
1535
|
+
// XHR, not fetch: only XHR reports upload progress. Updates the bar in place, not by re-rendering.
|
|
1536
|
+
function sendFile(f) {
|
|
1537
|
+
return new Promise((resolve, reject) => {
|
|
1538
|
+
const x = new XMLHttpRequest();
|
|
1539
|
+
x.open('POST', '/api/import/upload');
|
|
1540
|
+
x.setRequestHeader('X-Keepfold-Token', T);
|
|
1541
|
+
x.setRequestHeader('Content-Type', 'application/octet-stream');
|
|
1542
|
+
x.setRequestHeader('X-Keepfold-Name', encodeURIComponent(f.name));
|
|
1543
|
+
x.upload.onprogress = (e) => {
|
|
1544
|
+
if (!e.lengthComputable || !guide.sent) return;
|
|
1545
|
+
guide.sent.loaded = e.loaded;
|
|
1546
|
+
const bar = $('up-bar'), txt = $('up-text');
|
|
1547
|
+
if (bar) bar.value = e.loaded;
|
|
1548
|
+
if (txt) txt.textContent = sentText(guide.sent);
|
|
1549
|
+
};
|
|
1550
|
+
x.onload = () => resolve(x);
|
|
1551
|
+
x.onerror = () => reject(new TypeError('Failed to fetch')); // the message fetch gave
|
|
1552
|
+
x.send(f);
|
|
1553
|
+
});
|
|
1554
|
+
}
|
|
1555
|
+
async function upload(f) {
|
|
1556
|
+
if (f.size > MAX_UPLOAD) { guide.error = 'The file is larger than 4 GB; unzip it and paste the path of the file inside instead.'; load('setup'); return; }
|
|
1557
|
+
Object.assign(guide, { busy: `Adding ${f.name}…`, error: null, sent: { loaded: 0, total: f.size } });
|
|
1558
|
+
load('setup');
|
|
1559
|
+
try {
|
|
1560
|
+
const x = await sendFile(f);
|
|
1561
|
+
let data = {};
|
|
1562
|
+
try { data = JSON.parse(x.responseText); } catch (e) { /* no body */ }
|
|
1563
|
+
if (x.status < 200 || x.status > 299) throw new Error(data.error || `The app answered ${x.status}.`);
|
|
1564
|
+
Object.assign(guide, { upload: data.upload, path: null, busy: null, sent: null });
|
|
1565
|
+
check();
|
|
1566
|
+
} catch (e) { Object.assign(guide, { busy: null, sent: null, error: e.message }); load('setup'); }
|
|
1567
|
+
}
|
|
1568
|
+
// a file dropped beside the drop zone must not open in this tab
|
|
1569
|
+
window.addEventListener('dragover', (e) => e.preventDefault());
|
|
1570
|
+
window.addEventListener('drop', (e) => e.preventDefault());
|
|
1571
|
+
|
|
1572
|
+
function guidePanel(d, id) {
|
|
1573
|
+
if (id === 'browser') return historyRows(d.history, 'setup');
|
|
1574
|
+
const g = d.guides[id], s = guide.step;
|
|
1575
|
+
const back = (to) => btn('Back', () => { Object.assign(guide, { step: to, error: null }); load('setup'); });
|
|
1576
|
+
const steps = h('div', { class: 'gsteps' }, ['Get your export', 'Add it', 'Check and import'].map((t, i) =>
|
|
1577
|
+
h('span', { class: i + 1 === s ? 'on' : i + 1 < s ? 'done' : null, 'aria-current': i + 1 === s ? 'step' : null, text: `${i + 1}. ${t}` })));
|
|
1578
|
+
const err = guide.error ? row('That did not work', null, guide.error, null, 'gerr') : null;
|
|
1579
|
+
if (s === 1) {
|
|
1580
|
+
return [steps, h('ol', { class: 'how' }, g.steps.map((t) => h('li', { text: t }))),
|
|
1581
|
+
h('p', { class: 'help' }, g.link ? [ext(g.link, `Open ${new URL(g.link).hostname}`), ' · '] : null, `Typical wait: ${g.wait}.`),
|
|
1582
|
+
h('p', { class: 'help', text: `The file to pick: ${g.pick}.` }),
|
|
1583
|
+
h('div', { class: 'inline' }, btn('I have the file', () => { guide.step = 2; load('setup'); }, 'btn lit'))];
|
|
1584
|
+
}
|
|
1585
|
+
if (s === 2) {
|
|
1586
|
+
const file = h('input', { type: 'file', id: 'imp-file', accept: '.zip,.json,.html,.md,.txt,.ics,.csv,.pdf,.docx,.mbox,.apkg,.colpkg', disabled: !!guide.busy });
|
|
1587
|
+
file.addEventListener('change', () => { if (file.files[0]) upload(file.files[0]); });
|
|
1588
|
+
const drop = h('div', { class: 'drop' }, h('strong', { text: guide.busy || 'Drop the file here' }),
|
|
1589
|
+
guide.busy && guide.sent ? [h('progress', { id: 'up-bar', max: guide.sent.total || 1, value: guide.sent.loaded, 'aria-label': 'Upload progress' }),
|
|
1590
|
+
h('span', { id: 'up-text', class: 'sub', text: sentText(guide.sent) })] : null,
|
|
1591
|
+
h('label', { class: 'check', for: 'imp-file' }, h('span', { text: 'or choose it:' })), file);
|
|
1592
|
+
drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('over'); });
|
|
1593
|
+
drop.addEventListener('dragleave', () => drop.classList.remove('over'));
|
|
1594
|
+
drop.addEventListener('drop', (e) => { e.preventDefault(); drop.classList.remove('over'); if (!guide.busy && e.dataTransfer.files[0]) upload(e.dataTransfer.files[0]); });
|
|
1595
|
+
const path = h('input', { type: 'text', id: 'imp-path', spellcheck: 'false', placeholder: 'C:\\Users\\you\\Downloads\\export.zip', value: guide.path || '' });
|
|
1596
|
+
const usePath = () => {
|
|
1597
|
+
if (!path.value.trim()) { toast('Paste the path first.'); return; }
|
|
1598
|
+
Object.assign(guide, { upload: null, path: path.value });
|
|
1599
|
+
return check(); // busy until the check is posted: a second click is ignored
|
|
1600
|
+
};
|
|
1601
|
+
return [steps, err, drop,
|
|
1602
|
+
h('div', { class: 'field' }, h('label', { for: 'imp-path', text: 'Or paste its full path (a file or a folder)' }),
|
|
1603
|
+
h('div', { class: 'inline' }, path, btn('Check this file', usePath)),
|
|
1604
|
+
h('p', { class: 'help', text: 'Windows: hold Shift, right-click the file and choose Copy as path. macOS: select the file in Finder and press Option-Command-C.' })),
|
|
1605
|
+
h('div', { class: 'inline' }, back(1))];
|
|
1606
|
+
}
|
|
1607
|
+
const p = guide.preview, done = guide.done, again = done && done.result && done.result.need;
|
|
1608
|
+
const out = [steps, err];
|
|
1609
|
+
if (guide.error) out.push(h('div', { class: 'inline' }, back(2)));
|
|
1610
|
+
else if (!p) out.push(note('Checking the file…'));
|
|
1611
|
+
else {
|
|
1612
|
+
out.push(h('div', {}, p.lines.map((t) => h('p', { class: 'gfound', text: t })), p.note ? h('p', { class: 'help', text: p.note }) : null));
|
|
1613
|
+
if (p.need === 'embed') { // said at Check, before any Import (R3-3)
|
|
1614
|
+
out.push(h('div', { class: 'inline' }, btn('Download the search model', () => job('/api/setup/embed', {}), 'btn lit'),
|
|
1615
|
+
btn('Check again', check), back(2)));
|
|
1616
|
+
} else if (p.need === 'voice') { // installed only on this click (keepfold model download --voice)
|
|
1617
|
+
out.push(h('div', { class: 'inline' }, btn('Install', () => job('/api/setup/voice', {}), 'btn lit'),
|
|
1618
|
+
btn('Check again', check), back(2)));
|
|
1619
|
+
} else if (!done || again) {
|
|
1620
|
+
// C2: notes and calendars ask who may read the pages before Import (last choice preselected)
|
|
1621
|
+
const tier = p.tier ? h('select', { id: 'imp-tier', 'aria-label': `${g.name}: who may read it` },
|
|
1622
|
+
Object.entries(AUDIENCE).map(([v, t]) => h('option', { value: v, text: t }))) : null;
|
|
1623
|
+
if (tier) {
|
|
1624
|
+
tier.value = guide.tier || p.tier;
|
|
1625
|
+
tier.addEventListener('change', () => { guide.tier = tier.value; });
|
|
1626
|
+
out.push(row('Who may read these pages', null, null, [tier]));
|
|
1627
|
+
}
|
|
1628
|
+
out.push(h('div', { class: 'inline' }, btn('Import', () => guided('/api/import/run', 'import', tier ? { tier: tier.value } : {}), 'btn lit', { disabled: !!guide.wait || !p.found }),
|
|
1629
|
+
guide.wait ? h('span', { class: 'sub', text: 'Importing; the progress shows at the top.' }) : back(2)));
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
if (done) {
|
|
1633
|
+
out.push(...resultNodes(done));
|
|
1634
|
+
if (!again) out.push(h('div', { class: 'inline' }, btn('Done', () => { guide = null; load('setup'); }, 'btn lit')));
|
|
1635
|
+
}
|
|
1636
|
+
return out;
|
|
1637
|
+
}
|
|
1638
|
+
function historyBoard(d) {
|
|
1639
|
+
const hi = d.history, out = [note('Bring in what you already have, one source at a time. Each guide shows how to get the file, then checks it before anything is imported.')];
|
|
1640
|
+
for (const id of CARDS) {
|
|
1641
|
+
const imp = d.imports[id], open = !!guide && guide.source === id;
|
|
1642
|
+
const [name, blurb] = d.guides[id] ? [d.guides[id].name, CARD[id]] : CARD[id];
|
|
1643
|
+
const stat = imp ? (imp.count ? `imported ${imp.count.toLocaleString()} on ${imp.when.slice(0, 10)}` : 'not yet')
|
|
1644
|
+
: id === 'browser' || id === 'google-activity' ? (hi.imported ? `browsing last imported ${hi.imported.slice(0, 10)}` : 'not yet') : '';
|
|
1645
|
+
out.push(row(name, stat, blurb, [btn(open ? 'Close' : 'Start', () => {
|
|
1646
|
+
guide = open ? null : { source: id, step: 1 };
|
|
1647
|
+
opened.add('history'); // stays open when an import marks the step done
|
|
1648
|
+
load('setup');
|
|
1649
|
+
}, 'btn', { 'aria-expanded': open ? 'true' : 'false', 'aria-label': `${open ? 'Close' : 'Start'}: ${name}` })]));
|
|
1650
|
+
if (open) out.push(h('div', { class: 'guide' }, ...guidePanel(d, id)));
|
|
1651
|
+
}
|
|
1652
|
+
if (d.watched) out.push(...watchedRows(d.watched));
|
|
1653
|
+
return out;
|
|
1654
|
+
}
|
|
1655
|
+
/* R18: watched folders (keepfold.watch); the app's periodic pass imports their new and changed files */
|
|
1656
|
+
const WATCH_KINDS = { docs: 'Documents', notes: 'Notes', repos: 'Code projects', calendar: 'Calendar', zotero: 'Zotero' };
|
|
1657
|
+
function watchedRows(wd) {
|
|
1658
|
+
const out = [row('Watched folders', wd.rows.length ? String(wd.rows.length) : 'none',
|
|
1659
|
+
'Keepfold imports the new and changed files in these folders by itself, every 10 minutes while the app runs; files it has read are not read again until they change.')];
|
|
1660
|
+
for (const w of wd.rows) {
|
|
1661
|
+
const last = w.missing ? 'Not found; kept, and checked again on the next pass.'
|
|
1662
|
+
: w.last ? `${w.last.at.replace('T', ' ').slice(0, 16)}: ${w.last.line}` : 'Not read yet: the first pass runs within 10 minutes.';
|
|
1663
|
+
out.push(row(w.path, `${WATCH_KINDS[w.source] || w.source} · ${AUDIENCE[w.tier] || w.tier}`, last,
|
|
1664
|
+
[btn('Stop watching', () => post('/api/import/watch/remove', { path: w.path }, () => load('setup')), 'btn', { 'aria-label': `Stop watching: ${w.path}` })]));
|
|
1665
|
+
}
|
|
1666
|
+
const path = h('input', { type: 'text', id: 'w-path', spellcheck: 'false', placeholder: 'C:\\Users\\you\\Documents\\Papers' });
|
|
1667
|
+
const kind = h('select', { id: 'w-source', 'aria-label': 'What the folder holds' },
|
|
1668
|
+
Object.entries(WATCH_KINDS).map(([v, t]) => h('option', { value: v, text: t })));
|
|
1669
|
+
const tier = h('select', { id: 'w-tier', 'aria-label': 'Who may read its pages' },
|
|
1670
|
+
Object.entries(AUDIENCE).map(([v, t]) => h('option', { value: v, text: t })));
|
|
1671
|
+
kind.value = 'docs';
|
|
1672
|
+
tier.value = wd.tiers.docs || 'cloud';
|
|
1673
|
+
kind.addEventListener('change', () => { tier.value = wd.tiers[kind.value] || 'cloud'; }); // each source's last choice
|
|
1674
|
+
const add = () => post('/api/import/watch/add', { path: path.value, source: kind.value, tier: tier.value },
|
|
1675
|
+
() => { toast.ok('Watching it: the first pass runs within 10 minutes.'); load('setup'); });
|
|
1676
|
+
out.push(h('div', { class: 'field' }, h('label', { for: 'w-path', text: 'Watch a folder (its full path)' }),
|
|
1677
|
+
h('div', { class: 'inline' }, path, kind, tier, btn('Watch', add, 'btn lit')),
|
|
1678
|
+
h('p', { class: 'help', text: 'For Zotero, leave the path empty to use the library on this computer, or paste its data folder.' })));
|
|
1679
|
+
return out;
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
/* Browsing */
|
|
1683
|
+
const CATEGORY_NAMES = { adult: 'Adult', health: 'Health', money: 'Money and banking', betting: 'Betting', dating: 'Dating', sexuality: 'Sexuality', drugs: 'Drugs', selfharm: 'Self-harm' };
|
|
1684
|
+
const AUDIENCE = { skip: 'Don\'t save', local: 'Local AI only', cloud: 'Cloud AI apps can read' };
|
|
1685
|
+
const PROVIDERS = { openai: 'OpenAI', openrouter: 'OpenRouter', gemini: 'Google Gemini', anthropic: 'Anthropic', custom: 'Custom (OpenAI-compatible)' };
|
|
1686
|
+
function cloudBoard(c) {
|
|
1687
|
+
const on = h('input', { type: 'checkbox', id: 'c-on', checked: c.cloud_processing });
|
|
1688
|
+
const prov = h('select', { id: 'c-provider' }, h('option', { value: '', text: 'Choose a provider' }),
|
|
1689
|
+
[...c.presets, 'custom'].map((p) => h('option', { value: p, text: PROVIDERS[p] || p })));
|
|
1690
|
+
prov.value = c.provider || '';
|
|
1691
|
+
const text = (id, value, placeholder) => h('input', { type: 'text', id, value: value || '', placeholder, spellcheck: 'false', autocomplete: 'off' });
|
|
1692
|
+
const model = text('c-model', c.model, 'e.g. gpt-4o-mini'), base = text('c-base', c.base_url, 'e.g. https://example.com/v1');
|
|
1693
|
+
const env = text('c-env', c.api_key_env, 'e.g. OPENAI_API_KEY');
|
|
1694
|
+
const baseField = h('div', { class: 'field', hidden: prov.value !== 'custom' }, h('label', { for: 'c-base', text: 'Base URL (https only)' }), base);
|
|
1695
|
+
prov.addEventListener('change', () => { baseField.hidden = prov.value !== 'custom'; });
|
|
1696
|
+
const save = () => post('/api/browse/cloud', {
|
|
1697
|
+
cloud_processing: on.checked, provider: prov.value, model: model.value.trim(),
|
|
1698
|
+
base_url: prov.value === 'custom' ? base.value.trim() : '', api_key_env: env.value.trim(),
|
|
1699
|
+
}, () => { toast.ok('Saved.'); load('browse'); });
|
|
1700
|
+
const name = c.api_key_env || 'NAME';
|
|
1701
|
+
const runs = c.runs.length ? h('div', { class: 'table-scroll' }, h('table', {},
|
|
1702
|
+
h('thead', {}, h('tr', {}, ['When', 'Provider', 'Model'].map((t) => h('th', { text: t })),
|
|
1703
|
+
['Requests', 'Characters', 'Skipped for a secret'].map((t) => h('th', { class: 'n', text: t })))),
|
|
1704
|
+
h('tbody', {}, c.runs.map((r) => h('tr', {}, h('td', { text: (r.ts || '').replace('T', ' ').replace('Z', ' UTC') }),
|
|
1705
|
+
h('td', { text: r.provider }), h('td', { text: r.model }),
|
|
1706
|
+
['items', 'chars', 'skipped'].map((k) => h('td', { class: 'n', text: String(r[k] ?? 0) })))))))
|
|
1707
|
+
: note('No cloud runs yet.');
|
|
1708
|
+
return [board('Cloud model', { btn: ['Save', save, { 'aria-label': 'Save: Cloud model' }], note: c.cloud_processing ? 'on' : 'off' },
|
|
1709
|
+
h('div', { class: 'field' }, h('label', { class: 'check' }, on, h('span', { text: 'Let a cloud model sort and summarise' })),
|
|
1710
|
+
h('p', { class: 'help', text: 'Off (the default). On: when Keepfold processes browsing, pages of categories set to Cloud AI apps can read (with that switch on) go to this cloud model for short descriptions. Local AI only pages never leave this computer and never fall back to the cloud. A request that looks like it holds a key or token is not sent, and each run sends at most 500 requests unless cloudllm.max_items in the config says otherwise.' })),
|
|
1711
|
+
h('div', { class: 'field' }, h('label', { for: 'c-provider', text: 'Provider' }), prov),
|
|
1712
|
+
baseField,
|
|
1713
|
+
h('div', { class: 'field' }, h('label', { for: 'c-model', text: 'Model' }), model),
|
|
1714
|
+
h('div', { class: 'field' }, h('label', { for: 'c-env', text: 'Name of the environment variable that holds your API key' }), env,
|
|
1715
|
+
h('p', { class: 'help', text: c.api_key_env ? `${c.api_key_env} is ${c.key_set ? 'set' : 'not set'} for this app.` : 'No variable named yet.' }),
|
|
1716
|
+
h('p', { class: 'help', text: `Keepfold never asks for the key itself and never stores it. Set the variable yourself as below, then click Quit (top right). ${REOPEN}` }),
|
|
1717
|
+
h('ol', { class: 'how' },
|
|
1718
|
+
h('li', {}, 'Windows: in PowerShell run ', h('code', { text: `setx ${name} "your-key"` }), ', then open a new terminal.'),
|
|
1719
|
+
h('li', {}, 'macOS: add ', h('code', { text: `export ${name}="your-key"` }), ' to ~/.zshrc, then open a new terminal.')))),
|
|
1720
|
+
board('Recent cloud runs', { note: 'counts only' }, runs)];
|
|
1721
|
+
}
|
|
1722
|
+
function renderBrowse(d) {
|
|
1723
|
+
if (d.available === false) { put('browse', board('Browsing', {}, note('Not available in this version yet.'))); return; }
|
|
1724
|
+
const s = d.settings || {};
|
|
1725
|
+
const parts = [];
|
|
1726
|
+
if (s.available !== false) {
|
|
1727
|
+
const vis = h('input', { type: 'checkbox', id: 'b-vis', checked: s.visible_to_claude });
|
|
1728
|
+
const local = h('input', { type: 'checkbox', id: 'b-local', checked: s.private_mcp });
|
|
1729
|
+
const cats = (s.categories || []).map((c) => {
|
|
1730
|
+
const sel = h('select', { id: 'b-aud-' + c, 'aria-label': `${CATEGORY_NAMES[c] || c}: who may read it` },
|
|
1731
|
+
Object.entries(AUDIENCE).map(([v, t]) => h('option', { value: v, text: t })));
|
|
1732
|
+
sel.value = (s.audience || {})[c] || 'local';
|
|
1733
|
+
return { c, sel };
|
|
1734
|
+
});
|
|
1735
|
+
const list = (id, label, help, items) => h('div', { class: 'field' }, h('label', { for: id, text: label }),
|
|
1736
|
+
h('textarea', { id, spellcheck: 'false', placeholder: 'example.com', value: (items || []).join('\n') }), h('p', { class: 'help', text: help }));
|
|
1737
|
+
const save = () => post('/api/browse/settings', {
|
|
1738
|
+
visible_to_claude: vis.checked, private_mcp: local.checked,
|
|
1739
|
+
audience: Object.fromEntries(cats.map((x) => [x.c, x.sel.value])),
|
|
1740
|
+
deny: $('b-deny').value, allow: $('b-allow').value, private: $('b-private').value,
|
|
1741
|
+
}, () => { toast.ok('Saved.'); load('browse'); });
|
|
1742
|
+
parts.push(board('Privacy', { btn: ['Save', save, { 'aria-label': 'Save: Privacy' }] },
|
|
1743
|
+
h('div', { class: 'field' }, h('label', { class: 'check' }, vis, h('span', { text: 'Cloud AI apps can read' })),
|
|
1744
|
+
h('p', { class: 'help', text: 'Off (the default): browsing goes only to private pages that Obsidian and local models read; no cloud AI app (Claude, Gemini, ChatGPT, Cursor…) sees it. On: Keepfold also writes pages that cloud AI apps read through Keepfold: your topics and time, interest lines in your journal, and the sites you visit with their page titles, the searches that led to them and the searches made on them. That covers all your browsing except the categories below set to Local AI only (or Don\'t save), which never reach a cloud AI app.' })),
|
|
1745
|
+
h('div', { class: 'field' }, h('span', { class: 'lbl', text: 'Sensitive categories' }),
|
|
1746
|
+
h('p', { class: 'help', text: 'Don\'t save: dropped before anything is stored. Local AI only: kept on your private pages; only models on this computer read them. Cloud AI apps can read: treated like the rest of your browsing, so cloud AI apps read its sites, page titles and searches while the switch above is on.' })),
|
|
1747
|
+
...cats.map((x) => row(CATEGORY_NAMES[x.c] || x.c, null, null, [x.sel])),
|
|
1748
|
+
h('div', { class: 'field' }, h('label', { class: 'check' }, local, h('span', { text: 'Local AI access (LM Studio only)' })),
|
|
1749
|
+
h('p', { class: 'help', text: 'Off (the default). On: Connect AI apps offers LM Studio a private search over all your browsing, private pages included. It runs only with a model on this computer; no other app is ever given it.' })),
|
|
1750
|
+
h('div', { class: 'field' }, h('span', { class: 'lbl', text: 'Domain lists' }),
|
|
1751
|
+
h('p', { class: 'help', text: 'One domain per line; a domain covers its subdomains.' })),
|
|
1752
|
+
h('div', { class: 'fields3' },
|
|
1753
|
+
list('b-deny', 'Never record', 'These sites are dropped before anything is stored.', s.deny),
|
|
1754
|
+
list('b-allow', 'Only record', 'When not empty, every other site is dropped.', s.allow),
|
|
1755
|
+
list('b-private', 'Private only', 'Kept, but only on your private pages.', s.private))));
|
|
1756
|
+
}
|
|
1757
|
+
const recv = board('Receiver', {},
|
|
1758
|
+
d.login.supported
|
|
1759
|
+
? row('Start at login', d.login.exists ? 'on' : 'off', 'The receiver imports new browser history in the background, with no window. This adds or removes its login entry (a Run entry on Windows, a LaunchAgent on macOS, a user service on Linux), only when you click. It runs:',
|
|
1760
|
+
[btn(d.login.exists ? 'Remove' : 'Add', () => job('/api/browse/login', { on: !d.login.exists }))])
|
|
1761
|
+
: row('Start at login', 'not on this system', 'Windows only: start the receiver from your login items instead.'),
|
|
1762
|
+
d.login.command ? h('div', { class: 'pad' }, h('pre', { text: d.login.command })) : null);
|
|
1763
|
+
const past = board('Past history', { note: d.history && d.history.imported ? `last import ${d.history.imported}` : 'never imported' },
|
|
1764
|
+
...autoImportRows(d.history, s, d.login), ...historyRows(d.history, 'browse'));
|
|
1765
|
+
const acts = board('Actions', { note: `processed ${d.last_processed || 'never'}` },
|
|
1766
|
+
row('Process now', null, 'Turns new browser history into your private day pages.', [btn('Process now', () => job('/api/browse/process', {}))]),
|
|
1767
|
+
row('Self-test', null, 'Runs the whole import on made-up history in a temp folder; your vault and browsers are not touched.', [btn('Run self-test', () => job('/api/browse/selftest', {}))]),
|
|
1768
|
+
row('Private pages', null, 'Your browsing pages are for you only: open them in Obsidian.', [btn('Open private folder in Obsidian', () => post('/api/open', { what: 'private' }, noObsidian))]));
|
|
1769
|
+
put('browse', ...parts, privateChatsBoard(), ...(d.cloud ? cloudBoard(d.cloud) : []), past, recv, acts);
|
|
1770
|
+
}
|
|
1771
|
+
// imported AI chats the import made private for a sensitive category (server.private_chats): titles, never chat text
|
|
1772
|
+
function privateChatsBoard() {
|
|
1773
|
+
const body = h('tbody', {}), box = h('div', {}, note('Loading…'));
|
|
1774
|
+
const more = btn('Show more', () => page(body.children.length), null, { 'aria-label': 'Show more: Chats kept private' });
|
|
1775
|
+
const page = async (at) => {
|
|
1776
|
+
try {
|
|
1777
|
+
const r = await api('/api/browse/private-chats?offset=' + at);
|
|
1778
|
+
if (!r.total) { box.replaceChildren(note('No imported chat was made private.')); return; }
|
|
1779
|
+
if (r.locked) { // titles only while the Private switch is open (the Home page's Windows Hello unlock)
|
|
1780
|
+
const cats = Object.entries(r.by_category || {}).map(([c, n]) => `${CATEGORY_NAMES[c] || c} ${n}`).join(', ');
|
|
1781
|
+
box.replaceChildren(row(`${r.total} chat${r.total === 1 ? '' : 's'} kept private${cats ? ` (${cats})` : ''}.`, null,
|
|
1782
|
+
'Unlock Private to see their titles.',
|
|
1783
|
+
[btn('Unlock Private', () => post('/api/home/unlock', {}, (u) => {
|
|
1784
|
+
if (u.unlocked) page(0); else toast(u.message || 'Private items stay hidden.', true);
|
|
1785
|
+
}))]));
|
|
1786
|
+
return;
|
|
1787
|
+
}
|
|
1788
|
+
body.append(...r.rows.map((c) => h('tr', {}, h('td', { text: c.title }), h('td', { text: c.app }),
|
|
1789
|
+
h('td', { text: c.date }), h('td', { text: CATEGORY_NAMES[c.category] || c.category }))));
|
|
1790
|
+
more.hidden = body.children.length >= r.total;
|
|
1791
|
+
if (!at) box.replaceChildren(h('div', { class: 'table-scroll' }, h('table', {},
|
|
1792
|
+
h('thead', {}, h('tr', {}, ['Chat', 'App', 'Date', 'Category'].map((t) => h('th', { text: t })))), body)),
|
|
1793
|
+
h('div', { class: 'pad' }, more));
|
|
1794
|
+
} catch (e) { if (!dead) box.replaceChildren(note(e.message)); }
|
|
1795
|
+
};
|
|
1796
|
+
page(0);
|
|
1797
|
+
return board('Chats kept private', { note: 'newest first' },
|
|
1798
|
+
note('Imported AI chats that Keepfold saved as private pages because they fall in a sensitive category set to Local AI only. Only models on this computer read them.'), box);
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/* Dashboard and vault */
|
|
1802
|
+
// Export snapshot: the desktop app asks where to save it (then a job writes it); the browser downloads it
|
|
1803
|
+
async function exportSnapshot() {
|
|
1804
|
+
const r = await post('/api/vault/export', {});
|
|
1805
|
+
if (!r || r.cancelled) return;
|
|
1806
|
+
if (r.job) { poll(); return; }
|
|
1807
|
+
try {
|
|
1808
|
+
const res = await fetch(r.download, { headers: { 'X-Keepfold-Token': T } });
|
|
1809
|
+
if (!res.ok) throw new Error(`The app answered ${res.status}.`);
|
|
1810
|
+
const name = /filename="([^"]+)"/.exec(res.headers.get('Content-Disposition') || '');
|
|
1811
|
+
const a = h('a', { href: URL.createObjectURL(await res.blob()), download: name ? name[1] : 'keepfold-snapshot.html' });
|
|
1812
|
+
document.body.append(a);
|
|
1813
|
+
a.click();
|
|
1814
|
+
a.remove();
|
|
1815
|
+
setTimeout(() => URL.revokeObjectURL(a.href), 60000);
|
|
1816
|
+
toast.ok('Snapshot saved to your downloads.');
|
|
1817
|
+
} catch (e) { toast.error(e.message); }
|
|
1818
|
+
}
|
|
1819
|
+
const noObsidian = (r) => { if (r.obsidian === false) toast('Obsidian is not installed, so it opened with this computer’s own app.', true); };
|
|
1820
|
+
// Change folder: the inline field in the Vault board (the same job Setup's Vault step runs)
|
|
1821
|
+
const vaultChange = { open: false, text: '', focus: false, d: null, reconnect: false };
|
|
1822
|
+
const RECONNECT = 'Your AI apps still use your old folder. Open Connect AI apps and click Apply to move them.';
|
|
1823
|
+
const VAULT_HELP = 'Keepfold adds its own folders and a git history there, and never changes notes you already have. Obsidian can open it as a vault. Your current vault stays where it is.';
|
|
1824
|
+
function openChange() { vaultChange.open = true; vaultChange.focus = true; renderVault(vaultChange.d); }
|
|
1825
|
+
function closeChange() { vaultChange.open = false; vaultChange.text = ''; renderVault(vaultChange.d); }
|
|
1826
|
+
function changeField() {
|
|
1827
|
+
const use = btn('Use this folder', () => job('/api/setup/vault', { path: path.value.trim() }), 'btn lit', { disabled: !vaultChange.text.trim() });
|
|
1828
|
+
const path = h('input', { type: 'text', id: 'vault-change-path', value: vaultChange.text, placeholder: 'C:\\Notes\\MyVault', 'aria-label': 'Use another folder for your notes', spellcheck: 'false' });
|
|
1829
|
+
path.addEventListener('input', () => { vaultChange.text = path.value; use.disabled = !path.value.trim(); });
|
|
1830
|
+
path.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !use.disabled) { e.preventDefault(); use.click(); } });
|
|
1831
|
+
const f = h('div', { class: 'field', id: 'vault-change' }, h('label', { for: 'vault-change-path', text: 'Use another folder for your notes' }),
|
|
1832
|
+
h('div', { class: 'inline' }, path, use, btn('Cancel', closeChange)),
|
|
1833
|
+
h('p', { class: 'help', text: VAULT_HELP }));
|
|
1834
|
+
f.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); closeChange(); } });
|
|
1835
|
+
if (vaultChange.focus) { vaultChange.focus = false; setTimeout(() => path.focus(), 0); }
|
|
1836
|
+
return f;
|
|
1837
|
+
}
|
|
1838
|
+
function renderVault(d) {
|
|
1839
|
+
vaultChange.d = d;
|
|
1840
|
+
if (!d.ok) {
|
|
1841
|
+
put('vault', board('Vault', {}, row('No vault yet', d.path || '', 'Set one up first.', [btn('Open Setup', () => show('setup', true))])));
|
|
1842
|
+
return;
|
|
1843
|
+
}
|
|
1844
|
+
put('vault', board('Vault', {},
|
|
1845
|
+
row('Folder', d.path, 'Your notes live here as Markdown files.', [btn('Open vault in Obsidian', () => post('/api/open', { what: 'vault' }, noObsidian)),
|
|
1846
|
+
btn('Open folder', () => post('/api/open', { what: 'folder' }), null, { 'aria-label': 'Open folder: Vault' }),
|
|
1847
|
+
btn('Change folder', openChange, null, { 'aria-label': 'Change folder: Vault', 'aria-expanded': String(vaultChange.open) })]),
|
|
1848
|
+
vaultChange.open ? changeField() : null,
|
|
1849
|
+
d.temp ? h('div', { class: 'brow srow' }, stateCell('warn'),
|
|
1850
|
+
h('div', { class: 't' }, h('div', { class: 'line1' }, h('span', { class: 'ttl', text: 'This vault is in a temporary folder' })),
|
|
1851
|
+
h('span', { class: 'sub', text: 'Windows can empty it at any time. Use Change folder to pick your real vault.' })),
|
|
1852
|
+
h('div', { class: 'acts' }, btn('Change folder', openChange, 'btn lit', { 'aria-label': 'Change folder: temporary vault' }))) : null,
|
|
1853
|
+
vaultChange.reconnect ? h('div', { class: 'brow srow' }, stateCell('warn'),
|
|
1854
|
+
h('div', { class: 't' }, h('div', { class: 'line1' }, h('span', { class: 'ttl', text: 'Your AI apps still use your old folder' })),
|
|
1855
|
+
h('span', { class: 'sub', text: 'Open Connect AI apps and click Apply to move them.' })),
|
|
1856
|
+
h('div', { class: 'acts' }, btn('Open Connect AI apps', () => show('connect', true), 'btn lit'))) : null,
|
|
1857
|
+
h('div', { class: 'brow' }, h('div', { class: 't' }, h('div', { class: 'line1' }, h('span', { class: 'ttl', text: 'Notes' })),
|
|
1858
|
+
h('span', { class: 'sub', text: `Last indexed ${d.last_index || 'not yet'}.` })), h('div', { class: 'acts' }, noteCount(d.notes))),
|
|
1859
|
+
row('Snapshot', null, 'One page of your notes and the 3D brain that opens without Keepfold. Private items are never in it.',
|
|
1860
|
+
[btn('Export snapshot', exportSnapshot)]),
|
|
1861
|
+
row('Backups', d.backups ? `${d.backups}, last ${d.last_backup}` : 'none yet', 'A zip of the whole vault in .keepfold/backups. Copy it to another drive now and then.',
|
|
1862
|
+
[btn('Back up vault', () => job('/api/vault/backup', {}))]),
|
|
1863
|
+
row('Health', null, 'Checks that Keepfold and your notes folder are working, and finds common problems.', [btn('Check for problems', () => job('/api/vault/doctor', {}))])),
|
|
1864
|
+
gitBoard(d.git || { enabled: true, private_browsing: false }));
|
|
1865
|
+
}
|
|
1866
|
+
function gitBoard(g) {
|
|
1867
|
+
const on = h('input', { type: 'checkbox', id: 'g-on', checked: g.enabled });
|
|
1868
|
+
const priv = h('input', { type: 'checkbox', id: 'g-private', checked: g.private_browsing, disabled: !g.enabled });
|
|
1869
|
+
on.addEventListener('change', () => { priv.disabled = !on.checked; });
|
|
1870
|
+
const save = () => post('/api/vault/git', { enabled: on.checked, private_browsing: priv.checked }, () => { toast.ok('Saved.'); load('vault'); });
|
|
1871
|
+
return board('History', { btn: ['Save', save, { 'aria-label': 'Save: History' }] },
|
|
1872
|
+
h('div', { class: 'field' }, h('label', { class: 'check' }, on, h('span', { text: 'Keep the vault’s history in git (lets you undo sessions; uses more disk as the vault grows)' })),
|
|
1873
|
+
h('p', { class: 'help', text: 'On (the default): each session is saved as a git commit you can undo. Off: no new history is kept and undo is off; history already there is left as it is.' })),
|
|
1874
|
+
h('div', { class: 'field' }, h('label', { class: 'check' }, priv, h('span', { text: 'Include private browsing pages in git history' })),
|
|
1875
|
+
h('p', { class: 'help', text: 'Off (the default): private browsing pages stay out of git. On: they are saved in the history with everything else, so undo covers them and deleting one later leaves a copy in old commits.' })));
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
/* Review (plans 5a, 5b): what waits for the user's own click. One quiet count in the nav, no
|
|
1879
|
+
popups. Every text is the server's shown text, set with textContent. */
|
|
1880
|
+
function badge(n) {
|
|
1881
|
+
const k = Number(n) > 0 ? Number(n) : 0, b = $('review-badge'), o = $('review-option');
|
|
1882
|
+
const was = b.textContent;
|
|
1883
|
+
b.textContent = k ? String(k) : '';
|
|
1884
|
+
if (k && was && was !== String(k)) crossFade(b, was);
|
|
1885
|
+
b.hidden = !k;
|
|
1886
|
+
b.setAttribute('aria-label', `${k} waiting`);
|
|
1887
|
+
if (o) o.textContent = k ? `Review (${k})` : 'Review';
|
|
1888
|
+
}
|
|
1889
|
+
const PAGE = { 'teaching-contract': 'Teaching rule', preferences: 'Preferences', personality: 'Personality',
|
|
1890
|
+
goals: 'Goals', profile: 'Profile', voice: 'Voice', portrait: 'Portrait', core: 'Core',
|
|
1891
|
+
setup: 'Setup' };
|
|
1892
|
+
/* R3-4: every Review row is a card. J/K move focus between cards (a roving tabindex), and on
|
|
1893
|
+
the focused card Y approves, N dismisses, R retires and S skips; never while typing. */
|
|
1894
|
+
let lastReview = null, reviewAt = -1, reviewBusy = false, reviewMoreOpen = false;
|
|
1895
|
+
const reviewSkipped = new Set(); // cards skipped with S: out of Today's 5 until the page reloads
|
|
1896
|
+
function card(title, value, sub, acts, keys, id) {
|
|
1897
|
+
// keys: {y|n|r: [button, function]}; each key's button says its shortcut
|
|
1898
|
+
const r = row(title, value, sub, acts);
|
|
1899
|
+
r.classList.add('rcard');
|
|
1900
|
+
r.setAttribute('role', 'group');
|
|
1901
|
+
r.setAttribute('aria-label', title);
|
|
1902
|
+
r.setAttribute('tabindex', '-1');
|
|
1903
|
+
r.keys = {};
|
|
1904
|
+
for (const [k, [b, fn]] of Object.entries(keys || {})) {
|
|
1905
|
+
b.setAttribute('aria-keyshortcuts', k.toUpperCase());
|
|
1906
|
+
r.keys[k] = fn;
|
|
1907
|
+
}
|
|
1908
|
+
r.skipId = id || null;
|
|
1909
|
+
return r;
|
|
1910
|
+
}
|
|
1911
|
+
function cardOf(e) {
|
|
1912
|
+
for (; e && e !== document.body; e = e.parentNode) if (e.keys) return e;
|
|
1913
|
+
return null;
|
|
1914
|
+
}
|
|
1915
|
+
function focusCard(cards, i) {
|
|
1916
|
+
if (!cards.length) return;
|
|
1917
|
+
const k = Math.max(0, Math.min(i, cards.length - 1));
|
|
1918
|
+
cards.forEach((c, j) => c.setAttribute('tabindex', j === k ? '0' : '-1'));
|
|
1919
|
+
cards[k].focus();
|
|
1920
|
+
}
|
|
1921
|
+
// the sections whose cards answer the keys (Tonight shows Review's Today's 5) and their redraw
|
|
1922
|
+
const CARD_PAGES = { review: () => renderReview(lastReview), tonight: () => renderTonight(lastTonight) };
|
|
1923
|
+
function reviewKey(e) {
|
|
1924
|
+
if (!CARD_PAGES[current] || e.ctrlKey || e.metaKey || e.altKey || reviewBusy) return;
|
|
1925
|
+
const t = e.target || {}, tag = String(t.tagName || '').toUpperCase();
|
|
1926
|
+
if (['INPUT', 'TEXTAREA', 'SELECT'].includes(tag) || t.isContentEditable) return;
|
|
1927
|
+
const k = String(e.key || '').toLowerCase();
|
|
1928
|
+
if (!['j', 'k', 'y', 'n', 'r', 's'].includes(k)) return;
|
|
1929
|
+
const cards = [...$(current).querySelectorAll('.rcard')], at = cards.indexOf(cardOf(document.activeElement));
|
|
1930
|
+
if (k === 'j' || k === 'k') {
|
|
1931
|
+
e.preventDefault();
|
|
1932
|
+
focusCard(cards, at < 0 ? 0 : at + (k === 'j' ? 1 : -1));
|
|
1933
|
+
return;
|
|
1934
|
+
}
|
|
1935
|
+
if (at < 0) return;
|
|
1936
|
+
const c = cards[at];
|
|
1937
|
+
if (k === 's') {
|
|
1938
|
+
e.preventDefault();
|
|
1939
|
+
if (c.skipId) {
|
|
1940
|
+
reviewSkipped.add(c.skipId);
|
|
1941
|
+
reviewAt = at;
|
|
1942
|
+
CARD_PAGES[current]();
|
|
1943
|
+
} else focusCard(cards, at + 1);
|
|
1944
|
+
return;
|
|
1945
|
+
}
|
|
1946
|
+
if (!c.keys[k]) return;
|
|
1947
|
+
e.preventDefault();
|
|
1948
|
+
reviewAt = at;
|
|
1949
|
+
reviewBusy = true;
|
|
1950
|
+
Promise.resolve(c.keys[k]()).then(() => { reviewBusy = false; }, () => { reviewBusy = false; });
|
|
1951
|
+
}
|
|
1952
|
+
addEventListener('keydown', reviewKey);
|
|
1953
|
+
const list = (rows, empty) => (rows.length ? rows : [note(empty)]);
|
|
1954
|
+
// Review's card makers, shared with Tonight; `act(path, body, said)` posts a click and redraws
|
|
1955
|
+
function reviewCards(act) {
|
|
1956
|
+
const where = (x) => (PAGE[x.page] || x.page) + (x.section ? ` · ${x.section}` : '');
|
|
1957
|
+
const two = (y, n) => ({ y, n }); // [button, function] for Y and N
|
|
1958
|
+
const kb = (text, fn, cls, label) => { const b = btn(text, fn, cls, { 'aria-label': label }); return [b, fn]; };
|
|
1959
|
+
// UX-B: a muted line under a card's text naming up to 3 pages linked with its page (the
|
|
1960
|
+
// server's `related`), each opening the page in Obsidian; no line when there are none
|
|
1961
|
+
const rel = (el, x) => {
|
|
1962
|
+
const r = x.related || [];
|
|
1963
|
+
if (r.length) el.querySelector('.t').append(h('span', { class: 'sub related' }, 'Related: ',
|
|
1964
|
+
...r.flatMap((p, i) => [i ? ', ' : '', btn(p.title, () => post('/api/open', { what: 'page', path: p.path }), 'linkbtn', { 'aria-label': `Open in Obsidian: ${p.title}` })])));
|
|
1965
|
+
return el;
|
|
1966
|
+
};
|
|
1967
|
+
const pendingCard = (p, id) => {
|
|
1968
|
+
const y = kb('Approve', () => act('/api/review/approve', { key: p.key }, 'Approved.'), 'btn lit', `Approve: ${p.text}`);
|
|
1969
|
+
const n = kb('Dismiss', () => act('/api/review/dismiss', { key: p.key }, 'Dismissed. It will not be suggested again.'), null, `Dismiss: ${p.text}`);
|
|
1970
|
+
return rel(card(p.text, where(p), p.since ? `Suggested ${p.since}` : null, [y[0], n[0]], two(y, n), id), p);
|
|
1971
|
+
};
|
|
1972
|
+
const conflictCard = (c, id) => {
|
|
1973
|
+
const both = kb('Keep both', () => act('/api/review/conflict', { key: c.key, keep: 'both' }, 'Kept both.'), null, `Keep both: ${c.left.text} and ${c.right.text}`);
|
|
1974
|
+
const left = kb('Keep first', () => act('/api/review/conflict', { key: c.key, keep: 'left' }, 'Kept one; the other is retired.'), null, `Keep only: ${c.left.text}`);
|
|
1975
|
+
const right = kb('Keep second', () => act('/api/review/conflict', { key: c.key, keep: 'right' }, 'Kept one; the other is retired.'), null, `Keep only: ${c.right.text}`);
|
|
1976
|
+
// a recorded pair's right line is the newer one: Y takes it; N keeps both (G7's near-duplicates too)
|
|
1977
|
+
const keys = c.why === 'opposite' || c.why === 'same' || c.why === 'maybe_opposite' ? { n: both } : { y: right, n: both };
|
|
1978
|
+
return card(c.left.text, where(c.left), `or: ${c.right.text} (${where(c.right)})`, [both[0], left[0], right[0]], keys, id);
|
|
1979
|
+
};
|
|
1980
|
+
const ruleCard = (x, id) => {
|
|
1981
|
+
const y = kb('Approve', () => act('/api/review/rule/approve', { key: x.key }, x.page === 'core' ? 'Added to your core lines.' : 'Added to your preferences.'), 'btn lit', `Approve: ${x.text}`);
|
|
1982
|
+
const n = kb('Dismiss', () => act('/api/review/rule/dismiss', { key: x.key }, 'Dismissed. It will not be suggested again.'), null, `Dismiss: ${x.text}`);
|
|
1983
|
+
return rel(card(`You told ${x.chats} chats: ${x.text}`, x.page === 'core' ? 'Core' : 'Preferences', null, [y[0], n[0]], two(y, n), id), x);
|
|
1984
|
+
};
|
|
1985
|
+
const retire = (x) => kb('Retire', () => act('/api/review/retire', { id: x.id }, 'Retired.'), null, `Retire: ${x.text}`);
|
|
1986
|
+
// G6: a line AI apps are not given until Keep it; Keep it out retires it to ## Past
|
|
1987
|
+
const unsafeCard = (x, id) => {
|
|
1988
|
+
const r = kb('Keep it out', () => act('/api/review/retire', { id: x.id }, 'Kept out: the line moved to Past.'), null, `Keep it out: ${x.text}`);
|
|
1989
|
+
const y = kb('Keep it', () => act('/api/review/unsafe/keep', { key: x.key }, 'Kept. AI apps get the line again.'), null, `Keep it: ${x.text}`);
|
|
1990
|
+
// G5b-6: a command to run that an AI app wrote
|
|
1991
|
+
const said = x.command ? `An AI app wrote this line in me/${x.page}, and it holds a command to run: ${x.what}. AI apps don't get it until you keep it.`
|
|
1992
|
+
: `This line in me/${x.page} ${x.invisible ? 'holds invisible characters' : 'looks like an instruction to an AI'}: ${x.what}. Keep it out, or Keep it.`;
|
|
1993
|
+
return rel(card(x.text, said, null, [r[0], y[0]], { r, y }, id), x);
|
|
1994
|
+
};
|
|
1995
|
+
// R5a: a line on me/core, me/setup or the teaching contract Keepfold did not write; AI apps get it only after Keep
|
|
1996
|
+
const outsideCard = (x, id) => {
|
|
1997
|
+
const y = kb('Keep', () => act('/api/review/outside/keep', { key: x.key }, 'Kept. AI apps get the line from now on.'), null, `Keep: ${x.text}`);
|
|
1998
|
+
const r = kb('Remove', () => act('/api/review/outside/remove', { key: x.key }, 'Removed. AI apps do not get it.'), null, `Remove: ${x.text}`);
|
|
1999
|
+
return rel(card(x.text, `Changed outside Keepfold: keep? me/${x.page}` + (x.section ? ` · ${x.section}` : ''), 'AI apps do not get this line until you keep it.', [y[0], r[0]], { y, r }, id), x);
|
|
2000
|
+
};
|
|
2001
|
+
return { where, two, kb, rel, pendingCard, conflictCard, ruleCard, retire, unsafeCard, outsideCard };
|
|
2002
|
+
}
|
|
2003
|
+
// R3-4's Today's 5 board (Review and Tonight): the view's `today` keys as cards, skips left out;
|
|
2004
|
+
// D4: once none is left, the board says Done for today
|
|
2005
|
+
function todayBoard(d, m) {
|
|
2006
|
+
const find = { pending: d.pending || [], conflict: d.conflicts || [], rule: d.rules || [], unsafe: d.unsafe || [], outside: d.outside || [] };
|
|
2007
|
+
const make = { pending: m.pendingCard, conflict: m.conflictCard, rule: m.ruleCard, unsafe: m.unsafeCard, outside: m.outsideCard };
|
|
2008
|
+
const today = (d.today || []).filter((t) => !reviewSkipped.has(`${t.type}:${t.key}`)).map((t) => {
|
|
2009
|
+
const x = (find[t.type] || []).find((y) => y.key === t.key);
|
|
2010
|
+
return x ? make[t.type](x, `${t.type}:${t.key}`) : null;
|
|
2011
|
+
}).filter(Boolean);
|
|
2012
|
+
if (!today.length) return board('Done for today', { note: '0' }, note('Nothing else needs you. Keepfold saves and tidies the rest itself.'));
|
|
2013
|
+
return board('Today’s 5', { note: String(today.length) },
|
|
2014
|
+
h('p', { class: 'help pad', text: 'Keys: J and K move between cards, Y approve, N dismiss, R retire, S skip.' }),
|
|
2015
|
+
...today);
|
|
2016
|
+
}
|
|
2017
|
+
// after a key's action or a skip, focus stays at the same place among section `s`'s cards
|
|
2018
|
+
function cardsDrawn(s) {
|
|
2019
|
+
const cards = [...$(s).querySelectorAll('.rcard')];
|
|
2020
|
+
if (reviewAt >= 0) {
|
|
2021
|
+
const at = reviewAt;
|
|
2022
|
+
reviewAt = -1;
|
|
2023
|
+
focusCard(cards, at);
|
|
2024
|
+
} else if (cards.length && !cards.some((c) => c.getAttribute('tabindex') === '0')) cards[0].setAttribute('tabindex', '0');
|
|
2025
|
+
}
|
|
2026
|
+
function renderReview(d) {
|
|
2027
|
+
lastReview = d;
|
|
2028
|
+
badge(d.count);
|
|
2029
|
+
const act = (path, body, said) => post(path, body, (r) => { renderReview(r); toast.ok(said); });
|
|
2030
|
+
const m = reviewCards(act);
|
|
2031
|
+
const { where, two, kb, rel, pendingCard, conflictCard, ruleCard, retire, unsafeCard, outsideCard } = m;
|
|
2032
|
+
// D4: every board but Today's 5 sits folded under one section, closed until opened; the fold
|
|
2033
|
+
// leaves out the cards Today's 5 shows above and counts only what it holds
|
|
2034
|
+
const above = new Set((d.today || []).map((t) => `${t.type}:${t.key}`).filter((k) => !reviewSkipped.has(k)));
|
|
2035
|
+
const rest = (type, rows) => (rows || []).filter((x) => !above.has(`${type}:${x.key}`));
|
|
2036
|
+
const pending = rest('pending', d.pending), pairs = rest('conflict', d.conflicts), rules = rest('rule', d.rules), unsafe = rest('unsafe', d.unsafe), outside = rest('outside', d.outside);
|
|
2037
|
+
const folded = (d.more || 0) - [[d.pending, pending], [d.conflicts, pairs], [d.rules, rules], [d.unsafe, unsafe], [d.outside, outside]]
|
|
2038
|
+
.reduce((n, [all, left]) => n + (all || []).length - left.length, 0);
|
|
2039
|
+
const allRules = rules.length > 1 ? ['Approve all', () => act('/api/review/rule/approve-all', { keys: rules.map((x) => x.key) }, 'Added to your lines.'),
|
|
2040
|
+
{ 'aria-label': `Approve all ${rules.length} repeated corrections` }] : null;
|
|
2041
|
+
const more = h('details', { class: 'review-more', open: reviewMoreOpen },
|
|
2042
|
+
h('summary', { text: `More, only if you want (${folded})` }));
|
|
2043
|
+
more.addEventListener('toggle', () => { reviewMoreOpen = more.open; });
|
|
2044
|
+
more.append(
|
|
2045
|
+
board('Waiting for your approval', { note: String(pending.length) }, ...list(pending.map((p) => pendingCard(p)),
|
|
2046
|
+
'Nothing is waiting.')),
|
|
2047
|
+
board('Past their end date', { note: String(d.expired.length) }, ...list(d.expired.map((x) => {
|
|
2048
|
+
const r = retire(x);
|
|
2049
|
+
return rel(card(x.text, where(x), `Ended ${x.until}`, [r[0]], { r }), x);
|
|
2050
|
+
}), 'No line is past its end date.')),
|
|
2051
|
+
board('Still true?', { note: String(d.stale.length) }, ...list(d.stale.map((x) => {
|
|
2052
|
+
const y = kb('Still true', () => act('/api/review/still', { id: x.id }, 'Kept.'), 'btn lit', `Still true: ${x.text}`), r = retire(x);
|
|
2053
|
+
return rel(card(x.text, where(x), `Last confirmed ${x.since}`, [y[0], r[0]], { y, r }), x);
|
|
2054
|
+
}), 'Nothing to check this month.')),
|
|
2055
|
+
// G7: lines the X-ray shows cut for space in most primes (Keep pins them), and playbooks no AI app was served
|
|
2056
|
+
board('Rarely reach your apps: still worth keeping?', { note: String((d.crowded || []).length) }, ...list((d.crowded || []).filter((x) => !reviewSkipped.has(`crowded:${x.id}`)).map((x) => {
|
|
2057
|
+
const id = `crowded:${x.id}`;
|
|
2058
|
+
const y = kb('Keep', () => act('/api/review/crowded/keep', { id: x.id }, 'Kept and pinned: AI apps get it first.'), 'btn lit', `Keep and pin: ${x.text}`), r = retire(x);
|
|
2059
|
+
const s = btn('Skip', () => { reviewSkipped.add(id); renderReview(lastReview); }, null, { 'aria-label': `Skip: ${x.text}`, 'aria-keyshortcuts': 'S' });
|
|
2060
|
+
return rel(card(x.text, where(x), `Cut for space in ${x.cut} of the ${x.seen} primes that offered it, in the last ${x.window} primes`, [y[0], r[0], s], { y, r }, id), x);
|
|
2061
|
+
}), 'No line is crowded out.')),
|
|
2062
|
+
board('Still how you do this?', { note: String((d.unused || []).length) }, ...list((d.unused || []).filter((x) => !reviewSkipped.has(`unused:${x.id}`)).map((x) => {
|
|
2063
|
+
const y = kb('Keep', () => act('/api/review/playbook/keep', { id: x.id }, 'Kept. Asked again in 60 days.'), 'btn lit', `Keep: ${x.title}`);
|
|
2064
|
+
const o = btn('Open', () => post('/api/open', { what: 'page', path: x.path }), null, { 'aria-label': `Open in Obsidian: ${x.title}` });
|
|
2065
|
+
return card(x.title, 'Playbook', `No AI app was served it in the last ${x.calls} calls Keepfold keeps` + (x.since ? ` (since ${x.since})` : '') + `; last changed ${x.changed}`, [y[0], o], { y }, `unused:${x.id}`);
|
|
2066
|
+
}), 'Every playbook reached an AI app lately.')),
|
|
2067
|
+
// R28a: a preferences line that keeps coming back, offered for Core (one a month at most)
|
|
2068
|
+
...(d.promote || []).filter((x) => !reviewSkipped.has(`promote:${x.id}`)).map((x) => board('You keep coming back to this. Pin it to Core?', { note: '1' }, (() => {
|
|
2069
|
+
const y = kb('Pin to Core', () => act('/api/review/promote/pin', { id: x.id }, 'Added to your core lines.'), 'btn lit', `Pin to Core: ${x.text}`);
|
|
2070
|
+
const n = kb('Not now', () => act('/api/review/promote/later', { id: x.id }, 'Not asked again for 6 months.'), null, `Not now: ${x.text}`);
|
|
2071
|
+
return rel(card(x.text, where(x), null, [y[0], n[0]], two(y, n), `promote:${x.id}`), x);
|
|
2072
|
+
})())),
|
|
2073
|
+
board('Lines that may conflict', { note: String(pairs.length) }, ...list(pairs.map((c) => conflictCard(c)),
|
|
2074
|
+
'No lines seem to conflict.')),
|
|
2075
|
+
board('Corrections you repeat', { note: String(rules.length), btn: allRules }, ...list(rules.map((x) => ruleCard(x)),
|
|
2076
|
+
'No repeated corrections found.')),
|
|
2077
|
+
board('Decisions in your commits', { note: String((d.decisions || []).length) }, ...list((d.decisions || []).map((x) => {
|
|
2078
|
+
const y = kb('Approve', () => act('/api/review/decision/approve', { key: x.key }, 'Saved as a decision.'), 'btn lit', `Approve: ${x.subject}`);
|
|
2079
|
+
const n = kb('Dismiss', () => act('/api/review/decision/dismiss', { key: x.key }, 'Dismissed. It will not be suggested again.'), null, `Dismiss: ${x.subject}`);
|
|
2080
|
+
return card(x.subject, `${x.project} · ${x.date}`, `Matched "${x.word}"` + (x.private ? ' · private' : ''), [y[0], n[0]], two(y, n));
|
|
2081
|
+
}), 'No decisions found in your commits.')),
|
|
2082
|
+
board('Lines you asked to forget', { note: String((d.forget || []).length) }, ...list((d.forget || []).flatMap((x) => {
|
|
2083
|
+
const n = kb('Dismiss', () => act('/api/review/forget/dismiss', { key: x.key }, 'Dismissed. Nothing was changed.'), null, `Dismiss: ${x.text}`);
|
|
2084
|
+
return [card(`//forget: ${x.text}`, x.candidates.length ? 'Retire the line you meant' : 'No line matched', null, [n[0]], { n }),
|
|
2085
|
+
...x.candidates.map((c) => {
|
|
2086
|
+
// R10: retiring a //forget card's line sweeps it from every store; the receipt shows above Today's 5
|
|
2087
|
+
const r = kb('Forget it', () => act('/api/review/retire', { id: c.id }, 'Forgotten everywhere Keepfold keeps it. The receipt is at the top of Review.'), null, `Forget: ${c.text}`);
|
|
2088
|
+
return card(c.text, where(c), null, [r[0]], { r });
|
|
2089
|
+
})];
|
|
2090
|
+
}), 'Nothing to forget.')),
|
|
2091
|
+
board('Imported notes you edited', { note: String((d.imports || []).length) }, ...list((d.imports || []).map((x) => {
|
|
2092
|
+
const n = kb('Dismiss', () => act('/api/review/import/dismiss', { key: x.key }, 'Dismissed. Both pages stay as they are.'), null, `Dismiss: ${x.title}`);
|
|
2093
|
+
return rel(card(x.title, `Your edited page ${x.page} is kept; the changed file came in as ${x.new}`, x.private ? 'private' : null, [n[0]], { n }), x);
|
|
2094
|
+
}), 'No edited imports.')),
|
|
2095
|
+
board('Lines that may steer an AI', { note: String(unsafe.length) }, ...list(unsafe.map((x) => unsafeCard(x)),
|
|
2096
|
+
'No line looks like an instruction to an AI.')),
|
|
2097
|
+
board('Changed outside Keepfold', { note: String(outside.length) }, ...list(outside.map((x) => outsideCard(x)),
|
|
2098
|
+
'No line changed outside Keepfold.')));
|
|
2099
|
+
// R10: the receipt of a //forget just done: what went from each store and what Keepfold cannot remove
|
|
2100
|
+
const receipt = (d.receipt_lines || []).length ? board('Forgotten', { note: 'receipt', id: 'forget-receipt' },
|
|
2101
|
+
...d.receipt_lines.map((t) => h('p', { class: 'pad ink-2' + (t.startsWith('- ') ? ' mono' : ''), text: t }))) : null;
|
|
2102
|
+
put('review', receipt, todayBoard(d, m), more);
|
|
2103
|
+
cardsDrawn('review');
|
|
2104
|
+
}
|
|
2105
|
+
|
|
2106
|
+
/* Tonight (Gemini round 3 "Nightly Closeout"): close the day. One GET (/api/tonight) holds
|
|
2107
|
+
every board; Today's 5 is Review's own board, answered through Review's endpoints. Every
|
|
2108
|
+
text is the server's shown text, set with textContent. */
|
|
2109
|
+
let lastTonight = null;
|
|
2110
|
+
const plural = (n, one) => `${n} ${one}${n === 1 ? '' : 's'}`;
|
|
2111
|
+
function renderTonight(d) {
|
|
2112
|
+
lastTonight = d;
|
|
2113
|
+
const rv = d.review || {}, c = d.counts;
|
|
2114
|
+
badge(rv.count);
|
|
2115
|
+
const act = (path, body, said) => post(path, body, (r) => { renderTonight({ ...lastTonight, review: r }); toast.ok(said); });
|
|
2116
|
+
const empty = !d.pulse.some((x) => x.n);
|
|
2117
|
+
const pulse = empty ? [note('Nothing recorded today yet.')] : [
|
|
2118
|
+
h('div', { class: 'pulse pad' }, d.pulse.map((x, i) => {
|
|
2119
|
+
const label = `${x.from}–${x.to}: ${plural(x.n, 'event')}`;
|
|
2120
|
+
return h('span', { class: `pcell l${x.level}${i === d.hour ? ' now' : ''}`, role: 'img', 'aria-label': label, title: label,
|
|
2121
|
+
'aria-current': i === d.hour ? 'time' : null });
|
|
2122
|
+
})),
|
|
2123
|
+
h('p', { class: 'pad ink-2', text: `${plural(c.added, 'page')} added · ${plural(c.changed, 'page')} changed · ${plural(c.chat_turns, 'chat turn')} · ${plural(c.recorded, 'thing')} recorded by AI apps` }),
|
|
2124
|
+
d.sources.length ? h('div', { class: 'pad inline' }, d.sources.map((s) => h('span', { class: 'chip', text: `${s.source}: ${s.n}` }))) : null];
|
|
2125
|
+
const five = todayBoard(rv, reviewCards(act));
|
|
2126
|
+
const paused = rv.paused || [];
|
|
2127
|
+
five.append(h('div', { class: 'pad inline' }, btn('Open Review', () => show('review', true), 'linkbtn')),
|
|
2128
|
+
paused.length ? note(`Review stopped offering ${paused.map((p) => p.label).join(', ')}; Status has Resume.`) : '');
|
|
2129
|
+
const learned = d.learned.map((g) => h('div', { role: 'group', 'aria-label': `${g.client}: ${plural(g.rows.length, 'change')}` },
|
|
2130
|
+
row(g.client, plural(g.rows.length, 'change'), `Session ${g.session}`, [
|
|
2131
|
+
btn('Undo', () => confirmDialog(`Undo ${g.client}’s session?`, 'Undo',
|
|
2132
|
+
[h('p', { class: 'ink-2', text: `Everything ${g.client} saved in session ${g.session} is reverted, including the ${plural(g.rows.length, 'change')} listed here. This cannot be redone from the app.` })],
|
|
2133
|
+
() => job('/api/tonight/undo', { session: g.session })), null, { 'aria-label': `Undo everything ${g.client} saved in session ${g.session}` })]),
|
|
2134
|
+
g.rows.map((x) => row(x.text, x.id, x.time, null))));
|
|
2135
|
+
put('tonight',
|
|
2136
|
+
board('Today', { note: d.day }, ...pulse),
|
|
2137
|
+
five,
|
|
2138
|
+
board('What AI apps learned today', { note: String(d.learned.reduce((n, g) => n + g.rows.length, 0)) },
|
|
2139
|
+
...list(learned, 'No AI app saved anything today.')),
|
|
2140
|
+
d.studies === false ? null : board('Tomorrow', { note: d.tomorrow_day }, ...list(d.tomorrow.map((x) => row(x.title, x.subject, null, null)), 'Nothing due tomorrow.'),
|
|
2141
|
+
d.tomorrow.length ? h('p', { class: 'pad ink-2' }, 'A 2-minute cold check tomorrow: ask any AI app ', h('code', { text: '/keepfold review' }), '.') : null));
|
|
2142
|
+
cardsDrawn('tonight');
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
/* Agent X-ray (v9 item 6): what keepfold_prime and keepfold_context served each AI app. Ids come
|
|
2146
|
+
back resolved to titles by the server; a private page is only "a private page". Pin: prime
|
|
2147
|
+
always serves it; Mute: prime and context never do. Every text is set with textContent. */
|
|
2148
|
+
const BLOCK = { core: 'Core lines', profile: 'Profile', preferences: 'Lines about you', contract: 'Teaching contract',
|
|
2149
|
+
related: 'Related pages', mistakes: 'Open mistakes', hub: 'Topic', topic: 'Topic concepts', claims: 'Lines about you',
|
|
2150
|
+
found: 'Found', recalled: 'Recalled', read: 'Read' };
|
|
2151
|
+
const xrayOpen = new Set(); // the calls left open survive a redraw after a click
|
|
2152
|
+
const xrayDry = new Map(); // per AI app: its dry run's {prompt, r}
|
|
2153
|
+
const xrayTrace = new Map(); // R27b, per AI app: its traced reply's {text, r}
|
|
2154
|
+
const xrayCmp = { prompt: '', a: null, b: null, r: null }; // R27b: Compare two apps
|
|
2155
|
+
function renderXray(d) {
|
|
2156
|
+
const act = (path, body, said) => post(path, body, (r) => { renderXray(r); toast.ok(said); });
|
|
2157
|
+
const ref = (x) => (x.id ? { id: x.id } : { token: x.token });
|
|
2158
|
+
const pin = (x) => btn(x.pinned ? 'Unpin' : 'Pin', () => act('/api/xray/pin', { ...ref(x), on: !x.pinned },
|
|
2159
|
+
x.pinned ? 'Unpinned.' : 'Pinned. Keepfold now serves it in every first call.'), null, { 'aria-label': `${x.pinned ? 'Unpin' : 'Pin'}: ${x.title}` });
|
|
2160
|
+
const mute = (x) => btn(x.muted ? 'Unmute' : 'Mute', () => act('/api/xray/mute', { ...ref(x), on: !x.muted },
|
|
2161
|
+
x.muted ? 'Unmuted.' : 'Muted. Keepfold will not serve it again.'), null, { 'aria-label': `${x.muted ? 'Unmute' : 'Mute'}: ${x.title}` });
|
|
2162
|
+
const item = (x, block, extra) => row(x.title, BLOCK[block] || block, x.where || null,
|
|
2163
|
+
x.id && x.kind !== 'me' ? [pin(x), mute(x)] : [], extra);
|
|
2164
|
+
const call = (c, client) => {
|
|
2165
|
+
const key = `${client}|${c.ts}|${c.tool}`, when = c.ts ? daysAgo(c.ts, true) : '';
|
|
2166
|
+
const n = (bs) => bs.reduce((k, b) => k + b.items.length, 0);
|
|
2167
|
+
const det = h('details', { class: 'pad xray-call', open: xrayOpen.has(key) },
|
|
2168
|
+
h('summary', { text: `${c.tool} · ${when} · ${c.chars} characters · ${n(c.served)} served${c.trimmed.length ? `, ${n(c.trimmed)} cut for space` : ''}` }),
|
|
2169
|
+
...c.served.flatMap((b) => b.items.map((x) => item(x, b.block))),
|
|
2170
|
+
...c.trimmed.flatMap((b) => b.items.map((x) => item({ ...x, where: 'cut for space' }, b.block, 'cut'))),
|
|
2171
|
+
c.served.length || c.trimmed.length ? null : note('Nothing was served.'));
|
|
2172
|
+
det.addEventListener('toggle', () => { if (det.open) xrayOpen.add(key); else xrayOpen.delete(key); });
|
|
2173
|
+
return det;
|
|
2174
|
+
};
|
|
2175
|
+
const flags = (list, which) => list.map((x) => row(x.title, x.kind === 'claim' ? 'Line about you' : 'Page', x.where || null,
|
|
2176
|
+
[which === 'pin' ? pin(x) : mute(x)]));
|
|
2177
|
+
// P2 Agent Aperture: per AI app, what its profile lets it read (saved through /api/profiles,
|
|
2178
|
+
// as Connect → Agent profiles does), what it is served most, and a dry run of its first call
|
|
2179
|
+
const scopeName = (s) => (s === 'all' ? 'Everything except private' : s);
|
|
2180
|
+
const reads = (list) => (list.includes('all') ? 'everything except private'
|
|
2181
|
+
: d.all_scopes.filter((s) => list.includes(s)).join(', ') || 'nothing');
|
|
2182
|
+
const setScope = (g, s) => {
|
|
2183
|
+
const data = { profiles: d.profiles.profiles.map((p) => ({ ...p, scopes: [...p.scopes] })), unknown: [...d.profiles.unknown] };
|
|
2184
|
+
// the first rule with this match is the one the server matched; none: a new rule for this
|
|
2185
|
+
// app at the end, starting from a copy of "Any other app" (never widened from here)
|
|
2186
|
+
let p = g.rule == null ? null : data.profiles.find((x) => x.match === g.rule);
|
|
2187
|
+
if (!p) {
|
|
2188
|
+
if (data.profiles.length >= d.profiles_max) {
|
|
2189
|
+
toast.error(`Keepfold keeps at most ${d.profiles_max} rules. Remove one under Connect → Agent profiles, then try again.`);
|
|
2190
|
+
return null;
|
|
2191
|
+
}
|
|
2192
|
+
p = { match: g.name.slice(0, 60), scopes: [...data.unknown] };
|
|
2193
|
+
data.profiles.push(p);
|
|
2194
|
+
}
|
|
2195
|
+
const i = p.scopes.indexOf(s);
|
|
2196
|
+
if (i >= 0) p.scopes.splice(i, 1); else p.scopes.push(s);
|
|
2197
|
+
return post('/api/profiles', data).then((r) => r && load('xray').then(() => toast.ok(`Saved. ${g.client} reads: ${reads(p.scopes)}.`)));
|
|
2198
|
+
};
|
|
2199
|
+
const scopeBar = (g) => {
|
|
2200
|
+
const all = g.scopes.includes('all'), named = !!g.name;
|
|
2201
|
+
const chip = (s) => {
|
|
2202
|
+
const locked = !named || (all && s !== 'all');
|
|
2203
|
+
return h('button', { class: 'chip', type: 'button', 'aria-pressed': String(all || g.scopes.includes(s)),
|
|
2204
|
+
'aria-disabled': locked ? 'true' : null,
|
|
2205
|
+
title: !named ? 'Change “Any other app” under Connect → Agent profiles' : locked ? 'Turn off Everything first' : null,
|
|
2206
|
+
onclick: () => (locked ? null : setScope(g, s)) }, scopeName(s));
|
|
2207
|
+
};
|
|
2208
|
+
const why = !named ? 'This app sends no name, so it gets what “Any other app” gets. Change that under Connect → Agent profiles.'
|
|
2209
|
+
: g.rule != null ? `Set by the rule for apps named “${g.rule}”${g.shared.length ? `, shared with ${g.shared.join(', ')}` : ''}.`
|
|
2210
|
+
: `No rule names this app, so it gets what “Any other app” gets. Changing a chip adds a rule for “${g.name}”.`;
|
|
2211
|
+
return h('div', { class: 'field' },
|
|
2212
|
+
h('div', { class: 'inline', role: 'group', 'aria-label': `What ${g.client} reads` },
|
|
2213
|
+
h('span', { class: 'lbl', text: 'Reads:' }), d.all_scopes.map(chip)),
|
|
2214
|
+
h('p', { class: 'help', text: why }));
|
|
2215
|
+
};
|
|
2216
|
+
const often = (g) => (g.often.length ? [h('div', { class: 'field' }, h('span', { class: 'lbl', text: 'Served most often' })),
|
|
2217
|
+
...g.often.map((x) => row(x.title, `served ${x.count} time${x.count === 1 ? '' : 's'}`, x.where || null,
|
|
2218
|
+
x.id && x.kind !== 'me' ? [pin(x), mute(x)] : []))] : []);
|
|
2219
|
+
// a dry run's prompt and answer survive a redraw; its Pin and Mute show the flags as now
|
|
2220
|
+
const pins = new Set(d.pinned.map((x) => x.id || x.token)), mutes = new Set(d.muted.map((x) => x.id || x.token));
|
|
2221
|
+
const now = (x) => ({ ...x, pinned: pins.has(x.id || x.token), muted: mutes.has(x.id || x.token) });
|
|
2222
|
+
// R27b: an answer that lands after a redraw (a job's end, a second load) has lost its box;
|
|
2223
|
+
// a fresh render draws it from the kept state
|
|
2224
|
+
const fresh = (box, draw) => (document.body.contains(box) ? draw() : load('xray'));
|
|
2225
|
+
const dryRun = (g, k) => {
|
|
2226
|
+
const key = `${g.name}|${g.client}`, st = xrayDry.get(key) || { prompt: '', r: null }, id = `xray-dry-${k}`;
|
|
2227
|
+
xrayDry.set(key, st);
|
|
2228
|
+
const input = h('input', { type: 'text', id, value: st.prompt, maxlength: '2000', spellcheck: 'false', autocomplete: 'off' });
|
|
2229
|
+
const out = h('div', {});
|
|
2230
|
+
const draw = () => {
|
|
2231
|
+
const r = st.r;
|
|
2232
|
+
out.replaceChildren(...(r ? [note(`Dry run · ${r.chars} characters · nothing was sent or logged`),
|
|
2233
|
+
...r.served.flatMap((b) => b.items.map((x) => item(now(x), b.block))),
|
|
2234
|
+
...r.trimmed.flatMap((b) => b.items.map((x) => item({ ...now(x), where: 'cut for space' }, b.block, 'cut'))),
|
|
2235
|
+
r.served.length || r.trimmed.length ? null : note('Nothing would be served.')] : []));
|
|
2236
|
+
};
|
|
2237
|
+
const go = () => post('/api/xray/dryrun', { client: g.name, prompt: input.value }, (r) => { st.r = r; fresh(out, draw); });
|
|
2238
|
+
const show = btn('Show', go);
|
|
2239
|
+
const sync = () => { st.prompt = input.value; show.disabled = !input.value.trim(); };
|
|
2240
|
+
input.addEventListener('input', sync);
|
|
2241
|
+
input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !show.disabled) { e.preventDefault(); go(); } });
|
|
2242
|
+
sync();
|
|
2243
|
+
draw();
|
|
2244
|
+
return [h('div', { class: 'field' }, h('label', { for: id, text: `What would ${g.client} get for this prompt?` }),
|
|
2245
|
+
h('div', { class: 'inline' }, input, show)), out];
|
|
2246
|
+
};
|
|
2247
|
+
// R27b (C2): which served line a surprising reply came from; matched by the server with no
|
|
2248
|
+
// model, the reply kept nowhere. Text and results survive a redraw, as the dry run's do
|
|
2249
|
+
const trace = (g, k) => {
|
|
2250
|
+
const key = `${g.name}|${g.client}`, st = xrayTrace.get(key) || { text: '', r: null }, id = `xray-trace-${k}`;
|
|
2251
|
+
xrayTrace.set(key, st);
|
|
2252
|
+
const area = h('textarea', { id, rows: '4', maxlength: '4000', value: st.text, spellcheck: 'false' });
|
|
2253
|
+
const out = h('div', {});
|
|
2254
|
+
const retire = (x) => btn('Retire', () => post('/api/review/retire', { id: x.id.slice(1) }, () => {
|
|
2255
|
+
st.r = { ...st.r, hits: st.r.hits.filter((y) => y.id !== x.id) };
|
|
2256
|
+
toast.ok('Retired. AI apps no longer get this line.');
|
|
2257
|
+
load('xray');
|
|
2258
|
+
}), null, { 'aria-label': `Retire: ${x.title}` });
|
|
2259
|
+
const hit = (x) => {
|
|
2260
|
+
const acts = x.id && x.kind !== 'me' ? [mute(x)] : [];
|
|
2261
|
+
if (x.id && x.kind === 'claim') acts.push(retire(x));
|
|
2262
|
+
const e = row(x.title, null, `served by ${x.tool} · ${x.ts ? daysAgo(x.ts, true) : ''}`, acts);
|
|
2263
|
+
if (x.words && x.words.length) e.querySelector('.t').append(h('span', { class: 'sub', text: `Shared words: ${x.words.join(', ')}` }));
|
|
2264
|
+
return e;
|
|
2265
|
+
};
|
|
2266
|
+
const draw = () => {
|
|
2267
|
+
const r = st.r;
|
|
2268
|
+
out.replaceChildren(...(r ? [note(`Matched against what Keepfold gave ${g.client} in its last ${r.calls} call${r.calls === 1 ? '' : 's'} · the reply was not saved`),
|
|
2269
|
+
...(r.hits.length ? r.hits.map((x) => hit(now(x)))
|
|
2270
|
+
: [note(`None of what Keepfold gave ${g.client} recently matches this reply. The reply may come from the app's own memory or the model itself.`)])] : []));
|
|
2271
|
+
};
|
|
2272
|
+
// Ctrl+Enter too marks the button busy (pressable) for the seconds a big vault takes
|
|
2273
|
+
const run = btn('Trace', () => go());
|
|
2274
|
+
const go = pressable(run, () => post('/api/xray/trace', { client: g.name, text: area.value }, (r) => { st.r = r; fresh(out, draw); }));
|
|
2275
|
+
const sync = () => { st.text = area.value; run.disabled = !area.value.trim(); };
|
|
2276
|
+
area.addEventListener('input', sync);
|
|
2277
|
+
area.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && !run.disabled) { e.preventDefault(); go(); } });
|
|
2278
|
+
sync();
|
|
2279
|
+
draw();
|
|
2280
|
+
return [h('div', { class: 'field' }, h('label', { for: id, text: `Paste a reply from ${g.client} that surprised you` }),
|
|
2281
|
+
area, h('div', { class: 'inline' }, run)), out];
|
|
2282
|
+
};
|
|
2283
|
+
// R27b (G5b-5): an app that pulled many pages through find, recall or read in 15 minutes
|
|
2284
|
+
const when = (ts) => { const s = daysAgo(ts); return /^\d{4}-/.test(s) ? `on ${s}` : s; };
|
|
2285
|
+
const wide = (g) => (g.wide ? [row(`${g.client} read ${g.wide.n} pages in 15 minutes ${when(g.wide.end)}. Chats rarely need that many. If you didn't ask for it, narrow what it reads below, or remove the app under Connect.`,
|
|
2286
|
+
null, null, [btn('Got it', () => act('/api/xray/ack', { client: g.name, end: g.wide.end }, 'Hidden until it reads that widely again.'),
|
|
2287
|
+
null, { 'aria-label': `Got it: ${g.client} read ${g.wide.n} pages` })])] : []);
|
|
2288
|
+
// R27b (G5b-7): two apps' dry runs side by side, and the scopes each one's profile withholds
|
|
2289
|
+
const compare = () => {
|
|
2290
|
+
const apps = d.clients, has = (n) => apps.some((g) => g.name === n);
|
|
2291
|
+
if (!has(xrayCmp.a) || !has(xrayCmp.b)) { xrayCmp.a = apps[0].name; xrayCmp.b = apps[1].name; }
|
|
2292
|
+
const input = h('input', { type: 'text', id: 'xray-cmp-prompt', value: xrayCmp.prompt, maxlength: '2000', spellcheck: 'false', autocomplete: 'off' });
|
|
2293
|
+
const out = h('div', {});
|
|
2294
|
+
// Enter too marks the button busy (pressable) for the seconds a big vault takes
|
|
2295
|
+
const show = btn('Show', () => go());
|
|
2296
|
+
const go = pressable(show, () => post('/api/xray/compare', { prompt: input.value, a: xrayCmp.a, b: xrayCmp.b }, (r) => {
|
|
2297
|
+
const name = (n) => apps.find((g) => g.name === n).client;
|
|
2298
|
+
xrayCmp.r = { ...r, an: name(xrayCmp.a), bn: name(xrayCmp.b) };
|
|
2299
|
+
fresh(out, draw);
|
|
2300
|
+
}));
|
|
2301
|
+
const sync = () => { xrayCmp.prompt = input.value; show.disabled = !input.value.trim() || xrayCmp.a === xrayCmp.b; };
|
|
2302
|
+
const pick = (which, label) => {
|
|
2303
|
+
const s = h('select', { id: `xray-cmp-${which}` }, apps.map((g) => h('option', { value: g.name, text: g.client })));
|
|
2304
|
+
s.value = xrayCmp[which];
|
|
2305
|
+
s.addEventListener('change', () => { xrayCmp[which] = s.value; sync(); });
|
|
2306
|
+
return [h('label', { for: s.id, text: label }), s];
|
|
2307
|
+
};
|
|
2308
|
+
const col = (s, name, other) => {
|
|
2309
|
+
const theirs = new Set(other.served.flatMap((b) => b.items.map((x) => x.id || x.token)));
|
|
2310
|
+
const rows = [...s.served.flatMap((b) => b.items.map((x) => {
|
|
2311
|
+
const e = item(now(x), b.block);
|
|
2312
|
+
if (!theirs.has(x.id || x.token)) e.querySelector('.line1').append(h('span', { class: 'tag', text: `only ${name}` }));
|
|
2313
|
+
return e;
|
|
2314
|
+
})), ...s.trimmed.flatMap((b) => b.items.map((x) => item({ ...now(x), where: 'cut for space' }, b.block, 'cut'))),
|
|
2315
|
+
...s.withheld.map((w) => row(`Not given: ${scopeName(w)}`, null, null, null, 'cut'))];
|
|
2316
|
+
return h('div', { class: 'xray-col' }, h('div', { class: 'field' }, h('span', { class: 'lbl', text: name }),
|
|
2317
|
+
h('span', { class: 'help', text: `${s.chars} characters` })), ...(rows.length ? rows : [note('Nothing would be served.')]));
|
|
2318
|
+
};
|
|
2319
|
+
const draw = () => {
|
|
2320
|
+
const r = xrayCmp.r;
|
|
2321
|
+
out.className = r ? 'xray-cmp' : '';
|
|
2322
|
+
out.replaceChildren(...(r ? [col(r.a, r.an, r.b), col(r.b, r.bn, r.a)] : []));
|
|
2323
|
+
};
|
|
2324
|
+
input.addEventListener('input', sync);
|
|
2325
|
+
input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !show.disabled) { e.preventDefault(); go(); } });
|
|
2326
|
+
sync();
|
|
2327
|
+
draw();
|
|
2328
|
+
return board('Compare two apps', { cls: 'xray-compare' },
|
|
2329
|
+
h('div', { class: 'field' }, h('label', { for: 'xray-cmp-prompt', text: 'Prompt' }), input,
|
|
2330
|
+
h('div', { class: 'inline' }, ...pick('a', 'First app'), ...pick('b', 'Second app'), show)),
|
|
2331
|
+
out, note('Dry run · nothing was sent or logged'));
|
|
2332
|
+
};
|
|
2333
|
+
put('xray',
|
|
2334
|
+
board('Pinned and muted', { note: String(d.pinned.length + d.muted.length) },
|
|
2335
|
+
...(d.pinned.length || d.muted.length ? [...flags(d.pinned, 'pin'), ...flags(d.muted, 'mute')]
|
|
2336
|
+
: [note('Nothing pinned or muted. Pin or mute a page or line from a call below.')])),
|
|
2337
|
+
d.clients.length >= 2 ? compare() : null,
|
|
2338
|
+
...(d.clients.length ? d.clients.map((g, k) => board(g.client, { note: `${g.total} call${g.total === 1 ? '' : 's'}` },
|
|
2339
|
+
...wide(g), scopeBar(g), ...often(g), ...dryRun(g, k), ...trace(g, k), ...g.calls.map((c) => call(c, g.client))))
|
|
2340
|
+
: [board('No calls yet', {}, note('When an AI app asks Keepfold about you, each call shows here.'))]));
|
|
2341
|
+
}
|
|
2342
|
+
|
|
2343
|
+
/* Setup */
|
|
2344
|
+
const skipped = new Set(), opened = new Set();
|
|
2345
|
+
const pick = { model: null, runner: null };
|
|
2346
|
+
// the server keeps a skipped Connect (the app then lands on Status); opening it un-skips
|
|
2347
|
+
function skip(id, on) {
|
|
2348
|
+
const was = skipped.has(id);
|
|
2349
|
+
if (on) skipped.add(id); else skipped.delete(id);
|
|
2350
|
+
if (id === 'connect' && was !== on) return post('/api/setup/skip', { skipped: on }, () => load('setup'));
|
|
2351
|
+
return load('setup');
|
|
2352
|
+
}
|
|
2353
|
+
const STEP_DESC = { vault: 'The folder where your notes live.', connect: 'Let Claude, Cursor and others read and add to it.',
|
|
2354
|
+
history: 'Old AI chats, notes and calendars.', llm: 'A small AI on this computer for Chat.', finish: 'Ask a first question and see what Keepfold knows.' };
|
|
2355
|
+
let stepIds = []; // Setup's steps in order, for the numbers
|
|
2356
|
+
function step(id, name, done, body, first, desc) {
|
|
2357
|
+
const cur = id === first;
|
|
2358
|
+
const title = name.replace(' (optional)', ''), optional = title !== name;
|
|
2359
|
+
const collapsed = !cur && !opened.has(id); // one step at a time: the current one, plus any the user opened
|
|
2360
|
+
const mark = h('span', { class: 'step-mark' + (done ? ' done' : ''), 'aria-hidden': 'true', text: done ? '✓' : String(stepIds.indexOf(id) + 1) });
|
|
2361
|
+
const band = h('div', { class: 'band' }, mark,
|
|
2362
|
+
h('div', { class: 'step-t' }, h('h2', { text: title }), optional ? h('span', { class: 'step-opt', text: 'Optional' }) : null,
|
|
2363
|
+
h('p', { class: 'step-d', text: desc || STEP_DESC[id] })),
|
|
2364
|
+
h('span', { class: 'band-note' }, done ? 'Done' : skipped.has(id) ? 'Skipped' : null),
|
|
2365
|
+
collapsed ? btn(done ? 'Edit' : 'Open', () => { opened.add(id); return id === 'connect' ? skip(id, false) : load('setup'); }, 'band-btn',
|
|
2366
|
+
{ 'aria-label': `${done ? 'Edit' : 'Open'}: ${title}` })
|
|
2367
|
+
: !done && id !== 'finish' && !skipped.has(id) ? btn('Skip', () => { opened.delete(id); return skip(id, true); }, 'band-btn', { 'aria-label': `Skip: ${title}` })
|
|
2368
|
+
: done || skipped.has(id) ? btn('Hide', () => { opened.delete(id); load('setup'); }, 'band-btn', { 'aria-label': `Hide: ${title}` }) : null);
|
|
2369
|
+
return h('div', { class: 'board step' + (collapsed ? ' collapsed' : '') + (cur ? ' current' : '') }, band, ...body);
|
|
2370
|
+
}
|
|
2371
|
+
function renderSetup(d) {
|
|
2372
|
+
const cn = d.connect, on = cn.filter((t) => t.connected), todo = cn.filter((t) => t.detected && !t.connected);
|
|
2373
|
+
const names = (ts) => ts.map((t) => t.label).join(', ');
|
|
2374
|
+
const done = { vault: d.vault.done, embed: d.embed.done, connect: on.length > 0,
|
|
2375
|
+
history: d.history.done || Object.values(d.imports).some((x) => x.count), llm: d.test.done };
|
|
2376
|
+
if (d.connect_skipped) skipped.add('connect'); else skipped.delete('connect');
|
|
2377
|
+
const first = d.order.find((k) => !done[k] && !skipped.has(k)) || 'finish';
|
|
2378
|
+
stepIds = [...d.order, 'finish'];
|
|
2379
|
+
const rn = d.runner, md = d.model;
|
|
2380
|
+
if (!pick.model) pick.model = md.recommend;
|
|
2381
|
+
if (!pick.runner) pick.runner = rn.ollama.found || rn.ollama.serving ? 'ollama' : rn.lmstudio.found ? 'lmstudio' : 'ollama';
|
|
2382
|
+
const m = md.options.find((o) => o.id === pick.model) || md.options[0];
|
|
2383
|
+
|
|
2384
|
+
// moved: the config names a folder that is gone; ask, never prefill (that would make a new, empty vault)
|
|
2385
|
+
const moved = d.vault.moved, gi = d.git;
|
|
2386
|
+
const path = h('input', { type: 'text', id: 'vault-path', value: moved ? '' : d.vault.path || d.vault.default, placeholder: moved ? 'The folder’s new location' : null, 'aria-label': 'Vault folder', spellcheck: 'false' });
|
|
2387
|
+
const sVault = step('vault', 'Vault', d.vault.done, [
|
|
2388
|
+
moved ? row('Did you move your vault?', null, `Keepfold used ${d.vault.path}, which is not there any more. Paste the folder’s new location below, or a new folder to start an empty vault.`, null) : null,
|
|
2389
|
+
h('div', { class: 'field' }, h('label', { for: 'vault-path', text: 'The folder for your notes' }),
|
|
2390
|
+
h('div', { class: 'inline' }, path, btn('Use this folder', () => job('/api/setup/vault', { path: path.value }), 'btn lit')),
|
|
2391
|
+
h('p', { class: 'help', text: 'Keepfold adds its own folders and a history there, and never changes notes you already have. Obsidian can open it as a vault.' })),
|
|
2392
|
+
gi && !gi.found && gi.enabled !== false ? row('Git (history and undo)', 'not installed', 'Without git, Keepfold keeps no history of your vault, so undo does nothing. Free.',
|
|
2393
|
+
gi.install.run ? [btn(`Install Git (${gi.install.size}, via ${gi.install.source})`, () => job('/api/setup/git', {})), ext(gi.install.license, 'License')] : [ext(gi.install.page, 'Get Git')]) : null], first);
|
|
2394
|
+
|
|
2395
|
+
const e = d.embed;
|
|
2396
|
+
const sEmbed = step('embed', 'Search model', e.done, [
|
|
2397
|
+
row('Find notes by meaning', e.done ? 'downloaded' : 'not downloaded',
|
|
2398
|
+
'Without it, search matches words only. It downloads once, works offline, then indexes your notes.',
|
|
2399
|
+
[e.done ? null : btn(`Download search model (${e.size}, from ${e.source})`, () => job('/api/setup/embed', {}), 'btn lit')]),
|
|
2400
|
+
row('Index my notes', e.indexed ? `indexed ${e.indexed}` : 'not yet', 'Reads every note once so search by meaning can find it. Safe to stop and run again.',
|
|
2401
|
+
[btn('Index my notes', () => job('/api/setup/index', {}), 'btn', { disabled: !(e.done && d.vault.done) })])], first,
|
|
2402
|
+
`Find notes by meaning. A download of ${e.size}, once.`);
|
|
2403
|
+
|
|
2404
|
+
const inst = rn.install;
|
|
2405
|
+
const start = (id, name) => btn('Start', () => job('/api/setup/start', { runner: id }), 'btn lit', { 'aria-label': `Start: ${name}` });
|
|
2406
|
+
const oll = row('Ollama', RSTATE[rn.ollama.state], 'Runs AI models on this computer. Free.',
|
|
2407
|
+
rn.ollama.state === 'stopped' ? [start('ollama', 'Ollama')] : rn.ollama.found ? null
|
|
2408
|
+
: inst.run ? [btn(`Install Ollama (${inst.size}, via ${inst.source})`, () => job('/api/setup/install', {}), 'btn lit'), inst.license ? ext(inst.license, 'License') : null] : [ext(inst.page, 'Get Ollama')]);
|
|
2409
|
+
oll.querySelector('.line1').append(h('span', { class: 'rec', text: 'RECOMMENDED' }));
|
|
2410
|
+
const runnerRows = [
|
|
2411
|
+
oll,
|
|
2412
|
+
!rn.ollama.found ? h('div', { class: 'pad' }, h('span', { class: 'sub', text: inst.run ? 'The button runs:' : 'Run this yourself:' }),
|
|
2413
|
+
h('pre', { text: inst.run ? inst.run.join(' ') : inst.show || inst.page })) : null,
|
|
2414
|
+
row('LM Studio', RSTATE[rn.lmstudio.state], 'An app with its own model library; Keepfold uses its lms command.',
|
|
2415
|
+
rn.lmstudio.state === 'stopped' ? [start('lmstudio', 'LM Studio')] : rn.lmstudio.found ? null : [ext(rn.lmstudio.page, 'I’ll use LM Studio')]),
|
|
2416
|
+
h('p', { class: 'pad ink-3 small', text: 'Optional: skip this to run Keepfold on rules and the search model only. A model is a download of several GB.' })];
|
|
2417
|
+
|
|
2418
|
+
const runners = [['ollama', 'Ollama', rn.ollama.found || rn.ollama.serving], ['lmstudio', 'LM Studio', rn.lmstudio.found]];
|
|
2419
|
+
const opts = md.options.map((o) => {
|
|
2420
|
+
const r = h('input', { type: 'radio', name: 'model', value: o.id, checked: o.id === pick.model, id: 'm-' + o.id });
|
|
2421
|
+
r.addEventListener('change', () => { pick.model = o.id; load('setup'); });
|
|
2422
|
+
const have = o.have.ollama || o.have.lmstudio;
|
|
2423
|
+
return h('label', { class: 'brow opt', for: 'm-' + o.id }, r,
|
|
2424
|
+
h('div', { class: 't' }, h('div', { class: 'line1' }, h('span', { class: 'ttl', text: o.label }), h('span', { class: 'val', text: o.size }),
|
|
2425
|
+
o.id === md.recommend ? h('span', { class: 'rec', text: 'RECOMMENDED' }) : null, have ? h('span', { class: 'done-mark', text: '✓ downloaded' }) : null),
|
|
2426
|
+
h('span', { class: 'sub', text: o.tradeoff })));
|
|
2427
|
+
});
|
|
2428
|
+
const runnerPick = h('div', { class: 'inline' }, h('span', { class: 'lbl', text: 'Runner:' }), runners.map(([id, label, ok]) => {
|
|
2429
|
+
const r = h('input', { type: 'radio', name: 'runner', value: id, checked: pick.runner === id, disabled: !ok, id: 'r-' + id });
|
|
2430
|
+
r.addEventListener('change', () => { pick.runner = id; load('setup'); });
|
|
2431
|
+
return h('label', { class: 'check', for: 'r-' + id }, r, h('span', { text: label + (ok ? '' : ' (not found)') }));
|
|
2432
|
+
}));
|
|
2433
|
+
const haveIt = pick.runner === 'ollama' ? m.have.ollama : m.have.lmstudio;
|
|
2434
|
+
const runnerOk = runners.find((x) => x[0] === pick.runner)[2];
|
|
2435
|
+
const src = pick.runner === 'ollama' ? 'ollama.com' : 'LM Studio’s catalogue';
|
|
2436
|
+
const sLlm = step('llm', 'Local model (optional)', done.llm, [
|
|
2437
|
+
...runnerRows,
|
|
2438
|
+
row('This computer', md.hardware.label, 'The size a model can use well depends on this.'),
|
|
2439
|
+
h('div', { class: 'opts' }, opts),
|
|
2440
|
+
h('div', { class: 'field' }, runnerPick,
|
|
2441
|
+
h('div', { class: 'inline' }, btn(`Set up ${m.label}` + (haveIt ? ' (downloaded)' : ` (${m.size}, from ${src})`),
|
|
2442
|
+
() => job('/api/setup/model', { model: m.id, runner: pick.runner }), 'btn lit', { disabled: !runnerOk })),
|
|
2443
|
+
h('p', { class: 'help', text: runnerOk ? 'Downloads it here with progress (Cancel stops it), then sends one made-up sentence and turns the local model on when it answers.' : 'Install or start a runner first (above).' }))], first);
|
|
2444
|
+
|
|
2445
|
+
const connectFound = () => {
|
|
2446
|
+
const want = Object.fromEntries(todo.map((t) => [t.id, true]));
|
|
2447
|
+
return post('/api/connect/plan', { want }, (p) => {
|
|
2448
|
+
if (!p.rows.length) { toast('Nothing to change.'); return; }
|
|
2449
|
+
confirmChanges(p.rows, () => job('/api/connect/apply', { want }));
|
|
2450
|
+
});
|
|
2451
|
+
};
|
|
2452
|
+
const sConnect = step('connect', 'Connect AI apps', done.connect, [
|
|
2453
|
+
row(todo.length ? `Found: ${names(todo)}` : 'No other AI app found', null,
|
|
2454
|
+
'This is what lets Claude and your other AI apps know you. Keepfold adds itself to each app’s settings; you see the exact files first, and each one is backed up.',
|
|
2455
|
+
todo.length ? [btn(`Connect ${names(todo)}`, connectFound, 'btn lit', { disabled: !d.vault.done })]
|
|
2456
|
+
: on.length ? null : [ext('https://claude.ai/download', 'Get Claude Desktop')]),
|
|
2457
|
+
row('Choose apps one by one', null, 'Add or remove single apps, and see what each change does.', [btn('Open Connect AI apps', () => show('connect', true))])], first);
|
|
2458
|
+
|
|
2459
|
+
const sHistory = step('history', 'Add your history (optional)', done.history,
|
|
2460
|
+
d.vault.done ? historyBoard(d) : [note('Set up the vault first.')], first);
|
|
2461
|
+
|
|
2462
|
+
const sFinish = step('finish', 'Try it', false, [
|
|
2463
|
+
h('div', { class: 'pad' }, h('p', { class: 'ink-2', text: on.length ? `Restart ${names(on)} first, so it loads Keepfold.${on.some((t) => t.id === 'claude-desktop') ? ' ' + RESTART_DESKTOP : ''} Then try these in Claude:` : 'Connect an AI app first (above) and restart it. Then try these in Claude:' }),
|
|
2464
|
+
h('ol', { class: 'how' }, d.first_prompts.map((x) => h('li', {}, h('code', { text: x })))),
|
|
2465
|
+
h('p', { class: 'help', text: 'This step never gets a check mark: Keepfold cannot see your chats in Claude. When Claude answers one of these using Keepfold, you are set.' })),
|
|
2466
|
+
row('Chat', null, 'Or ask about your notes here, with a model on this computer.', [btn('Open Chat', () => show('chat', true))]),
|
|
2467
|
+
row('Browsing', null, 'Bring in your browser history, privately.', [btn('Open', () => show('browse', true))])], first);
|
|
2468
|
+
const steps = { vault: sVault, embed: sEmbed, connect: sConnect, history: sHistory, llm: sLlm };
|
|
2469
|
+
const n = d.order.filter((k) => done[k]).length, total = stepIds.length;
|
|
2470
|
+
const fill = h('span', {});
|
|
2471
|
+
fill.style.setProperty('--pct', `${Math.round(100 * n / total)}%`);
|
|
2472
|
+
// the fill is scaleX(--f); a changed value starts from the last one drawn, so it moves (app.css .setup-bar)
|
|
2473
|
+
const f1 = String(n / total), f0 = setupWas ? setupWas.f : f1;
|
|
2474
|
+
fill.style.setProperty('--f', still() ? f1 : f0);
|
|
2475
|
+
const bar = h('div', { class: 'setup-bar', role: 'progressbar', 'aria-label': 'Setup progress', 'aria-valuemin': '0', 'aria-valuemax': String(total), 'aria-valuenow': String(n) }, fill);
|
|
2476
|
+
const label = `${n} of ${total} done`, text = h('span', { class: 'prog-text', text: label });
|
|
2477
|
+
put('setup', h('div', { class: 'setup-prog' }, bar, text), ...d.order.map((k) => steps[k]), sFinish);
|
|
2478
|
+
if (f0 !== f1 && !still()) { void fill.offsetWidth; fill.style.setProperty('--f', f1); } // flush, then move
|
|
2479
|
+
if (setupWas && setupWas.label !== label) crossFade(text, setupWas.label);
|
|
2480
|
+
setupWas = { f: f1, label };
|
|
2481
|
+
}
|
|
2482
|
+
let setupWas = null; // the last Setup progress drawn: its fill value and its text
|
|
2483
|
+
|
|
2484
|
+
/* ---- the welcome guide: a first-run dialog, one step at a time. Every action is Setup's or
|
|
2485
|
+
Connect's own route and job; every state comes from /api/setup (`wg.d`) ---- */
|
|
2486
|
+
const WG_N = 6;
|
|
2487
|
+
// mine: a job this guide started is running, from step `at` (only that step shows its line)
|
|
2488
|
+
const wg = { step: 1, d: null, open: false, done: false, mine: false, job: null, at: 0, path: null };
|
|
2489
|
+
async function wgJob(path, body) {
|
|
2490
|
+
Object.assign(wg, { mine: true, job: null, at: wg.step });
|
|
2491
|
+
const r = await job(path, body);
|
|
2492
|
+
if (!r) wg.mine = false; // refused (an empty path, say): no job of the guide's
|
|
2493
|
+
return r;
|
|
2494
|
+
}
|
|
2495
|
+
const wgConnected = (d) => d.connect.some((t) => t.connected);
|
|
2496
|
+
const WG_EXTRAS = [['embed', 'Search model', (d) => `Finds notes by meaning; ${d.embed.size}, once.`, (d) => d.embed.done],
|
|
2497
|
+
['history', 'Your history', () => 'Old AI chats, notes and calendars.', (d) => d.history.done || Object.values(d.imports).some((x) => x.count)],
|
|
2498
|
+
['llm', 'Local model', () => 'A small AI on this computer for Chat.', (d) => d.test.done]];
|
|
2499
|
+
const WG_TOUR = [
|
|
2500
|
+
['Every day', [['home', 'Home', 'What is due and your brain.'], ['tonight', 'Tonight', 'Close the day and see what comes tomorrow.'],
|
|
2501
|
+
['chat', 'Chat', 'Ask about your notes.'], ['review', 'Review', 'What Keepfold wants you to check.']]],
|
|
2502
|
+
['Your setup', [['setup', 'Setup', 'These steps, any time.'], ['connect', 'Connect AI apps', 'Which apps use Keepfold.'],
|
|
2503
|
+
['llm', 'Local model', 'The small AI for Chat.'], ['browse', 'Browsing', 'Your browser history, kept on this computer.']]],
|
|
2504
|
+
['Check', [['status', 'Status', 'Each part of Keepfold, and what needs you.'], ['xray', 'Agent X-ray', 'What each AI app was given.'],
|
|
2505
|
+
['vault', 'Dashboard and vault', 'Your notes folder, backups and checks.']]]];
|
|
2506
|
+
function wgOpen(at, d) {
|
|
2507
|
+
const dlg = $('welcome');
|
|
2508
|
+
Object.assign(wg, { step: at || 1, open: true });
|
|
2509
|
+
if (d) wg.d = d;
|
|
2510
|
+
if (!dlg.open) dlg.showModal();
|
|
2511
|
+
dlg.append($('toast')); // in the top layer with the guide, so a message shows above its backdrop
|
|
2512
|
+
wgDraw();
|
|
2513
|
+
$('wg-next').focus();
|
|
2514
|
+
return d ? null : wgLoad();
|
|
2515
|
+
}
|
|
2516
|
+
async function wgLoad() {
|
|
2517
|
+
try { wg.d = await api('/api/setup'); } catch (e) { /* api() said why; the step keeps what it had */ }
|
|
2518
|
+
if (wg.open) wgDraw();
|
|
2519
|
+
}
|
|
2520
|
+
// Finish, Skip for now, Esc, the corner button, or a page opened from the guide: never by itself again
|
|
2521
|
+
function wgClosed() {
|
|
2522
|
+
if (!wg.open) return;
|
|
2523
|
+
wg.open = false;
|
|
2524
|
+
document.body.append($('toast')); // back to the page
|
|
2525
|
+
if (!wg.done) { wg.done = true; post('/api/app/welcome', { welcome_done: true }); }
|
|
2526
|
+
}
|
|
2527
|
+
function wgClose() {
|
|
2528
|
+
$('welcome').close(); // the browser puts focus back where it was before the guide opened
|
|
2529
|
+
wgClosed();
|
|
2530
|
+
}
|
|
2531
|
+
function wgGo(s) { // a page from the guide: close it, then open the page
|
|
2532
|
+
wgClose();
|
|
2533
|
+
if (s === 'home') location.assign('/');
|
|
2534
|
+
else show(s, true);
|
|
2535
|
+
}
|
|
2536
|
+
// the job this guide started (the vault, a Connect): its line in the step, as the job line says it
|
|
2537
|
+
function wgJobLine() {
|
|
2538
|
+
const j = wg.job, p = h('p', { class: 'wg-job', id: 'wg-job', role: 'status' });
|
|
2539
|
+
if (!j || wg.at !== wg.step) return p;
|
|
2540
|
+
const r = j.result || {};
|
|
2541
|
+
if (j.running) p.textContent = `${j.name}… ${j.line || ''}`;
|
|
2542
|
+
// j.error is the toast's (finish): said once, so this line names only the failure
|
|
2543
|
+
else if (jobFailed(j)) { p.classList.add('bad'); p.textContent = `${j.name}: failed.${j.error ? '' : ` ${(r.lines || [])[0] || ''}`}`.trim(); }
|
|
2544
|
+
else p.textContent = `${j.name}: done.`;
|
|
2545
|
+
return p;
|
|
2546
|
+
}
|
|
2547
|
+
function wgSteps(d) {
|
|
2548
|
+
const wait = [note('Loading…')];
|
|
2549
|
+
return [
|
|
2550
|
+
['Welcome to Keepfold', 'Keepfold is your second brain on this computer. It keeps what you learn, decide and read as notes in one folder, and gives your AI apps (Claude, Cursor, Codex, Gemini CLI and others) what they need to know about you, so you stop repeating yourself. Your notes stay on this computer; the AI apps you connect see what Keepfold hands them.',
|
|
2551
|
+
false, [h('p', { class: 'wg-sub', text: 'What happens next:' }),
|
|
2552
|
+
h('ol', { class: 'how' }, ['Pick a folder for your notes.', 'Connect your AI apps.', 'Ask Keepfold a question.'].map((t) => h('li', { text: t })))]],
|
|
2553
|
+
['Your vault', 'Your vault is one folder on this computer where Keepfold keeps your notes, as plain text files that Obsidian can open too.',
|
|
2554
|
+
!!d && d.vault.done, !d ? wait : d.vault.done
|
|
2555
|
+
? [h('p', { class: 'wg-ok' }, h('span', { class: 'done-mark', text: '✓' }), ' Your notes are in ', h('span', { class: 'mono', text: d.vault.path })), wgJobLine()]
|
|
2556
|
+
: (() => {
|
|
2557
|
+
const moved = d.vault.moved;
|
|
2558
|
+
const path = h('input', { type: 'text', id: 'wg-path', value: wg.path ?? (moved ? '' : d.vault.path || d.vault.default),
|
|
2559
|
+
placeholder: moved ? 'The folder’s new location' : null, spellcheck: 'false' });
|
|
2560
|
+
path.addEventListener('input', () => { wg.path = path.value; });
|
|
2561
|
+
const use = () => wgJob('/api/setup/vault', { path: path.value });
|
|
2562
|
+
path.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); use(); } });
|
|
2563
|
+
return [moved ? h('p', { class: 'help', text: `Keepfold used ${d.vault.path}, which is not there any more. Type the folder’s new location, or a new folder to start an empty vault.` }) : null,
|
|
2564
|
+
h('div', { class: 'field' }, h('label', { for: 'wg-path', text: 'The folder for your notes' }),
|
|
2565
|
+
h('div', { class: 'inline' }, path, btn('Use this folder', use, 'btn lit')),
|
|
2566
|
+
h('p', { class: 'help', text: 'Keepfold adds its own folders and a history there, and never changes notes you already have.' })),
|
|
2567
|
+
wgJobLine()];
|
|
2568
|
+
})()],
|
|
2569
|
+
['Connect your AI apps', 'Connecting lets an AI app read what Keepfold knows about you and save what you teach it. You see the exact files first, and each one is backed up.',
|
|
2570
|
+
!!d && wgConnected(d), !d ? wait : (() => {
|
|
2571
|
+
const apps = d.connect.filter((t) => t.detected || t.connected);
|
|
2572
|
+
const one = (t) => {
|
|
2573
|
+
const want = { [t.id]: true }; // this app only: the others stay as they are
|
|
2574
|
+
return post('/api/connect/plan', { want }, (p) => {
|
|
2575
|
+
if (!p.rows.length) { toast('Nothing to change.'); return; }
|
|
2576
|
+
confirmChanges(p.rows, () => wgJob('/api/connect/apply', { want }));
|
|
2577
|
+
});
|
|
2578
|
+
};
|
|
2579
|
+
return [...(apps.length ? apps.map((t) => row(t.label, null, t.connected ? 'Connected.' : 'Found on this computer; not connected.',
|
|
2580
|
+
[t.connected ? h('span', { class: 'done-mark', text: '✓ Connected' })
|
|
2581
|
+
: btn('Connect', () => one(t), 'btn lit', { 'aria-label': `Connect ${t.label}`, disabled: !d.vault.done })]))
|
|
2582
|
+
: [row('No AI app found on this computer', null, 'Install one, then come back to this step.', [ext('https://claude.ai/download', 'Get Claude Desktop')])]),
|
|
2583
|
+
!d.vault.done && apps.length ? h('p', { class: 'help', text: 'Set up your vault first (step 2): each app is pointed at it.' }) : null,
|
|
2584
|
+
h('p', { class: 'help', text: 'Restart an app after connecting it.' }), wgJobLine()];
|
|
2585
|
+
})()],
|
|
2586
|
+
['Optional extras', 'Each of these is optional. Add them now or any time later from Setup.',
|
|
2587
|
+
!!d && WG_EXTRAS.every((x) => x[3](d)), !d ? wait : WG_EXTRAS.map(([id, title, why, done]) => row(title, null, why(d),
|
|
2588
|
+
[done(d) ? h('span', { class: 'done-mark', text: '✓ Done' })
|
|
2589
|
+
: btn('Open in Setup', () => { opened.add(id); wgGo('setup'); }, 'btn', { 'aria-label': `Open in Setup: ${title}` })]))],
|
|
2590
|
+
['Where things are', 'Every page is in the sidebar on the left, in three groups.', false,
|
|
2591
|
+
[h('div', { class: 'wg-tour' }, WG_TOUR.flatMap(([group, items]) => [h('h3', { text: group }),
|
|
2592
|
+
h('ul', {}, items.map(([s, name, what]) => h('li', {}, btn(name, () => wgGo(s), 'linkbtn', { 'aria-label': `Open ${name}` }), h('span', { text: what }))))]))]],
|
|
2593
|
+
['Try it', 'Ask Keepfold something about your notes. Chat answers on this computer and shows the pages it used.', false, (() => {
|
|
2594
|
+
// a new vault has the About you pages, so the example gets a real answer; empty sends it
|
|
2595
|
+
const q = h('input', { type: 'text', id: 'wg-q', spellcheck: 'true', placeholder: 'For example: what do you know about me?' });
|
|
2596
|
+
const ask = () => {
|
|
2597
|
+
const text = q.value.trim() || 'What do you know about me?';
|
|
2598
|
+
q.value = ''; // sent: the field is empty if the guide is seen again
|
|
2599
|
+
wgClose();
|
|
2600
|
+
// a new chat with the question sent, as a Chat example fills the box and Enter sends it
|
|
2601
|
+
if (!chatS.busy) { dropFiles(); Object.assign(chatS, { id: null, msgs: [], remembers: 0, pages: [], draft: text, focus: true, ask: true }); }
|
|
2602
|
+
show('chat', true);
|
|
2603
|
+
};
|
|
2604
|
+
q.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); ask(); } });
|
|
2605
|
+
return [h('div', { class: 'field' }, h('label', { for: 'wg-q', text: 'Ask Keepfold something about your notes' }),
|
|
2606
|
+
h('div', { class: 'inline' }, q, btn('Ask', ask, 'btn lit')))];
|
|
2607
|
+
})()]];
|
|
2608
|
+
}
|
|
2609
|
+
function wgDraw() {
|
|
2610
|
+
const n = wg.step, a = document.activeElement, body = $('wg-body');
|
|
2611
|
+
const keep = a && a.id && body.contains(a) ? a.id : null; // a redraw keeps focus on the same field
|
|
2612
|
+
const [title, lead, done, kids] = wgSteps(wg.d)[n - 1];
|
|
2613
|
+
$('wg-count').textContent = `Step ${n} of ${WG_N}`;
|
|
2614
|
+
$('wg-count').setAttribute('aria-current', 'step');
|
|
2615
|
+
$('wg-state').hidden = !done;
|
|
2616
|
+
$('wg-bar').setAttribute('aria-valuenow', String(n));
|
|
2617
|
+
$('wg-fill').style.setProperty('--f', String(n / WG_N));
|
|
2618
|
+
$('wg-title').textContent = title;
|
|
2619
|
+
body.replaceChildren(h('p', { class: 'wg-lead', id: 'wg-desc', text: lead }), ...kids.filter(Boolean));
|
|
2620
|
+
const lost = a === $('wg-back') && n === 1;
|
|
2621
|
+
$('wg-back').hidden = n === 1;
|
|
2622
|
+
$('wg-next').textContent = n === 1 ? 'Let’s start' : n === WG_N ? 'Finish' : 'Next';
|
|
2623
|
+
if (keep && $(keep)) $(keep).focus();
|
|
2624
|
+
else if (lost || (a && body.contains(a))) $('wg-next').focus();
|
|
2625
|
+
}
|
|
2626
|
+
function wgMove(by) {
|
|
2627
|
+
wg.step = Math.min(WG_N, Math.max(1, wg.step + by));
|
|
2628
|
+
if (!wg.mine) wg.job = null; // a finished job's line belongs to the step that ran it
|
|
2629
|
+
wgDraw();
|
|
2630
|
+
if (wg.step >= 2 && wg.step <= 4) wgLoad(); // a step done elsewhere meanwhile shows Done
|
|
2631
|
+
}
|
|
2632
|
+
$('wg-x').append(icon('x'));
|
|
2633
|
+
$('wg-x').addEventListener('click', wgClose);
|
|
2634
|
+
$('wg-skip').addEventListener('click', wgClose);
|
|
2635
|
+
$('wg-back').addEventListener('click', () => wgMove(-1));
|
|
2636
|
+
$('wg-next').addEventListener('click', () => (wg.step === WG_N ? wgClose() : wgMove(1)));
|
|
2637
|
+
$('welcome').addEventListener('close', wgClosed); // Esc closes it as Skip does
|
|
2638
|
+
$('welcome-open').addEventListener('click', () => wgOpen(1));
|
|
2639
|
+
|
|
2640
|
+
const RENDER = { tonight: renderTonight, setup: renderSetup, chat: renderChat, status: renderStatus, review: renderReview, xray: renderXray, connect: renderConnect, llm: renderLlm, browse: renderBrowse, vault: renderVault };
|
|
2641
|
+
|
|
2642
|
+
/* ---- header: wordmark, theme, quit, nav ---- */
|
|
2643
|
+
$('wordmark').append(dm('KEEPFOLD', 3, 'Keepfold'));
|
|
2644
|
+
const root = document.documentElement;
|
|
2645
|
+
const dayMq = window.matchMedia('(prefers-color-scheme: light)');
|
|
2646
|
+
// one key with Home (dashboard.js); 'keepfold-app-theme' was this page's own key before
|
|
2647
|
+
try { const t = localStorage.getItem('keepfold-theme') || localStorage.getItem('keepfold-app-theme'); if (t === 'day' || t === 'night') root.dataset.theme = t; } catch (e) { /* storage off */ }
|
|
2648
|
+
function themeBtn() {
|
|
2649
|
+
const day = root.dataset.theme ? root.dataset.theme === 'day' : dayMq.matches;
|
|
2650
|
+
const b = $('theme');
|
|
2651
|
+
b.replaceChildren(icon(day ? 'moon' : 'sun'));
|
|
2652
|
+
b.setAttribute('aria-label', day ? 'Switch to the night theme' : 'Switch to the day theme');
|
|
2653
|
+
b.title = b.getAttribute('aria-label');
|
|
2654
|
+
}
|
|
2655
|
+
$('theme').addEventListener('click', () => {
|
|
2656
|
+
const day = root.dataset.theme ? root.dataset.theme === 'day' : dayMq.matches;
|
|
2657
|
+
root.dataset.theme = day ? 'night' : 'day';
|
|
2658
|
+
try { localStorage.setItem('keepfold-theme', root.dataset.theme); } catch (e) { /* storage off */ }
|
|
2659
|
+
themeBtn();
|
|
2660
|
+
});
|
|
2661
|
+
dayMq.addEventListener('change', themeBtn);
|
|
2662
|
+
themeBtn();
|
|
2663
|
+
$('quit').addEventListener('click', () => confirmDialog('Stop Keepfold?', 'Quit',
|
|
2664
|
+
[h('p', { class: 'ink-2', text: 'Running jobs are cancelled; your vault is not affected.' })],
|
|
2665
|
+
() => post('/api/quit', {}, () => gone('The Keepfold app has stopped. You can close this tab.'))));
|
|
2666
|
+
$('job-cancel').addEventListener('click', pressable($('job-cancel'), () => post('/api/job/cancel', {})));
|
|
2667
|
+
$('toast-x').append(icon('x'));
|
|
2668
|
+
$('toast-x').addEventListener('click', toastHide);
|
|
2669
|
+
for (const [t, fn] of [['mouseenter', toastHold], ['mouseleave', toastRelease], ['focusin', toastHold], ['focusout', toastRelease]]) $('toast').addEventListener(t, fn);
|
|
2670
|
+
document.querySelectorAll('.side button').forEach((b) => b.addEventListener('click', () => show(b.dataset.s, true)));
|
|
2671
|
+
$('section-select').addEventListener('change', (e) => (e.target.value === 'home' ? location.assign('/') : show(e.target.value, true)));
|
|
2672
|
+
window.addEventListener('popstate', () => { const s = location.hash.slice(1); if (s !== current) show(s, true); }); // Back switches sections
|
|
2673
|
+
|
|
2674
|
+
// a section at once: the link's, else the last one this tab used, else Status (its first
|
|
2675
|
+
// answer may move to the app's choice); each shows Loading… until its answer comes
|
|
2676
|
+
const want = location.hash.slice(1);
|
|
2677
|
+
let lastSection = null;
|
|
2678
|
+
try { lastSection = sessionStorage.getItem('keepfold.section'); } catch (e) { /* storage off */ }
|
|
2679
|
+
if (want === 'import-claude') { // Home's claude.ai reminder: Setup, with that card's steps open
|
|
2680
|
+
guide = { source: 'claude', step: 1 };
|
|
2681
|
+
opened.add('history');
|
|
2682
|
+
show('setup');
|
|
2683
|
+
} else if (SECTIONS.includes(want)) show(want);
|
|
2684
|
+
else if (SECTIONS.includes(lastSection)) show(lastSection);
|
|
2685
|
+
else { landing = true; show('status'); }
|
|
2686
|
+
// the welcome guide: Home's Help link (#welcome) opens it at step 1; by itself once, on a first
|
|
2687
|
+
// run (no vault, or Setup's key steps not done) until it is finished or skipped. No vault: at
|
|
2688
|
+
// once, from the quick look, while /api/setup loads for steps 2-4; a vault but no AI app
|
|
2689
|
+
// connected needs Setup's answer first
|
|
2690
|
+
if (want === 'welcome') wgOpen(1);
|
|
2691
|
+
// by itself never over another open dialog (a confirm, say): once that one closes
|
|
2692
|
+
const wgAuto = (d) => {
|
|
2693
|
+
const other = [...document.querySelectorAll('dialog')].find((x) => x.open);
|
|
2694
|
+
// fresh state then: that dialog may have connected an app
|
|
2695
|
+
if (other) other.addEventListener('close', () => { if (!wg.open && !wg.done) wgAuto(); }, { once: true });
|
|
2696
|
+
else wgOpen(1, d);
|
|
2697
|
+
};
|
|
2698
|
+
api('/api/app/welcome').then((w) => {
|
|
2699
|
+
// the nav's Review count, only once a vault exists (without one /api/review answers 400)
|
|
2700
|
+
if (w.vault && current !== 'review') api('/api/review').then((d) => badge(d.count), () => {});
|
|
2701
|
+
if (typeof w.welcome_done !== 'boolean' || w.welcome_done || wg.open) { wg.done = w.welcome_done === true; return null; }
|
|
2702
|
+
if (!w.vault) return wgAuto();
|
|
2703
|
+
return api('/api/setup').then((d) => {
|
|
2704
|
+
if (!wg.open && d.vault && !(d.connect_skipped || wgConnected(d))) wgAuto(d);
|
|
2705
|
+
});
|
|
2706
|
+
}).catch(() => {});
|
|
2707
|
+
idle();
|
|
2708
|
+
poll(true);
|
|
2709
|
+
// the app starts the automatic history import by itself: the job line shows it within 15 s
|
|
2710
|
+
setInterval(() => { if (!dead && !document.hidden) poll(true); }, 15000);
|
|
2711
|
+
document.addEventListener('visibilitychange', () => { if (!dead && !document.hidden) poll(true); }); // shown again: the job line at once
|
|
2712
|
+
})();
|