@mevdragon/vidfarm-devcli 0.18.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.agents/skills/vidfarm-media/SKILL.md +41 -4
  2. package/SKILL.director.md +17 -3
  3. package/SKILL.platform.md +3 -3
  4. package/demo/dist/app.js +69 -69
  5. package/demo/dist/favicon.ico +0 -0
  6. package/dist/src/app.js +1550 -187
  7. package/dist/src/cli.js +227 -7
  8. package/dist/src/devcli/clip-store.js +29 -2
  9. package/dist/src/devcli/clips.js +52 -9
  10. package/dist/src/devcli/composition-edit.js +262 -0
  11. package/dist/src/devcli/timeline-edit.js +283 -0
  12. package/dist/src/editor-chat.js +29 -6
  13. package/dist/src/frontend/discover-client.js +130 -0
  14. package/dist/src/frontend/discover-store.js +23 -0
  15. package/dist/src/frontend/file-directory.js +744 -0
  16. package/dist/src/frontend/template-editor-chat.js +22 -19
  17. package/dist/src/landing-page.js +24 -7
  18. package/dist/src/page-shell.js +25 -1
  19. package/dist/src/reskin/agency-page.js +1 -1
  20. package/dist/src/reskin/calendar-page.js +2 -1
  21. package/dist/src/reskin/chat-page.js +319 -72
  22. package/dist/src/reskin/discover-page.js +486 -31
  23. package/dist/src/reskin/document.js +1171 -384
  24. package/dist/src/reskin/help-page.js +1 -0
  25. package/dist/src/reskin/inpaint-page.js +10 -4
  26. package/dist/src/reskin/library-page.js +918 -220
  27. package/dist/src/reskin/login-page.js +6 -6
  28. package/dist/src/reskin/pricing-page.js +2 -0
  29. package/dist/src/reskin/settings-page.js +55 -10
  30. package/dist/src/reskin/theme.js +337 -17
  31. package/dist/src/services/clip-curation/gemini.js +5 -0
  32. package/dist/src/services/clip-curation/hunt.js +79 -1
  33. package/dist/src/services/clip-curation/index.js +2 -1
  34. package/dist/src/services/clip-curation/local-agent.js +4 -3
  35. package/dist/src/services/clip-curation/media-select.js +85 -0
  36. package/dist/src/services/clip-curation/query.js +5 -1
  37. package/dist/src/services/clip-curation/refine.js +50 -20
  38. package/dist/src/services/clip-curation/scan.js +10 -3
  39. package/dist/src/services/clip-curation/taxonomy.js +3 -1
  40. package/dist/src/services/clip-curation/taxonomy.v1.json +13 -1
  41. package/dist/src/services/clip-records.js +14 -1
  42. package/dist/src/services/clip-search.js +43 -13
  43. package/dist/src/services/file-directory.js +114 -0
  44. package/dist/src/services/storage.js +24 -1
  45. package/dist/src/services/upstream.js +5 -5
  46. package/dist/src/template-editor-shell.js +16 -2
  47. package/package.json +1 -1
  48. package/public/assets/discover-client-app.js +1 -0
  49. package/public/assets/file-directory-app.js +2 -0
  50. package/public/assets/homepage-client-app.js +12 -12
  51. package/public/assets/page-runtime-client-app.js +24 -24
  52. package/src/assets/favicon.ico +0 -0
  53. package/src/assets/logo-vidfarm.png +0 -0
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // NOTE: the sidebar uses `.rk-sidebar*` class names — deliberately NOT `.rk-side*`
14
14
  // (that belongs to the settings page's own inner tab rail) so the two never clash.
15
- import { RESKIN_CSS, RESKIN_FONT_LINKS, RESKIN_PAGES } from "./theme.js";
15
+ import { RESKIN_CSS, RESKIN_FONT_LINKS } from "./theme.js";
16
16
  /** Minimal HTML escaper so reskin modules don't need to import app helpers. */
17
17
  export function rkEscape(value) {
18
18
  return String(value ?? "")
@@ -22,6 +22,17 @@ export function rkEscape(value) {
22
22
  .replace(/"/g, """)
23
23
  .replace(/'/g, "'");
24
24
  }
25
+ /** Canonical brand name + origin, used for <title>, meta tags, and social cards. */
26
+ export const BRAND_NAME = "VidFarm";
27
+ export const BRAND_ORIGIN = "https://vidfarm.cc";
28
+ export const BRAND_OG_IMAGE = `${BRAND_ORIGIN}/assets/logo-vidfarm.png`;
29
+ /** Normalize any page title to the canonical "VidFarm" branding. Older reskin
30
+ * modules pass "vidfarm reskin — X" / "vidfarm — X"; both collapse to "VidFarm — X". */
31
+ export function rkBrandTitle(raw) {
32
+ return String(raw ?? "")
33
+ .replace(/vidfarm reskin/gi, BRAND_NAME)
34
+ .replace(/\bvidfarm\b/gi, BRAND_NAME);
35
+ }
25
36
  /** The sidebar shows only the core app pages (not every reskinned page).
26
37
  * Other pages stay reachable from the /reskin gallery (brand link). */
27
38
  const SIDEBAR_NAV = [
@@ -32,59 +43,107 @@ const SIDEBAR_NAV = [
32
43
  { slug: "help", label: "Guides" },
33
44
  { slug: "settings", label: "Settings" }
34
45
  ];
35
- function renderSidebar(activeSlug) {
46
+ /** Title-case the local-part of an email as a display-name fallback. Kept inline
47
+ * so this module stays free of app-side imports (see file header). */
48
+ function rkNameFromEmail(email) {
49
+ const local = email.trim().toLowerCase().split("@", 1)[0] || email.trim().toLowerCase();
50
+ const words = local
51
+ .split(/[^a-z0-9]+/i)
52
+ .filter(Boolean)
53
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1));
54
+ return words.join(" ") || email.trim();
55
+ }
56
+ /** The subtle name + email block pinned to the sidebar foot. Renders nothing
57
+ * when signed out (no email), so the sidebar is unchanged for visitors. */
58
+ function renderSidebarAccount(account) {
59
+ const email = account?.email?.trim() || "";
60
+ if (!email)
61
+ return "";
62
+ const name = account?.name?.trim() || rkNameFromEmail(email);
63
+ return `<div class="rk-sidebar-account" title="Signed in as ${rkEscape(email)}">
64
+ <div class="rk-sidebar-account-name">${rkEscape(name)}</div>
65
+ <div class="rk-sidebar-account-email">${rkEscape(email)}</div>
66
+ </div>`;
67
+ }
68
+ function renderSidebar(activeSlug, account) {
36
69
  const items = SIDEBAR_NAV.map((p) => {
37
70
  const active = p.slug === activeSlug ? " is-active" : "";
38
71
  return `<a class="rk-sidebar-item${active}" href="/${p.slug}"${p.slug === activeSlug ? ` aria-current="page"` : ""}>${p.label}</a>`;
39
72
  }).join("");
73
+ // Phone nav: a CSS checkbox-hack hamburger (no JS). At ≤640px the horizontal
74
+ // strip hides the nav behind the burger and drops it into a vertical dropdown
75
+ // when the box is checked — the sibling `~` combinator needs the checkbox to
76
+ // precede both the nav and the account block, hence the order below.
40
77
  return `<aside class="rk-sidebar">
41
- <a class="rk-sidebar-brand" href="/discover"><span class="rk-brand-mark">V</span>vidfarm</a>
78
+ <a class="rk-sidebar-brand" href="/discover"><span class="rk-brand-mark">V</span>VidFarm</a>
79
+ <input type="checkbox" id="rk-navtoggle" class="rk-nav-toggle-cb" hidden>
80
+ <label for="rk-navtoggle" class="rk-nav-burger" aria-label="Toggle navigation" aria-controls="rk-navtoggle">
81
+ <svg viewBox="0 0 20 20" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M3 6h14M3 10h14M3 14h14"/></svg>
82
+ </label>
42
83
  <nav class="rk-sidebar-nav" aria-label="Reskin pages">
43
84
  ${items}
44
85
  </nav>
86
+ ${renderSidebarAccount(account)}
45
87
  </aside>`;
46
88
  }
47
89
  /** Draggable chat FAB (defaults to the old sidebar-foot spot, bottom-left) +
48
90
  * the popup AI chat panel it toggles. Sample chat only — this is the design
49
91
  * sandbox, so the panel demos the UI rather than hitting a live agent. The
50
92
  * old "compare with live page" link survives as the ↗ tool in the panel head. */
51
- function renderChatDock(activeSlug) {
52
- const page = RESKIN_PAGES.find((p) => p.slug === activeSlug);
53
- const label = rkEscape(page?.label ?? "vidfarm");
93
+ export function renderChatDock(activeSlug) {
94
+ // In the /editor left-dock, the brand block is replaced by an obvious
95
+ // "Back to Library" button — the editor is a focused workspace, so its
96
+ // primary chrome affordance is getting back out, not re-stating the brand.
97
+ const head = activeSlug === "editor"
98
+ ? `<a class="rk-aichat-back" id="rkAichatBack" href="/library" title="Back to your library">
99
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5"/><path d="m12 19-7-7 7-7"/></svg>
100
+ <span>Back to Library</span>
101
+ </a>`
102
+ : `<span class="rk-brand-mark">V</span>
103
+ <div class="rk-aichat-head-main">
104
+ <div class="rk-aichat-title">VidFarm AI</div>
105
+ <div class="rk-aichat-sub">on your own AI keys</div>
106
+ </div>`;
54
107
  return `<button class="rk-fab" id="rkFab" type="button" aria-label="Open AI chat" aria-expanded="false" aria-controls="rkAichat" title="Chat with vidfarm AI — drag to move">
55
108
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
56
109
  </button>
57
110
  <aside class="rk-aichat has-files" id="rkAichat" hidden aria-label="AI chat panel">
58
111
  <div class="rk-aichat-files" id="rkAichatFiles" aria-label="Files">
59
- <div class="rk-aichat-crumbs" id="rkAichatCrumbs" aria-label="Current folder"></div>
60
- <div class="rk-aichat-files-body" id="rkAichatFilesBody"></div>
61
- <div class="rk-aichat-drop" id="rkAichatDrop" hidden>
62
- <input type="file" id="rkAichatUploadInput" multiple hidden>
63
- <div class="rk-aichat-drop-text" id="rkAichatDropText">Drop files to upload</div>
64
- <button type="button" class="rk-aichat-drop-btn" id="rkAichatUploadBtn">Upload files</button>
112
+ <div class="rk-aichat-files-head">
113
+ <span class="rk-aichat-files-title">Your files</span>
114
+ <button class="rk-aichat-tool" id="rkFilesClose" type="button" title="Minimize files" aria-label="Minimize files">
115
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/><path d="m16 15-3-3 3-3"/></svg>
116
+ </button>
65
117
  </div>
118
+ <div class="rk-aichat-files-mount" id="rkAichatFilesMount" data-rk-directory data-mode="attach"></div>
119
+ </div>
120
+ <div class="rk-aichat-history" id="rkAichatHistory" aria-label="Chat history">
121
+ <div class="rk-aichat-hist-head">Chat history</div>
122
+ <div class="rk-aichat-hist-body" id="rkAichatHistBody"></div>
66
123
  </div>
67
124
  <div class="rk-aichat-main">
68
125
  <header class="rk-aichat-head">
69
- <span class="rk-brand-mark">V</span>
70
- <div class="rk-aichat-head-main">
71
- <div class="rk-aichat-title">Vidfarm AI</div>
72
- <div class="rk-aichat-sub">sample chat</div>
73
- </div>
74
- <button class="rk-aichat-tool is-on" id="rkFilesToggle" type="button" title="Toggle My Files" aria-label="Toggle My Files" aria-pressed="true">
75
- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>
126
+ ${head}
127
+ <button class="rk-aichat-tool" id="rkHistoryToggle" type="button" title="Chat history" aria-label="Toggle chat history" aria-pressed="false">
128
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l3 2"/></svg>
129
+ </button>
130
+ <button class="rk-aichat-tool" id="rkNewChat" type="button" title="New chat" aria-label="Start a new chat">
131
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z"/></svg>
76
132
  </button>
77
133
  <button class="rk-aichat-tool" id="rkAichatMin" type="button" title="Minimize" aria-label="Minimize chat">—</button>
78
134
  </header>
79
135
  <div class="rk-aichat-log" id="rkAichatLog">
80
- <div class="rk-aichat-msg is-ai">Hi! I'm the vidfarm assistant. Ask me anything about the ${label} page — or attach a file from the Files panel on the left.</div>
81
- <div class="rk-aichat-msg is-user">What changed in this reskin?</div>
82
- <div class="rk-aichat-msg is-ai">This page was ported into the farmville design system — honey-gold accent, soft rounded cards, the shared rk- primitives — while keeping the layout one-to-one with the live page.</div>
136
+ <div class="rk-aichat-msg is-ai">Hi! I'm the vidfarm assistant. I can take real actions on your account browse your files, hit vidfarm APIs, kick off renders. Ask me anything, or attach a file from the panel on the left.</div>
83
137
  </div>
84
138
  <div class="rk-aichat-chips" id="rkAichatChips"></div>
85
139
  <form class="rk-aichat-composer" id="rkAichatForm">
86
- <input class="rk-input" id="rkAichatInput" placeholder="Ask the vidfarm AI…" autocomplete="off">
87
- <button class="rk-btn rk-btn-gold rk-btn-sm" type="submit">Send</button>
140
+ <textarea class="rk-aichat-field" id="rkAichatInput" rows="3" placeholder="Ask the vidfarm AI…" autocomplete="off"></textarea>
141
+ <div class="rk-aichat-composer-actions">
142
+ <button class="rk-aichat-attach" id="rkAichatAttach" type="button" title="Attach a file" aria-label="Attach a file">
143
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
144
+ </button>
145
+ <button class="rk-btn rk-btn-gold rk-btn-sm" type="submit">Send</button>
146
+ </div>
88
147
  </form>
89
148
  </div>
90
149
  </aside>`;
@@ -95,15 +154,26 @@ function renderChatDock(activeSlug) {
95
154
  * on the left it replaces the sidebar nav (body.rk-chat-left). Open state
96
155
  * survives page navigation via sessionStorage. Plain IIFE — no backticks or
97
156
  * dollar-brace inside (it is embedded in a template literal). */
98
- const RESKIN_CHROME_SCRIPT = `(() => {
157
+ export const RESKIN_CHROME_SCRIPT = `(() => {
99
158
  var fab = document.getElementById('rkFab');
100
159
  var panel = document.getElementById('rkAichat');
101
160
  if (!fab || !panel) return;
161
+ // Editor dock mode: the /editor shell mounts this chat as a permanent, always-
162
+ // open LEFT column (no floating FAB) — reusing the exact same agentic dock. On
163
+ // narrow screens it degrades back to the floating FAB.
164
+ var isEditorDock = !!document.querySelector('[data-rk-editor-dock]');
165
+ var editorDockWide = isEditorDock && (typeof window.matchMedia !== 'function' || window.matchMedia('(min-width: 1025px)').matches);
166
+ if (isEditorDock) fab.hidden = true;
102
167
  var minBtn = document.getElementById('rkAichatMin');
103
168
  var form = document.getElementById('rkAichatForm');
104
169
  var input = document.getElementById('rkAichatInput');
105
170
  var log = document.getElementById('rkAichatLog');
106
171
  var MARGIN = 10;
172
+ // On the dedicated /chat page the panel's chat column is redundant (the page
173
+ // IS the chat), so we hide the floating FAB and instead let the composer's
174
+ // attach button open the panel in FILES-ONLY mode (just the file explorer).
175
+ var isChatPage = !!document.querySelector('.rk-chat-page');
176
+ if (isChatPage) fab.hidden = true;
107
177
 
108
178
  function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
109
179
 
@@ -130,18 +200,37 @@ const RESKIN_CHROME_SCRIPT = `(() => {
130
200
  document.body.classList.toggle('rk-chat-left', !panel.hidden && !onRight);
131
201
  }
132
202
 
133
- function openPanel() {
203
+ function openPanel(filesOnly) {
134
204
  panel.hidden = false;
205
+ panel.classList.toggle('is-files-only', !!filesOnly);
135
206
  fab.classList.add('is-open');
136
207
  fab.setAttribute('aria-expanded', 'true');
137
- anchorPanel();
138
- try { sessionStorage.setItem('rk-chat-open', '1'); } catch (e) {}
208
+ if (filesOnly) {
209
+ // slim left-hand drawer that replaces the sidebar (like the normal dock),
210
+ // so it never covers the centered chat column's composer / Send button
211
+ setLeftMode('files');
212
+ panel.classList.remove('is-right');
213
+ document.body.classList.add('rk-chat-left');
214
+ } else {
215
+ anchorPanel();
216
+ // On short / narrow screens the left drawer stacks ABOVE the chat and
217
+ // crushes the log + composer. Start collapsed to the chat column there;
218
+ // the user can still open Files/History from the header toggles.
219
+ try {
220
+ if (window.matchMedia && window.matchMedia('(max-width:700px)').matches) setLeftMode('');
221
+ } catch (e) {}
222
+ }
223
+ try { sessionStorage.setItem('rk-chat-open', filesOnly ? 'files' : '1'); } catch (e) {}
224
+ if (!filesOnly) loadBoot();
139
225
  refreshFilesOnOpen();
140
- if (input) input.focus();
226
+ if (!filesOnly && input) input.focus();
141
227
  }
142
228
 
143
229
  function closePanel() {
230
+ // Editor dock (wide) is a permanent column — minimize / Escape can't close it.
231
+ if (editorDockWide) return;
144
232
  panel.hidden = true;
233
+ panel.classList.remove('is-files-only');
145
234
  fab.classList.remove('is-open');
146
235
  fab.setAttribute('aria-expanded', 'false');
147
236
  document.body.classList.remove('rk-chat-left');
@@ -198,371 +287,796 @@ const RESKIN_CHROME_SCRIPT = `(() => {
198
287
  el.textContent = text;
199
288
  log.appendChild(el);
200
289
  log.scrollTop = log.scrollHeight;
290
+ return el;
201
291
  }
202
- if (form) form.addEventListener('submit', function (e) {
203
- e.preventDefault();
204
- var v = (input.value || '').trim();
205
- var picked = selected.slice();
206
- if (!v && !picked.length) return;
207
- var line = v;
208
- if (picked.length) {
209
- var names = picked.map(function (f) { return f.name; }).join(', ');
210
- line = (v ? v + ' ' : '') + '(attached: ' + names + ')';
211
- }
212
- bubble('is-user', line);
213
- input.value = '';
214
- clearChips();
215
- setTimeout(function () {
216
- bubble('is-ai', picked.length
217
- ? 'Got the ' + picked.length + ' file' + (picked.length > 1 ? 's' : '') + ' from your ' + rootLabel(fstate.root) + ' — on the live app I would use ' + (picked.length > 1 ? 'them' : 'it') + ' in the conversation. This reskin panel is a sample, so replies are canned.'
218
- : "I'm the sample chat in the reskin sandbox, so replies here are canned — on the live app this panel wires up to the vidfarm agent.");
219
- }, 450);
220
- });
292
+ function logBottom() { if (log) log.scrollTop = log.scrollHeight; }
221
293
 
222
- // ─── My Files drawer: real directory navigation over my_files/ + temp/ ───
223
- var filesPane = document.getElementById('rkAichatFiles');
224
- var crumbsEl = document.getElementById('rkAichatCrumbs');
225
- var filesBody = document.getElementById('rkAichatFilesBody');
226
- var chipsEl = document.getElementById('rkAichatChips');
227
- var filesToggle = document.getElementById('rkFilesToggle');
228
- var dropEl = document.getElementById('rkAichatDrop');
229
- var dropText = document.getElementById('rkAichatDropText');
230
- var uploadInput = document.getElementById('rkAichatUploadInput');
231
- var uploadBtn = document.getElementById('rkAichatUploadBtn');
232
- var selected = [];
233
- var uploading = false, uploadMsg = '';
234
-
235
- var ROOTS = {
236
- my_files: { url: '/api/v1/user/me/attachments', key: 'attachments', label: 'My Files' },
237
- temp: { url: '/api/v1/user/me/temporary-files', key: 'files', label: 'Temp' },
238
- // Raws = the reusable clip/source library (renamed clips→raws). Flat list
239
- // (no folders); items have a clip shape, so they get their own normalizer.
240
- raws: { url: '/raws/feed', key: 'clips', label: 'Raws', norm: normRaw }
241
- };
242
- // The sources are surfaced as top-level FOLDERS of one virtual root (no source
243
- // tabs) — navigate into them natively like any folder.
244
- var VROOTS = [{ key: 'my_files', label: 'My Files' }, { key: 'temp', label: 'Temp' }, { key: 'raws', label: 'Raws' }];
245
- var fstate = {
246
- root: '', // '' = virtual root (lists My Files + Temp + Raws); else a ROOTS key
247
- path: { my_files: '', temp: '', raws: '' },
248
- data: { my_files: null, temp: null, raws: null },
249
- status: { my_files: 'idle', temp: 'idle', raws: 'idle' } // idle|loading|ready|auth|error
250
- };
294
+ // Remember the opening greeting so "New chat" can restore a fresh thread.
295
+ var GREETING = (function () {
296
+ var first = log && log.querySelector('.rk-aichat-msg.is-ai');
297
+ return first ? first.textContent : "Hi! I'm the vidfarm assistant — ask me anything about your videos, clips, and posts.";
298
+ })();
251
299
 
252
- function rootLabel(root) { return ROOTS[root] ? ROOTS[root].label : 'Files'; }
253
- function normFolder(v) {
254
- return String(v || '').split('/').map(function (s) { return s.trim(); }).filter(Boolean).join('/');
300
+ // ─── real agentic chat: wired to the live editor-chat backend ──────────────
301
+ // Boot (endpoint + api key + brainstorm template) is fetched lazily on first
302
+ // open from /chat-dock/boot (cookie-authed). Tool calls surface as first-class
303
+ // actions: every http_request becomes a clickable card that opens a modal with
304
+ // the exact request + response, exactly like the /editor chat.
305
+ var BOOT = null, BOOT_STATE = 'idle'; // idle|loading|ready|anon|error
306
+ var ENDPOINT = '/api/v1/editor-chat', API_KEY = null, TEMPLATE = null, CACHED = null;
307
+ var THREADS_URL = '/api/v1/editor-chat/threads', TEMPLATE_ID = 'chat-brainstorm';
308
+ var convo = []; // [{role,text}] running conversation
309
+ var threadId = null; // set on first send / when opening a saved thread
310
+ var busy = false;
311
+ var pendingAbort = null; // AbortController for the in-flight reply (Stop button)
312
+
313
+ // On the /editor dock the chat MUST be scoped to the OPEN composition, not the
314
+ // generic brainstorm boot — otherwise the agent has no fork id and can't run
315
+ // video_context / editor_action (it guesses "chat-brainstorm" and gives up).
316
+ // The editor page already embeds the composition identity in #hf-boot; use it
317
+ // as the template context (exactly like the SPA chat's body.template) so
318
+ // thread_template_id is the real template_… id and create_video is dropped in
319
+ // favor of the edit tools. Set eagerly so the very first send is correct even
320
+ // before /chat-dock/boot resolves (that fetch still supplies the api key).
321
+ var EDITOR_TEMPLATE = null;
322
+ if (isEditorDock) {
323
+ try {
324
+ var hfBootEl = document.getElementById('hf-boot');
325
+ var hfBoot = hfBootEl ? JSON.parse(hfBootEl.textContent || '{}') : null;
326
+ var editorTplId = hfBoot && (hfBoot.templateId || hfBoot.compositionId);
327
+ if (editorTplId) {
328
+ EDITOR_TEMPLATE = {
329
+ page: 'docs', tracerId: null, tracers: [], defaultRequestTracer: null,
330
+ templateId: editorTplId,
331
+ templateSlug: (hfBoot && (hfBoot.slugId || hfBoot.templateId)) || editorTplId,
332
+ templateTitle: (hfBoot && hfBoot.title) || 'Studio',
333
+ templateDescription: '', docsRoutes: []
334
+ };
335
+ TEMPLATE = EDITOR_TEMPLATE;
336
+ TEMPLATE_ID = editorTplId;
337
+ }
338
+ } catch (e) {}
255
339
  }
256
- function normItem(raw) {
257
- var id = raw.id || raw.attachment_id || raw.file_id || '';
258
- var name = raw.fileName || raw.file_name || '';
259
- if (!id || !name) return null;
260
- return {
261
- id: id, name: name,
262
- contentType: raw.contentType || raw.content_type || '',
263
- viewUrl: raw.viewUrl || raw.view_url || '',
264
- sizeBytes: typeof raw.sizeBytes === 'number' ? raw.sizeBytes : raw.size_bytes,
265
- folderPath: normFolder(raw.folderPath || raw.folder_path || '')
266
- };
340
+
341
+ function genId(p) { return p + '-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8); }
342
+ function setBusy(v) {
343
+ busy = v;
344
+ // While a reply streams, the Send button becomes an interruptive Stop
345
+ // (stays clickable so the user can abort); it flips back to Send when done.
346
+ if (form) { var b = form.querySelector('button[type=submit]'); if (b) { b.textContent = v ? 'Stop' : 'Send'; b.classList.toggle('is-stop', v); } }
347
+ if (newChatBtn) newChatBtn.disabled = v;
267
348
  }
268
- function fmtBytes(b) {
269
- if (!b || b <= 0) return '';
270
- var u = ['B', 'KB', 'MB', 'GB'], v = b, i = 0;
271
- while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
272
- return (v >= 10 || i === 0 ? Math.round(v) : v.toFixed(1)) + ' ' + u[i];
273
- }
274
- function fmtDur(s) {
275
- if (typeof s !== 'number' || !(s > 0)) return '';
276
- s = Math.round(s); var m = Math.floor(s / 60), r = s % 60;
277
- return m + ':' + (r < 10 ? '0' + r : r);
278
- }
279
- // Raws feed items are clips (clip_id / source_filename / view_url / duration),
280
- // a different shape than attachments — map them onto the file-row model.
281
- function normRaw(raw) {
282
- var id = raw.clip_id || raw.id || '';
283
- if (!id) return null;
284
- return {
285
- id: id,
286
- name: raw.source_filename || raw.description || 'clip',
287
- contentType: 'video/mp4',
288
- viewUrl: raw.view_url || raw.viewUrl || '',
289
- thumbUrl: raw.thumbnail_url || raw.thumbnailUrl || '',
290
- metaText: fmtDur(raw.duration_sec),
291
- sizeBytes: undefined,
292
- folderPath: ''
293
- };
349
+ function clientContext() {
350
+ var now = new Date(), local = null, tz = null;
351
+ try { local = new Intl.DateTimeFormat(undefined, { dateStyle: 'full', timeStyle: 'long' }).format(now); } catch (e) { local = now.toString(); }
352
+ try { tz = (Intl.DateTimeFormat().resolvedOptions().timeZone) || null; } catch (e) { tz = null; }
353
+ return { currentDateTime: now.toISOString(), localDateTime: local, timeZone: tz };
294
354
  }
295
- function immediateFolders(data, current) {
296
- var cur = normFolder(current);
297
- var prefix = cur ? cur + '/' : '';
298
- var names = {};
299
- function consider(fp) {
300
- var n = normFolder(fp);
301
- if (!n || (cur && n === cur) || n.indexOf(prefix) !== 0) return;
302
- var child = n.slice(prefix.length).split('/')[0];
303
- if (child) names[child] = prefix + child;
304
- }
305
- (data.folders || []).forEach(consider);
306
- (data.items || []).forEach(function (it) { consider(it.folderPath); });
307
- return Object.keys(names).sort().map(function (n) { return { name: n, path: names[n] }; });
355
+ // The live composition snapshot (fork id, layers, DNA) the SPA editor bundle
356
+ // exposes on window.__vidfarmEditorAction.getSnapshot(). Injected into the
357
+ // outgoing user turn verbatim to what the SPA's own chat sends — so the agent
358
+ // knows which fork to read (video_context) and mutate (editor_action). Only the
359
+ // /editor dock has this bridge; elsewhere it returns ''.
360
+ function editorContextBlock() {
361
+ if (!isEditorDock) return '';
362
+ var bridge = (typeof window !== 'undefined') ? window.__vidfarmEditorAction : null;
363
+ if (!bridge || typeof bridge.getSnapshot !== 'function') return '';
364
+ var snap; try { snap = bridge.getSnapshot(); } catch (e) { snap = null; }
365
+ if (!snap) return '';
366
+ try { return '\\n\\n<editor_context>\\n' + JSON.stringify(snap, null, 2) + '\\n</editor_context>'; }
367
+ catch (e) { return ''; }
308
368
  }
309
-
310
- function loadRoot(root, force) {
311
- if (!ROOTS[root]) return;
312
- if (!force && fstate.status[root] === 'ready') { renderFiles(); return; }
313
- fstate.status[root] = 'loading';
314
- renderFiles();
315
- fetch(ROOTS[root].url, { credentials: 'same-origin', headers: { accept: 'application/json' } })
316
- .then(function (r) {
317
- if (r.status === 401 || r.status === 403) { fstate.status[root] = 'auth'; return null; }
318
- if (!r.ok) throw new Error('http ' + r.status);
319
- return r.json();
320
- })
369
+ function loadBoot() {
370
+ if (BOOT_STATE === 'ready' || BOOT_STATE === 'loading') return;
371
+ BOOT_STATE = 'loading';
372
+ fetch('/chat-dock/boot', { credentials: 'same-origin', headers: { accept: 'application/json' } })
373
+ .then(function (r) { return r.ok ? r.json() : null; })
321
374
  .then(function (j) {
322
- if (!j) { renderFiles(); return; }
323
- var raw = j[ROOTS[root].key] || [];
324
- var norm = ROOTS[root].norm || normItem;
325
- var items = [];
326
- for (var i = 0; i < raw.length; i++) { var n = norm(raw[i]); if (n) items.push(n); }
327
- fstate.data[root] = { items: items, folders: j.folders || [] };
328
- fstate.status[root] = 'ready';
329
- renderFiles();
375
+ var b = j && j.editorChat;
376
+ if (!b) { BOOT_STATE = 'anon'; return; }
377
+ BOOT = b;
378
+ ENDPOINT = b.apiUrl || ENDPOINT;
379
+ API_KEY = b.vidfarmApiKey || null;
380
+ // On the editor dock keep the composition-scoped template from #hf-boot —
381
+ // the generic brainstorm boot would strand the agent without a fork id.
382
+ if (EDITOR_TEMPLATE) { TEMPLATE = EDITOR_TEMPLATE; TEMPLATE_ID = EDITOR_TEMPLATE.templateId; }
383
+ else { TEMPLATE = b.template || null; TEMPLATE_ID = (TEMPLATE && TEMPLATE.templateId) || TEMPLATE_ID; }
384
+ CACHED = b.cachedContext || null;
385
+ THREADS_URL = b.threadsUrl || THREADS_URL;
386
+ BOOT_STATE = 'ready';
387
+ loadThreads();
330
388
  })
331
- .catch(function () { fstate.status[root] = 'error'; renderFiles(); });
332
- }
333
-
334
- function fstateNode(text, opts) {
335
- var wrap = document.createElement('div');
336
- wrap.className = 'rk-aichat-fstate';
337
- var p = document.createElement('div');
338
- p.textContent = text;
339
- wrap.appendChild(p);
340
- if (opts && opts.href) {
341
- var a = document.createElement('a');
342
- a.href = opts.href;
343
- a.textContent = opts.linkText || 'Open';
344
- wrap.appendChild(a);
389
+ .catch(function () { BOOT_STATE = 'error'; });
390
+ }
391
+
392
+ // ── first-class HTTP action card + request/response modal ──
393
+ function fmtBody(v) {
394
+ if (v === null || v === undefined) return '';
395
+ if (typeof v === 'string') { try { return JSON.stringify(JSON.parse(v), null, 2); } catch (e) { return v; } }
396
+ try { return JSON.stringify(v, null, 2); } catch (e) { return String(v); }
397
+ }
398
+ function copyText(t) {
399
+ try { if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(t); return; } } catch (e) {}
400
+ try { var ta = document.createElement('textarea'); ta.value = t; ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); } catch (e) {}
401
+ }
402
+ var COPY_SVG = '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
403
+ var CARET_SVG = '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m7 4 6 6-6 6"/></svg>';
404
+
405
+ // Expandable/collapsible JSON tree — a recursive walk of the value with a
406
+ // per-path collapsed set (re-rendered on toggle). Mirrors the /editor chat's
407
+ // JsonViewer: indent depth*16+10px, quoted-key + colon, [ … ]/{ … } collapsed
408
+ // previews, per-line hover copy button.
409
+ function jsonViewer(value) {
410
+ var collapsed = {};
411
+ var wrap = document.createElement('div'); wrap.className = 'rk-aichat-json';
412
+ var bar = document.createElement('div'); bar.className = 'rk-aichat-json-bar';
413
+ var expand = document.createElement('button'); expand.type = 'button'; expand.className = 'rk-aichat-json-all'; expand.textContent = 'Collapse all';
414
+ var copyAll = document.createElement('button'); copyAll.type = 'button'; copyAll.className = 'rk-aichat-json-all'; copyAll.textContent = 'Copy all';
415
+ bar.appendChild(expand); bar.appendChild(copyAll);
416
+ var scroll = document.createElement('div'); scroll.className = 'rk-aichat-json-scroll';
417
+ wrap.appendChild(bar); wrap.appendChild(scroll);
418
+ function fmt(v) { if (typeof v === 'string') return JSON.stringify(v); if (typeof v === 'number' || typeof v === 'boolean') return String(v); if (v === null) return 'null'; return JSON.stringify(v); }
419
+ function lineRow(text, depth) {
420
+ var row = document.createElement('div'); row.className = 'rk-aichat-json-line'; row.style.paddingLeft = (depth * 16 + 10) + 'px';
421
+ var cp = document.createElement('button'); cp.type = 'button'; cp.className = 'rk-aichat-json-copy'; cp.setAttribute('aria-label', 'Copy line'); cp.innerHTML = COPY_SVG;
422
+ cp.addEventListener('click', function () { copyText(text); });
423
+ var sp = document.createElement('span'); sp.className = 'rk-aichat-json-text'; sp.textContent = text;
424
+ row.appendChild(cp); row.appendChild(sp); return row;
425
+ }
426
+ function toggleRow(text, depth, path, open) {
427
+ var row = document.createElement('div'); row.className = 'rk-aichat-json-line is-toggle'; row.style.paddingLeft = (depth * 16 + 10) + 'px';
428
+ var t = document.createElement('button'); t.type = 'button'; t.className = 'rk-aichat-json-caret'; t.setAttribute('data-open', open ? 'true' : 'false'); t.innerHTML = CARET_SVG;
429
+ t.addEventListener('click', function () { if (open) collapsed[path] = true; else delete collapsed[path]; render(); });
430
+ var sp = document.createElement('span'); sp.className = 'rk-aichat-json-text'; sp.textContent = text;
431
+ row.appendChild(t); row.appendChild(sp); return row;
345
432
  }
346
- if (opts && opts.retry) {
347
- var btn = document.createElement('button');
348
- btn.type = 'button';
349
- btn.textContent = 'Try again';
350
- btn.addEventListener('click', function () { loadRoot(fstate.root, true); });
351
- wrap.appendChild(btn);
433
+ function walk(v, depth, prefix, isLast, path) {
434
+ var comma = isLast ? '' : ',';
435
+ if (Array.isArray(v)) {
436
+ if (!v.length) { scroll.appendChild(lineRow(prefix + '[]' + comma, depth)); return; }
437
+ if (collapsed[path]) { scroll.appendChild(toggleRow(prefix + '[ … ]' + comma, depth, path, false)); return; }
438
+ scroll.appendChild(toggleRow(prefix + '[', depth, path, true));
439
+ for (var i = 0; i < v.length; i++) walk(v[i], depth + 1, '', i === v.length - 1, path + '.' + i);
440
+ scroll.appendChild(lineRow(']' + comma, depth));
441
+ } else if (v && typeof v === 'object') {
442
+ var keys = Object.keys(v);
443
+ if (!keys.length) { scroll.appendChild(lineRow(prefix + '{}' + comma, depth)); return; }
444
+ if (collapsed[path]) { scroll.appendChild(toggleRow(prefix + '{ … }' + comma, depth, path, false)); return; }
445
+ scroll.appendChild(toggleRow(prefix + '{', depth, path, true));
446
+ for (var k = 0; k < keys.length; k++) {
447
+ var key = keys[k], cp = JSON.stringify(key) + ': ', last = k === keys.length - 1, child = v[key];
448
+ if (child && typeof child === 'object') walk(child, depth + 1, cp, last, path + '.' + key);
449
+ else scroll.appendChild(lineRow(cp + fmt(child) + (last ? '' : ','), depth + 1));
450
+ }
451
+ scroll.appendChild(lineRow('}' + comma, depth));
452
+ } else {
453
+ scroll.appendChild(lineRow(prefix + fmt(v) + comma, depth));
454
+ }
352
455
  }
456
+ function render() { scroll.innerHTML = ''; walk(value, 0, '', true, 'root'); }
457
+ var allCollapsed = false;
458
+ function markAll(v, path) {
459
+ if (Array.isArray(v)) { if (v.length) { collapsed[path] = true; for (var i = 0; i < v.length; i++) markAll(v[i], path + '.' + i); } }
460
+ else if (v && typeof v === 'object') { var ks = Object.keys(v); if (ks.length) { collapsed[path] = true; for (var k = 0; k < ks.length; k++) markAll(v[ks[k]], path + '.' + ks[k]); } }
461
+ }
462
+ expand.addEventListener('click', function () {
463
+ allCollapsed = !allCollapsed;
464
+ if (allCollapsed) { markAll(value, 'root'); delete collapsed['root']; expand.textContent = 'Expand all'; }
465
+ else { collapsed = {}; expand.textContent = 'Collapse all'; }
466
+ render();
467
+ });
468
+ copyAll.addEventListener('click', function () { copyText(fmtBody(value)); });
469
+ render();
353
470
  return wrap;
354
471
  }
355
-
356
- // Generic folder row. onOpen is called on click; sub is an optional caption
357
- // under the name (used for the virtual roots to show their file count / hint).
358
- function folderRow(label, onOpen, sub) {
472
+ function escapeHtml(s) { return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
473
+ // Render inline markdown in assistant text: bold, italic, markdown links and
474
+ // bare absolute URLs → HTML (mirrors the /editor chat's renderInlineMarkdown).
475
+ // Order matters: **bold** before *italic*; links before bare-URL autolinking
476
+ // (an href="…" is never preceded by whitespace/'(' so it won't double-link).
477
+ function linkify(text) {
478
+ var html = escapeHtml(text);
479
+ html = html.replace(/\\*\\*([^*]+)\\*\\*/g, '<strong>$1</strong>');
480
+ html = html.replace(/(^|[^\\w*])\\*([^*\\n]+)\\*/g, '$1<em>$2</em>');
481
+ html = html.replace(/(^|[^\\w_])_([^_\\n]+)_/g, '$1<em>$2</em>');
482
+ html = html.replace(/\\[([^\\]]+)\\]\\((https?:\\/\\/[^\\s)]+)\\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
483
+ html = html.replace(/(^|[\\s(])(https?:\\/\\/[^\\s<]+[^<.,:;"')\\]\\s])/g, '$1<a href="$2" target="_blank" rel="noopener noreferrer">$2</a>');
484
+ return html;
485
+ }
486
+ function openHttpModal(ex) {
487
+ var req = ex.request || {}, res = ex.response || {};
488
+ var status = typeof res.status === 'number' ? res.status : 0;
489
+ var isErr = status >= 400 || res.error;
490
+ var back = document.createElement('div');
491
+ back.className = 'rk-aichat-modal-back';
492
+ var modal = document.createElement('div');
493
+ modal.className = 'rk-aichat-modal';
494
+ var head = document.createElement('div');
495
+ head.className = 'rk-aichat-modal-head';
496
+ head.innerHTML = '<span class="rk-aichat-http-method">' + (req.method || 'GET') + '</span>'
497
+ + '<span class="rk-aichat-http-url"></span>'
498
+ + '<span class="rk-aichat-http-status" data-error="' + (isErr ? 'true' : 'false') + '">' + (status || '—') + (res.statusText ? ' ' + res.statusText : '') + '</span>'
499
+ + '<button type="button" class="rk-aichat-modal-x" aria-label="Close">&times;</button>';
500
+ head.querySelector('.rk-aichat-http-url').textContent = req.url || req.path || '';
501
+ var body = document.createElement('div');
502
+ body.className = 'rk-aichat-modal-body';
503
+ // A raw string block (URL, error text). Always plain <pre>.
504
+ function textBlock(label, text) {
505
+ if (!text) return;
506
+ var wrap = document.createElement('div'); wrap.className = 'rk-aichat-http-block';
507
+ var l = document.createElement('div'); l.className = 'rk-aichat-http-blabel'; l.textContent = label;
508
+ var pre = document.createElement('pre'); pre.className = 'rk-aichat-http-pre'; pre.textContent = text;
509
+ wrap.appendChild(l); wrap.appendChild(pre); body.appendChild(wrap);
510
+ }
511
+ // A body/headers block: collapsible JSON tree when structured, else <pre>.
512
+ function dataBlock(label, value) {
513
+ if (value === null || value === undefined || value === '') return;
514
+ var data = value;
515
+ if (typeof value === 'string') { try { var p = JSON.parse(value); if (p && typeof p === 'object') data = p; } catch (e) {} }
516
+ var wrap = document.createElement('div'); wrap.className = 'rk-aichat-http-block';
517
+ var l = document.createElement('div'); l.className = 'rk-aichat-http-blabel'; l.textContent = label;
518
+ wrap.appendChild(l);
519
+ if (data && typeof data === 'object') { wrap.appendChild(jsonViewer(data)); }
520
+ else { var pre = document.createElement('pre'); pre.className = 'rk-aichat-http-pre'; pre.textContent = (typeof value === 'string') ? value : fmtBody(value); wrap.appendChild(pre); }
521
+ body.appendChild(wrap);
522
+ }
523
+ function hasKeys(o) { return o && typeof o === 'object' && Object.keys(o).length > 0; }
524
+ if (ex.explanation) { var note = document.createElement('div'); note.className = 'rk-aichat-http-note'; note.textContent = ex.explanation; body.appendChild(note); }
525
+ textBlock('URL', req.url || req.path || '');
526
+ if (req.body !== undefined && req.body !== null && req.body !== '') dataBlock('Request', req.body);
527
+ if (res.error) textBlock('Response', res.error);
528
+ else dataBlock('Response', (res.body === undefined || res.body === null || res.body === '') ? '(empty)' : res.body);
529
+ if (hasKeys(res.headers)) dataBlock('Response headers', res.headers);
530
+ modal.appendChild(head); modal.appendChild(body); back.appendChild(modal);
531
+ function close() { if (back.parentNode) back.parentNode.removeChild(back); document.removeEventListener('keydown', onKey); }
532
+ function onKey(e) { if (e.key === 'Escape') { e.stopPropagation(); close(); } }
533
+ back.addEventListener('click', function (e) { if (e.target === back) close(); });
534
+ head.querySelector('.rk-aichat-modal-x').addEventListener('click', close);
535
+ document.addEventListener('keydown', onKey);
536
+ document.body.appendChild(back);
537
+ }
538
+ function httpCard(ex) {
539
+ var req = ex.request || {}, res = ex.response || {};
540
+ var status = typeof res.status === 'number' ? res.status : 0;
541
+ var isErr = status >= 400 || res.error;
359
542
  var b = document.createElement('button');
360
543
  b.type = 'button';
361
- b.className = 'rk-aichat-frow';
362
- var ic = document.createElement('span');
363
- ic.className = 'rk-aichat-fic rk-aichat-fic-folder';
364
- ic.textContent = '/';
365
- var main = document.createElement('span');
366
- main.className = 'rk-aichat-fmain';
367
- var name = document.createElement('span');
368
- name.className = 'rk-aichat-fname';
369
- name.textContent = label;
370
- main.appendChild(name);
371
- if (sub) {
372
- var meta = document.createElement('span');
373
- meta.className = 'rk-aichat-fmeta';
374
- meta.textContent = sub;
375
- main.appendChild(meta);
376
- }
377
- var chev = document.createElement('span');
378
- chev.className = 'rk-aichat-fadd';
379
- chev.textContent = 'Open ›';
380
- b.appendChild(ic); b.appendChild(main); b.appendChild(chev);
381
- b.addEventListener('click', onOpen);
544
+ b.className = 'rk-aichat-http';
545
+ var m = document.createElement('span'); m.className = 'rk-aichat-http-method'; m.textContent = req.method || 'GET';
546
+ var u = document.createElement('span'); u.className = 'rk-aichat-http-url';
547
+ var url = req.url || req.path || '';
548
+ u.textContent = url.replace(/^https?:\\/\\/[^/]+/, ''); u.title = url;
549
+ var s = document.createElement('span'); s.className = 'rk-aichat-http-status';
550
+ s.setAttribute('data-error', isErr ? 'true' : 'false'); s.textContent = status || '—';
551
+ b.appendChild(m); b.appendChild(u); b.appendChild(s);
552
+ b.addEventListener('click', function () { openHttpModal(ex); });
382
553
  return b;
383
554
  }
384
- // A virtual-root entry (My Files / Temp) — shows a live count once loaded.
385
- function vrootRow(v) {
386
- var sub = '';
387
- var st = fstate.status[v.key];
388
- var d = fstate.data[v.key];
389
- if (st === 'ready' && d) sub = d.items.length + (d.items.length === 1 ? ' file' : ' files');
390
- else if (st === 'loading') sub = 'Loading…';
391
- else if (st === 'auth') sub = 'Sign in to view';
392
- return folderRow(v.label, function () { enterRoot(v.key); }, sub);
555
+
556
+ // ── file preview: classify a file by content-type + extension ──
557
+ function fileKind(name, ct) {
558
+ ct = (ct || '').toLowerCase();
559
+ var ext = ((name || '').split('.').pop() || '').toLowerCase();
560
+ if (ct.indexOf('image/') === 0 || /^(png|jpe?g|gif|webp|svg|avif|bmp|heic|ico)$/.test(ext)) return 'image';
561
+ if (ct.indexOf('video/') === 0 || /^(mp4|mov|webm|m4v|mkv|ogv)$/.test(ext)) return 'video';
562
+ if (ct.indexOf('audio/') === 0 || /^(mp3|wav|m4a|aac|ogg|oga|flac|opus)$/.test(ext)) return 'audio';
563
+ if (ct.indexOf('application/pdf') === 0 || ext === 'pdf') return 'pdf';
564
+ if (ct.indexOf('json') >= 0 || ext === 'json') return 'json';
565
+ if (ext === 'md' || ext === 'markdown' || ct.indexOf('markdown') >= 0) return 'markdown';
566
+ if (ct.indexOf('text/') === 0 || /^(txt|csv|tsv|srt|vtt|log|xml|yaml|yml|ini|conf|html?)$/.test(ext)) return 'text';
567
+ return 'other';
393
568
  }
394
569
 
395
- function fileRow(it) {
396
- var b = document.createElement('button');
397
- b.type = 'button';
398
- b.className = 'rk-aichat-frow';
399
- var ic = document.createElement('span');
400
- ic.className = 'rk-aichat-fic rk-aichat-fic-file';
401
- if (it.thumbUrl) {
402
- var thumb = document.createElement('img'); thumb.src = it.thumbUrl; thumb.alt = ''; thumb.loading = 'lazy'; ic.appendChild(thumb);
403
- } else if (it.viewUrl && it.contentType.indexOf('image/') === 0) {
404
- var img = document.createElement('img'); img.src = it.viewUrl; img.alt = ''; img.loading = 'lazy'; ic.appendChild(img);
405
- } else if (it.viewUrl && it.contentType.indexOf('video/') === 0) {
406
- var vid = document.createElement('video'); vid.src = it.viewUrl; vid.muted = true; vid.playsInline = true; ic.appendChild(vid);
407
- } else {
408
- ic.textContent = (it.name.split('.').pop() || it.name.slice(0, 1)).slice(0, 3).toUpperCase();
570
+ // Compact markdown → HTML for .md previews (headings, lists, quotes, rules,
571
+ // fenced + inline code, bold/italic/links). Escapes first, then injects tags
572
+ // (same order as linkify). Backticks are built via char codes to avoid
573
+ // escaping issues inside this template literal.
574
+ function renderMarkdown(src) {
575
+ var BT = String.fromCharCode(96), FENCE = BT + BT + BT;
576
+ function inline(s) {
577
+ s = escapeHtml(s);
578
+ s = s.replace(new RegExp(BT + '([^' + BT + ']+)' + BT, 'g'), '<code>$1</code>');
579
+ s = s.replace(/\\*\\*([^*]+)\\*\\*/g, '<strong>$1</strong>');
580
+ s = s.replace(/(^|[^\\w*])\\*([^*\\n]+)\\*/g, '$1<em>$2</em>');
581
+ s = s.replace(/\\[([^\\]]+)\\]\\((https?:\\/\\/[^\\s)]+)\\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
582
+ s = s.replace(/(^|[\\s(])(https?:\\/\\/[^\\s<]+[^<.,:;"')\\]\\s])/g, '$1<a href="$2" target="_blank" rel="noopener noreferrer">$2</a>');
583
+ return s;
409
584
  }
410
- var main = document.createElement('span');
411
- main.className = 'rk-aichat-fmain';
412
- var name = document.createElement('span');
413
- name.className = 'rk-aichat-fname';
414
- name.textContent = it.name;
415
- var meta = document.createElement('span');
416
- meta.className = 'rk-aichat-fmeta';
417
- meta.textContent = it.metaText || fmtBytes(it.sizeBytes) || it.contentType || 'file';
418
- main.appendChild(name); main.appendChild(meta);
419
- var add = document.createElement('span');
420
- add.className = 'rk-aichat-fadd';
421
- add.textContent = '+ Attach';
422
- b.appendChild(ic); b.appendChild(main); b.appendChild(add);
423
- b.addEventListener('click', function () { attachFile(it); });
424
- return b;
585
+ var lines = String(src).replace(/\\r\\n?/g, '\\n').split('\\n');
586
+ var out = [], inCode = false, code = [], listType = null, listItems = [];
587
+ function flushList() { if (!listType) return; out.push('<' + listType + '>' + listItems.join('') + '</' + listType + '>'); listType = null; listItems = []; }
588
+ function flushCode() { out.push('<pre class="rk-aichat-preview-code"><code>' + escapeHtml(code.join('\\n')) + '</code></pre>'); code = []; }
589
+ for (var i = 0; i < lines.length; i++) {
590
+ var ln = lines[i];
591
+ if (ln.trim().indexOf(FENCE) === 0) { if (inCode) { flushCode(); inCode = false; } else { flushList(); inCode = true; } continue; }
592
+ if (inCode) { code.push(ln); continue; }
593
+ var h = ln.match(/^(#{1,6})\\s+(.*)$/);
594
+ if (h) { flushList(); var lvl = h[1].length; out.push('<h' + lvl + '>' + inline(h[2]) + '</h' + lvl + '>'); continue; }
595
+ if (/^\\s*([-*+])\\s+/.test(ln)) { if (listType !== 'ul') { flushList(); listType = 'ul'; } listItems.push('<li>' + inline(ln.replace(/^\\s*[-*+]\\s+/, '')) + '</li>'); continue; }
596
+ var om = ln.match(/^\\s*\\d+\\.\\s+(.*)$/);
597
+ if (om) { if (listType !== 'ol') { flushList(); listType = 'ol'; } listItems.push('<li>' + inline(om[1]) + '</li>'); continue; }
598
+ if (/^\\s*>\\s?/.test(ln)) { flushList(); out.push('<blockquote>' + inline(ln.replace(/^\\s*>\\s?/, '')) + '</blockquote>'); continue; }
599
+ if (/^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$/.test(ln)) { flushList(); out.push('<hr>'); continue; }
600
+ if (!ln.trim()) { flushList(); continue; }
601
+ flushList();
602
+ out.push('<p>' + inline(ln) + '</p>');
603
+ }
604
+ if (inCode) flushCode();
605
+ flushList();
606
+ return out.join('');
425
607
  }
426
608
 
427
- function crumb(label, current, onClick) {
428
- var b = document.createElement('button');
429
- b.type = 'button';
430
- b.className = 'rk-aichat-crumb' + (current ? ' is-current' : '');
431
- b.textContent = label;
432
- b.addEventListener('click', onClick);
433
- return b;
609
+ // ── file preview modal: images (carousel), video, audio, pdf, and text
610
+ // (json collapsible tree, md → rendered, txt/csv/srt/vtt → <pre>) ──
611
+ function openFilePreview(items, index) {
612
+ items = (items || []).filter(function (f) { return f && f.viewUrl; });
613
+ if (!items.length) return;
614
+ var idx = Math.max(0, Math.min(index || 0, items.length - 1));
615
+
616
+ var back = document.createElement('div'); back.className = 'rk-aichat-modal-back';
617
+ var modal = document.createElement('div'); modal.className = 'rk-aichat-modal rk-aichat-preview';
618
+ var head = document.createElement('div'); head.className = 'rk-aichat-modal-head';
619
+ var nameEl = document.createElement('span'); nameEl.className = 'rk-aichat-http-url rk-aichat-preview-name';
620
+ var openLink = document.createElement('a'); openLink.className = 'rk-aichat-preview-open'; openLink.target = '_blank'; openLink.rel = 'noopener noreferrer'; openLink.textContent = 'Open ↗';
621
+ var xBtn = document.createElement('button'); xBtn.type = 'button'; xBtn.className = 'rk-aichat-modal-x'; xBtn.setAttribute('aria-label', 'Close'); xBtn.innerHTML = '&times;';
622
+ head.appendChild(nameEl); head.appendChild(openLink); head.appendChild(xBtn);
623
+
624
+ var body = document.createElement('div'); body.className = 'rk-aichat-modal-body rk-aichat-preview-body';
625
+
626
+ var nav = document.createElement('div'); nav.className = 'rk-aichat-preview-nav';
627
+ var prev = document.createElement('button'); prev.type = 'button'; prev.className = 'rk-aichat-preview-btn'; prev.innerHTML = '‹ Prev';
628
+ var counter = document.createElement('span'); counter.className = 'rk-aichat-preview-count';
629
+ var next = document.createElement('button'); next.type = 'button'; next.className = 'rk-aichat-preview-btn'; next.innerHTML = 'Next ›';
630
+ nav.appendChild(prev); nav.appendChild(counter); nav.appendChild(next);
631
+
632
+ function renderUnknown(container, it, msg) {
633
+ var wrap = document.createElement('div'); wrap.className = 'rk-aichat-preview-empty';
634
+ var p = document.createElement('div'); p.textContent = msg || 'No inline preview for this file type.'; wrap.appendChild(p);
635
+ var a = document.createElement('a'); a.href = it.viewUrl; a.target = '_blank'; a.rel = 'noopener noreferrer'; a.className = 'rk-aichat-preview-dl'; a.textContent = 'Open / download ↗'; wrap.appendChild(a);
636
+ container.appendChild(wrap);
637
+ }
638
+ function renderText(container, it, kind) {
639
+ var loading = document.createElement('div'); loading.className = 'rk-aichat-preview-loading'; loading.textContent = 'Loading…'; container.appendChild(loading);
640
+ fetch(it.viewUrl, { credentials: 'same-origin' })
641
+ .then(function (r) { if (!r.ok) throw new Error('http ' + r.status); return r.text(); })
642
+ .then(function (txt) {
643
+ container.innerHTML = '';
644
+ if (kind === 'json') {
645
+ var parsed; try { parsed = JSON.parse(txt); } catch (e) { parsed = undefined; }
646
+ if (parsed && typeof parsed === 'object') { container.appendChild(jsonViewer(parsed)); return; }
647
+ var pj = document.createElement('pre'); pj.className = 'rk-aichat-http-pre rk-aichat-preview-text'; pj.textContent = txt; container.appendChild(pj); return;
648
+ }
649
+ if (kind === 'markdown') { var md = document.createElement('div'); md.className = 'rk-aichat-preview-md'; md.innerHTML = renderMarkdown(txt); container.appendChild(md); return; }
650
+ var pre = document.createElement('pre'); pre.className = 'rk-aichat-http-pre rk-aichat-preview-text'; pre.textContent = txt; container.appendChild(pre);
651
+ })
652
+ .catch(function () { container.innerHTML = ''; renderUnknown(container, it, 'Couldn’t load this file.'); });
653
+ }
654
+ function render() {
655
+ var it = items[idx];
656
+ nameEl.textContent = it.name || 'file'; nameEl.title = it.name || '';
657
+ openLink.href = it.viewUrl;
658
+ body.innerHTML = '';
659
+ var kind = fileKind(it.name, it.contentType);
660
+ if (kind === 'image') { var im = document.createElement('img'); im.className = 'rk-aichat-preview-img'; im.src = it.viewUrl; im.alt = it.name || ''; body.appendChild(im); }
661
+ else if (kind === 'video') { var v = document.createElement('video'); v.className = 'rk-aichat-preview-media'; v.src = it.viewUrl; v.controls = true; v.playsInline = true; body.appendChild(v); }
662
+ else if (kind === 'audio') { var wrap = document.createElement('div'); wrap.className = 'rk-aichat-preview-audiowrap'; var a = document.createElement('audio'); a.className = 'rk-aichat-preview-audio'; a.src = it.viewUrl; a.controls = true; wrap.appendChild(a); body.appendChild(wrap); }
663
+ else if (kind === 'pdf') { var f = document.createElement('iframe'); f.className = 'rk-aichat-preview-frame'; f.src = it.viewUrl; body.appendChild(f); }
664
+ else if (kind === 'json' || kind === 'markdown' || kind === 'text') { renderText(body, it, kind); }
665
+ else { renderUnknown(body, it); }
666
+ counter.textContent = (idx + 1) + ' / ' + items.length;
667
+ prev.disabled = idx <= 0; next.disabled = idx >= items.length - 1;
668
+ nav.hidden = items.length < 2;
669
+ }
670
+ prev.addEventListener('click', function () { if (idx > 0) { idx--; render(); } });
671
+ next.addEventListener('click', function () { if (idx < items.length - 1) { idx++; render(); } });
672
+
673
+ modal.appendChild(head); modal.appendChild(body); modal.appendChild(nav); back.appendChild(modal);
674
+ function close() { if (back.parentNode) back.parentNode.removeChild(back); document.removeEventListener('keydown', onKey); }
675
+ function onKey(e) { if (e.key === 'Escape') { e.stopPropagation(); close(); } else if (e.key === 'ArrowLeft') { if (idx > 0) { idx--; render(); } } else if (e.key === 'ArrowRight') { if (idx < items.length - 1) { idx++; render(); } } }
676
+ back.addEventListener('click', function (e) { if (e.target === back) close(); });
677
+ xBtn.addEventListener('click', close);
678
+ document.addEventListener('keydown', onKey);
679
+ document.body.appendChild(back);
680
+ render();
434
681
  }
435
- function crumbSep() {
436
- var s = document.createElement('span');
437
- s.className = 'rk-aichat-crumb-sep';
438
- s.textContent = '/';
439
- return s;
440
- }
441
- function renderCrumbs() {
442
- crumbsEl.innerHTML = '';
443
- // "Files" (virtual root) is always the first crumb
444
- var atVirtual = !fstate.root;
445
- crumbsEl.appendChild(crumb('Files', atVirtual, goVirtualRoot));
446
- if (atVirtual) return;
447
- if (fstate.status[fstate.root] !== 'ready') return;
448
- var cur = normFolder(fstate.path[fstate.root]);
449
- crumbsEl.appendChild(crumbSep());
450
- crumbsEl.appendChild(crumb(ROOTS[fstate.root].label, !cur, function () { goPath(''); }));
451
- var parts = cur.split('/').filter(Boolean);
452
- var acc = '';
453
- parts.forEach(function (part, idx) {
454
- crumbsEl.appendChild(crumbSep());
455
- acc = acc ? acc + '/' + part : part;
456
- var pth = acc;
457
- crumbsEl.appendChild(crumb(part, idx === parts.length - 1, function () { goPath(pth); }));
458
- });
682
+
683
+ // ── assistant turn controller (status → actions → streamed text) ──
684
+ function appendAssistant() {
685
+ var turn = document.createElement('div'); turn.className = 'rk-aichat-turn';
686
+ var actions = document.createElement('div'); actions.className = 'rk-aichat-actions';
687
+ var status = document.createElement('div'); status.className = 'rk-aichat-status';
688
+ status.innerHTML = '<span class="rk-aichat-typing"><span></span><span></span><span></span></span>';
689
+ var textEl = document.createElement('div'); textEl.className = 'rk-aichat-msg is-ai rk-aichat-stream'; textEl.hidden = true;
690
+ turn.appendChild(actions); turn.appendChild(status); turn.appendChild(textEl);
691
+ log.appendChild(turn); logBottom();
692
+ var lastText = '', flowEl = null;
693
+ return {
694
+ hideStatus: function () { status.hidden = true; },
695
+ showText: function () { status.hidden = true; textEl.hidden = false; },
696
+ setText: function (t) { lastText = t; textEl.textContent = t; },
697
+ // After streaming completes, re-render the text as markdown (bold/italic/links).
698
+ renderMd: function () { if (lastText) textEl.innerHTML = linkify(lastText); },
699
+ addNote: function (name) {
700
+ var n = document.createElement('div'); n.className = 'rk-aichat-toolnote';
701
+ n.textContent = 'Running ' + name + '…'; actions.appendChild(n); logBottom();
702
+ return n;
703
+ },
704
+ // Terminal one-line note (kind 'ok' | 'err' | undefined) — e.g. the real
705
+ // browser-side outcome of an editor_action apply.
706
+ note: function (text, kind) {
707
+ var n = document.createElement('div');
708
+ n.className = 'rk-aichat-toolnote' + (kind === 'err' ? ' is-err' : (kind === 'ok' ? ' is-ok' : ''));
709
+ n.textContent = text; actions.appendChild(n); logBottom();
710
+ return n;
711
+ },
712
+ addHttp: function (ex) { actions.appendChild(httpCard(ex)); logBottom(); },
713
+ // create_video pipeline progress (persistent status row, distinct from the
714
+ // thinking dots which hide once agent text streams).
715
+ flowStatus: function (s) {
716
+ if (!flowEl) { flowEl = document.createElement('div'); flowEl.className = 'rk-aichat-flow'; flowEl.innerHTML = '<span class="rk-aichat-typing"><span></span><span></span><span></span></span><span class="rk-aichat-flow-label"></span>'; turn.appendChild(flowEl); }
717
+ flowEl.hidden = false; flowEl.querySelector('.rk-aichat-flow-label').textContent = s || ''; logBottom();
718
+ },
719
+ // Final pipeline message (markdown-linkified, e.g. "Open it in the editor").
720
+ flowResult: function (md) {
721
+ if (flowEl) flowEl.hidden = true;
722
+ var b = document.createElement('div'); b.className = 'rk-aichat-msg is-ai'; b.innerHTML = linkify(md); turn.appendChild(b); logBottom();
723
+ },
724
+ fail: function (msg) {
725
+ status.hidden = true;
726
+ var er = document.createElement('div'); er.className = 'rk-aichat-err';
727
+ er.textContent = msg || 'Something went wrong.'; turn.appendChild(er); logBottom();
728
+ }
729
+ };
730
+ }
731
+
732
+ // ── SSE reader (mirrors the live editor-chat client) ──
733
+ function handleEvent(raw, h) {
734
+ var lines = raw.split('\\n'), dataLine = null;
735
+ for (var j = 0; j < lines.length; j++) { var t = lines[j].trim(); if (t.indexOf('data:') === 0) { dataLine = t; break; } }
736
+ if (!dataLine) return;
737
+ var payload = dataLine.slice(5).trim();
738
+ if (payload === '[DONE]' || !payload) return;
739
+ var chunk; try { chunk = JSON.parse(payload); } catch (e) { return; }
740
+ if (!chunk || typeof chunk !== 'object') return;
741
+ if (chunk.type === 'text-delta' && typeof chunk.delta === 'string') h.onDelta(chunk.delta);
742
+ else if (chunk.type === 'tool-call' && typeof chunk.toolName === 'string') h.onToolCall(chunk.toolName, chunk.toolCallId);
743
+ else if (chunk.type === 'tool-result') h.onToolResult(chunk.toolName, chunk.result, chunk.toolCallId);
744
+ else if (chunk.type === 'error') h.onError((typeof chunk.errorText === 'string') ? chunk.errorText : ((chunk.error && chunk.error.message) || 'Unable to read assistant response.'));
745
+ }
746
+ function readStream(response, h) {
747
+ if (!response.body || !response.body.getReader) return response.text().then(function (t) { t.split('\\n\\n').forEach(function (ev) { handleEvent(ev, h); }); });
748
+ var reader = response.body.getReader(), decoder = new TextDecoder(), buffer = '';
749
+ function pump() {
750
+ return reader.read().then(function (res) {
751
+ if (res.done) { if (buffer) handleEvent(buffer, h); return; }
752
+ buffer += decoder.decode(res.value, { stream: true });
753
+ var events = buffer.split('\\n\\n');
754
+ buffer = events.pop() || '';
755
+ for (var i = 0; i < events.length; i++) handleEvent(events[i], h);
756
+ return pump();
757
+ });
758
+ }
759
+ return pump();
459
760
  }
460
761
 
461
- var rendering = false;
462
- function renderFiles() {
463
- if (!filesPane) return;
464
- // loadRoot() calls renderFiles() synchronously to show a loading state; a
465
- // guard stops that re-entrant call from duplicating rows mid-render.
466
- if (rendering) return;
467
- rendering = true;
468
- try { renderFilesInner(); } finally { rendering = false; }
469
- }
470
- function renderFilesInner() {
471
- renderCrumbs();
472
- updateDropzone();
473
- filesBody.innerHTML = '';
474
- // Virtual root: the two sources appear as folders. Kick off a background
475
- // load of each so the counts fill in, but render the folders immediately.
476
- if (!fstate.root) {
477
- VROOTS.forEach(function (v) { if (fstate.status[v.key] === 'idle') loadRoot(v.key, false); });
478
- VROOTS.forEach(function (v) { filesBody.appendChild(vrootRow(v)); });
762
+ function sendMessage(text) {
763
+ if (busy) return;
764
+ text = (text || '').trim();
765
+ var picked = (typeof selected !== 'undefined' ? selected : []).slice();
766
+ var atts = picked.filter(function (f) { return f && f.viewUrl; }).map(function (f) {
767
+ return { id: String(f.id), fileName: f.name || 'file', contentType: f.contentType || 'application/octet-stream', viewUrl: f.viewUrl };
768
+ });
769
+ if (!text && !atts.length) return;
770
+ if (BOOT_STATE === 'idle' || BOOT_STATE === 'error') loadBoot();
771
+
772
+ var line = text;
773
+ if (picked.length) { line = (text ? text + ' ' : '') + '(attached: ' + picked.map(function (f) { return f.name; }).join(', ') + ')'; }
774
+ bubble('is-user', line);
775
+ convo.push({ role: 'user', text: text || line });
776
+ if (input) { input.value = ''; if (typeof autosizeInput === 'function') autosizeInput(); }
777
+ if (typeof clearChips === 'function') clearChips();
778
+
779
+ if (BOOT_STATE === 'anon') {
780
+ var v = appendAssistant(); v.showText();
781
+ v.setText('Sign in to chat with the vidfarm AI on your own provider keys.');
479
782
  return;
480
783
  }
481
- var st = fstate.status[fstate.root];
482
- if (st === 'idle') { loadRoot(fstate.root, false); return; }
483
- if (st === 'loading') { filesBody.appendChild(fstateNode('Loading your files…')); return; }
484
- if (st === 'auth') { filesBody.appendChild(fstateNode('Sign in to browse your files.', { href: '/login', linkText: 'Sign in' })); return; }
485
- if (st === 'error') { filesBody.appendChild(fstateNode('Couldn’t reach your files.', { retry: true })); return; }
486
- var data = fstate.data[fstate.root] || { items: [], folders: [] };
487
- var cur = normFolder(fstate.path[fstate.root]);
488
- var folders = immediateFolders(data, cur);
489
- var here = data.items.filter(function (it) { return normFolder(it.folderPath) === cur; });
490
- if (!folders.length && !here.length) {
491
- filesBody.appendChild(fstateNode(cur ? 'This folder is empty.' : 'No files in ' + ROOTS[fstate.root].label + ' yet.'));
784
+
785
+ var view = appendAssistant();
786
+ setBusy(true);
787
+ if (!threadId) threadId = genId('thread');
788
+ // Attach a fresh <editor_context> to the current (last) user turn only, so the
789
+ // model sees the composition state without bloating persisted history.
790
+ var ctxBlock = editorContextBlock();
791
+ var outMessages = convo.map(function (m, i) {
792
+ var t = m.text;
793
+ if (ctxBlock && m.role === 'user' && i === convo.length - 1) t = t + ctxBlock;
794
+ return { role: m.role, content: [{ type: 'text', text: t }] };
795
+ });
796
+ var body = {
797
+ messages: outMessages,
798
+ thread_id: threadId,
799
+ thread_template_id: TEMPLATE_ID,
800
+ thread_title: (text || line).slice(0, 42),
801
+ thread_tracers: (TEMPLATE && TEMPLATE.tracers) || [],
802
+ client_context: clientContext(),
803
+ user_message: { id: genId('user'), role: 'user', text: text || line, attachments: atts },
804
+ assistant_message: { id: genId('assistant') }
805
+ };
806
+ if (TEMPLATE) body.template = TEMPLATE;
807
+ if (CACHED) body.cached_context = CACHED;
808
+ var headers = { 'content-type': 'application/json' };
809
+ if (API_KEY) headers['vidfarm-api-key'] = API_KEY;
810
+
811
+ var acc = '', sawText = false, errored = false;
812
+ var handlers = {
813
+ onDelta: function (d) { if (!sawText) { sawText = true; view.showText(); } acc += d; view.setText(acc); logBottom(); },
814
+ onToolCall: function (name) { if (name !== 'http_request' && name !== 'create_video') view.addNote(name); },
815
+ onToolResult: function (name, result) {
816
+ if (name === 'create_video') { runCreateVideoFlow(view, result); return; }
817
+ // editor_action only mutates the composition browser-side. On /editor the
818
+ // SPA bundle exposes window.__vidfarmEditorAction; apply the tool result
819
+ // through it and surface the REAL outcome. Without this the dock ignored
820
+ // editor_action entirely, so the model's edits were pure no-ops even
821
+ // though its reply claimed success. (Only wired on the editor dock — the
822
+ // bridge is absent on /discover, /library, etc.)
823
+ if (name === 'editor_action') { applyEditorActionFromChat(view, result); return; }
824
+ if (result && result.request && result.response) view.addHttp(result);
825
+ },
826
+ onError: function (m) { errored = true; view.fail(m); }
827
+ };
828
+
829
+ var controller = (typeof AbortController !== 'undefined') ? new AbortController() : null;
830
+ pendingAbort = controller;
831
+ var req;
832
+ try { req = fetch(ENDPOINT, { method: 'POST', headers: headers, credentials: 'same-origin', body: JSON.stringify(body), signal: controller ? controller.signal : undefined }); }
833
+ catch (err) { req = Promise.reject(err); }
834
+ req.then(function (resp) {
835
+ if (!resp.ok) return resp.json().catch(function () { return {}; }).then(function (j) { throw new Error((j && j.error) || ('Chat request failed (' + resp.status + ').')); });
836
+ return readStream(resp, handlers);
837
+ }).then(function () {
838
+ pendingAbort = null;
839
+ view.hideStatus();
840
+ if (sawText) { convo.push({ role: 'assistant', text: acc }); view.renderMd(); }
841
+ else if (!errored) { view.showText(); view.setText('Done.'); }
842
+ setBusy(false);
843
+ if (input) input.focus();
844
+ loadThreads();
845
+ }).catch(function (err) {
846
+ pendingAbort = null;
847
+ // User hit Stop mid-reply — keep whatever streamed so far, no error.
848
+ if (err && (err.name === 'AbortError' || (controller && controller.signal && controller.signal.aborted))) {
849
+ view.hideStatus();
850
+ if (sawText) { convo.push({ role: 'assistant', text: acc }); view.renderMd(); }
851
+ else { view.showText(); view.setText('Stopped.'); }
852
+ setBusy(false); if (input) input.focus();
853
+ return;
854
+ }
855
+ var msg = (err && err.message) ? err.message : String(err);
856
+ if (!API_KEY) msg = msg + '\\n\\nAdd an AI provider key in Settings to chat on your own keys.';
857
+ view.fail(msg); setBusy(false); if (input) input.focus();
858
+ });
859
+ }
860
+
861
+ function resetConversation() {
862
+ convo = []; threadId = null;
863
+ if (log) { log.innerHTML = ''; bubble('is-ai', GREETING); }
864
+ if (typeof clearChips === 'function') clearChips();
865
+ }
866
+ function newChat() {
867
+ resetConversation();
868
+ setActiveThread(null);
869
+ if (input) { input.value = ''; if (typeof autosizeInput === 'function') autosizeInput(); input.focus(); }
870
+ }
871
+ // NOTE: the New-chat button element (rkNewChat) is resolved later (see the
872
+ // var block below), so bind its click handler there — binding here would run
873
+ // against an undefined newChatBtn (var hoisting) and silently never attach.
874
+ if (form) form.addEventListener('submit', function (e) {
875
+ e.preventDefault();
876
+ if (busy) { if (pendingAbort) pendingAbort.abort(); return; }
877
+ sendMessage(input ? input.value : '');
878
+ });
879
+
880
+ // The composer is now a multi-row textarea: grow with content (capped) and let
881
+ // Enter send (Shift+Enter inserts a newline, like every modern chat box).
882
+ function autosizeInput() {
883
+ if (!input || input.tagName !== 'TEXTAREA') return;
884
+ input.style.height = 'auto';
885
+ input.style.height = Math.min(input.scrollHeight, 210) + 'px';
886
+ }
887
+ if (input) {
888
+ input.addEventListener('input', autosizeInput);
889
+ input.addEventListener('keydown', function (e) {
890
+ if (e.key === 'Enter' && !e.shiftKey) {
891
+ e.preventDefault();
892
+ if (form && form.requestSubmit) form.requestSubmit();
893
+ else { if (busy) { if (pendingAbort) pendingAbort.abort(); } else sendMessage(input.value); }
894
+ }
895
+ });
896
+ }
897
+
898
+ // ─── editor_action: apply a composition mutation through the SPA bridge that
899
+ // the editor bundle exposes on window (__vidfarmEditorAction). Only present on
900
+ // the /editor dock; elsewhere there is no composition to mutate. ───
901
+ function applyEditorActionFromChat(view, result) {
902
+ var label = (result && result.action_type) ? String(result.action_type) : 'editor_action';
903
+ var bridge = (typeof window !== 'undefined') ? window.__vidfarmEditorAction : null;
904
+ if (!bridge || typeof bridge.apply !== 'function') {
905
+ view.note('⚠ Editor not ready — reload the page, then ask again (' + label + ' was not applied).', 'err');
492
906
  return;
493
907
  }
494
- folders.forEach(function (f) { filesBody.appendChild(folderRow(f.name, function () { goPath(f.path); })); });
495
- here.forEach(function (it) { filesBody.appendChild(fileRow(it)); });
496
- }
497
-
498
- function goPath(p) { uploadMsg = ''; fstate.path[fstate.root] = normFolder(p); renderFiles(); }
499
- function goVirtualRoot() { uploadMsg = ''; fstate.root = ''; renderFiles(); }
500
- function enterRoot(root) {
501
- if (!ROOTS[root]) return;
502
- uploadMsg = '';
503
- fstate.root = root;
504
- fstate.path[root] = '';
505
- loadRoot(root, false);
506
- renderFiles();
507
- }
508
-
509
- // ── upload: drop files or click the button; posts to the current source +
510
- // folder's real upload endpoint (attachments/upload or temporary-files/upload).
511
- function dropCaption() {
512
- if (!fstate.root) return '';
513
- var f = normFolder(fstate.path[fstate.root]);
514
- return 'Drop files into ' + ROOTS[fstate.root].label + (f ? ' / ' + f : '');
515
- }
516
- function updateDropzone() {
517
- if (!dropEl) return;
518
- // Raws are imported/scanned, not plain-uploaded — no dropzone in that root.
519
- var show = !!fstate.root && fstate.root !== 'raws' && fstate.status[fstate.root] !== 'auth';
520
- dropEl.hidden = !show;
521
- if (show && dropText && !uploading) { dropText.textContent = uploadMsg || dropCaption(); }
522
- }
523
- function uploadFiles(fileList) {
524
- if (!fstate.root || fstate.root === 'raws' || uploading) return;
525
- var files = [];
526
- for (var i = 0; i < fileList.length; i++) files.push(fileList[i]);
527
- if (!files.length) return;
528
- uploading = true; uploadMsg = '';
529
- var root = fstate.root;
530
- var folder = normFolder(fstate.path[root]);
531
- var url = ROOTS[root].url + '/upload';
532
- if (dropEl) dropEl.classList.remove('is-drag');
533
- if (uploadBtn) uploadBtn.disabled = true;
534
- var total = files.length, failed = 0;
535
- if (dropText) dropText.textContent = 'Uploading ' + total + ' file' + (total > 1 ? 's' : '') + '…';
536
- function next(idx) {
537
- if (idx >= files.length) {
538
- uploading = false;
539
- if (uploadBtn) uploadBtn.disabled = false;
540
- uploadMsg = failed ? (failed + ' of ' + total + ' failed to upload') : '';
541
- loadRoot(root, true); // refresh listing; its re-render resets the caption
908
+ var outcome;
909
+ try { outcome = bridge.apply(result); }
910
+ catch (e) { outcome = { ok: false, error: (e && e.message) ? e.message : String(e) }; }
911
+ if (outcome && outcome.ok) {
912
+ view.note('✓ ' + (outcome.summary || ('Applied ' + label + '.')), 'ok');
913
+ } else {
914
+ view.note('⚠ Couldn’t apply ' + label + ((outcome && outcome.error) ? ': ' + outcome.error : '.'), 'err');
915
+ }
916
+ }
917
+
918
+ // ─── create_video: the browser-side pipeline behind the agent's create_video
919
+ // tool. The backend tool is a passthrough (returns the intent only); the
920
+ // frontend runs ingest → decompose → fork and posts a clickable "Open in the
921
+ // editor" link. Ported 1:1 from the /editor chat's runCreateVideoFlow. ───
922
+ function ivHeaders(json) { var h = { accept: 'application/json' }; if (json) h['content-type'] = 'application/json'; if (API_KEY) h['vidfarm-api-key'] = API_KEY; return h; }
923
+ function ivSleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
924
+ function ivJson(res) { return res.text().then(function (t) { try { return t ? JSON.parse(t) : null; } catch (e) { return null; } }); }
925
+ async function runCreateVideoFlow(view, intentRaw) {
926
+ var intent = intentRaw || {};
927
+ if (!API_KEY) { view.flowResult('⚠️ You need to be logged in to create a video.'); return; }
928
+ var origin = window.location.origin;
929
+
930
+ function pollInspirationReady(id) {
931
+ var deadline = Date.now() + 5 * 60 * 1000;
932
+ function step() {
933
+ return fetch(origin + '/api/v1/videos/' + encodeURIComponent(id), { headers: ivHeaders(false) }).then(ivJson).then(function (j) {
934
+ var st = String((j && j.status) || '');
935
+ if (st === 'ready') return j;
936
+ if (st === 'failed') throw new Error('source video download failed' + ((j && j.error) ? ': ' + j.error : '') + '.');
937
+ if (Date.now() > deadline) throw new Error('source video download timed out.');
938
+ return ivSleep(5000).then(step);
939
+ });
940
+ }
941
+ return step();
942
+ }
943
+ function jobMediaUrl(job) {
944
+ function s(v) { return (typeof v === 'string' && v.trim()) ? v.trim() : null; }
945
+ var result = (job && job.result && typeof job.result === 'object') ? job.result : {};
946
+ var out = (result.output && typeof result.output === 'object') ? result.output : result;
947
+ var direct = s(out.primary_file_url) || s(out.video && out.video.file_url) || s(out.image && out.image.file_url) || s(out.render && out.render.output_url);
948
+ if (direct) return direct;
949
+ if (out.files && out.files.length) { for (var i = 0; i < out.files.length; i++) { var f = out.files[i]; var u = s(typeof f === 'string' ? f : (f && (f.file_url || f.url))); if (u) return u; } }
950
+ if (job && job.artifacts && job.artifacts.length) { for (var k = 0; k < job.artifacts.length; k++) { var u2 = s(job.artifacts[k] && job.artifacts[k].public_url); if (u2) return u2; } }
951
+ return null;
952
+ }
953
+ function pollJobMedia(jobId) {
954
+ var deadline = Date.now() + 8 * 60 * 1000;
955
+ function step() {
956
+ return ivSleep(5000).then(function () {
957
+ return fetch(origin + '/api/v1/user/me/jobs/' + encodeURIComponent(jobId), { headers: ivHeaders(false) }).then(ivJson).then(function (j) {
958
+ var st = String((j && j.status) || '');
959
+ var url = jobMediaUrl(j);
960
+ if (url) return url;
961
+ if (st === 'failed' || st === 'cancelled') throw new Error('generation ' + st + '.');
962
+ if (Date.now() > deadline) throw new Error('generation timed out.');
963
+ return step();
964
+ });
965
+ });
966
+ }
967
+ return step();
968
+ }
969
+ async function ingestGeneratedVideo(mediaUrl, title) {
970
+ var blob = await (await fetch(mediaUrl)).blob();
971
+ var presignRes = await fetch(origin + '/discover/templates/upload/presign', { method: 'POST', headers: ivHeaders(true), body: JSON.stringify({ file_name: 'generated.mp4', content_type: 'video/mp4', size_bytes: blob.size }) });
972
+ var presign = await ivJson(presignRes);
973
+ if (!presignRes.ok) throw new Error((presign && presign.error) || ('upload presign failed (' + presignRes.status + ')'));
974
+ var storageKey = presign && presign.storage_key;
975
+ var uploadedName = (presign && presign.file_name) || 'generated.mp4';
976
+ if (presign && presign.transport === 'presigned' && presign.upload && presign.upload.url) {
977
+ var put = await fetch(presign.upload.url, { method: (presign.upload.method || 'PUT'), headers: presign.upload.headers || {}, body: blob });
978
+ if (!put.ok) throw new Error('upload failed (' + put.status + ')');
979
+ } else {
980
+ var form = new FormData(); form.append('file', blob, 'generated.mp4');
981
+ var up = await fetch(origin + ((presign && presign.upload && presign.upload.url) || '/discover/templates/upload'), { method: 'POST', headers: ivHeaders(false), body: form });
982
+ var upJson = await ivJson(up);
983
+ if (!up.ok || !upJson || !upJson.storage_key) throw new Error((upJson && upJson.error) || ('upload failed (' + up.status + ')'));
984
+ storageKey = upJson.storage_key; uploadedName = upJson.file_name || 'generated.mp4';
985
+ }
986
+ if (!storageKey) throw new Error('upload did not return a storage key.');
987
+ var addRes = await fetch(origin + '/discover/templates', { method: 'POST', headers: ivHeaders(true), body: JSON.stringify({ upload: { storage_key: storageKey, file_name: uploadedName }, title: title, origin: 'raw' }) });
988
+ var add = await ivJson(addRes);
989
+ if (!addRes.ok) throw new Error((add && add.error) || ('ingest failed (' + addRes.status + ')'));
990
+ return add;
991
+ }
992
+
993
+ try {
994
+ var mode = intent.mode === 'replicate' ? 'replicate' : (intent.mode === 'generate' ? 'generate' : null);
995
+ var inspiration, userPrompt;
996
+ if (mode === 'replicate') {
997
+ var sourceUrl = String(intent.source_url || '').trim();
998
+ if (!/^https?:\\/\\//i.test(sourceUrl)) { view.flowResult('⚠️ I need a video URL (TikTok/YouTube/Instagram/X) to replicate.'); return; }
999
+ userPrompt = String(intent.instructions || '').trim() || null;
1000
+ view.flowStatus('Fetching the source video…');
1001
+ var addRes = await fetch(origin + '/discover/templates', { method: 'POST', headers: ivHeaders(true), body: JSON.stringify({ source_url: sourceUrl }) });
1002
+ var add = await ivJson(addRes);
1003
+ if (!addRes.ok) throw new Error((add && add.error) || ("couldn't fetch that URL (" + addRes.status + ')'));
1004
+ inspiration = (add && add.status === 'ready') ? add : await pollInspirationReady(add && add.inspiration_id);
1005
+ } else if (mode === 'generate') {
1006
+ var prompt = String(intent.prompt || '').trim();
1007
+ if (!prompt) { view.flowResult("⚠️ Tell me what the video should be about and I'll create it."); return; }
1008
+ userPrompt = prompt;
1009
+ view.flowStatus('Generating your video… (this can take a couple of minutes)');
1010
+ var genRes = await fetch(origin + '/api/v1/primitives/videos/generate', { method: 'POST', headers: ivHeaders(true), body: JSON.stringify({ tracer: 'chat-create-' + Date.now().toString(36), payload: { prompt: prompt } }) });
1011
+ var gen = await ivJson(genRes);
1012
+ if (!genRes.ok) throw new Error((gen && gen.error) || ("couldn't start generation (" + genRes.status + ')'));
1013
+ var mediaUrl = await pollJobMedia(gen && gen.job_id);
1014
+ view.flowStatus('Building an editable template from the generated video…');
1015
+ var add2 = await ingestGeneratedVideo(mediaUrl, prompt.slice(0, 80));
1016
+ inspiration = (add2 && add2.status === 'ready') ? add2 : await pollInspirationReady(add2 && add2.inspiration_id);
1017
+ } else {
1018
+ view.flowResult("⚠️ I couldn't tell whether to generate a new video or replicate a URL — try rephrasing.");
542
1019
  return;
543
1020
  }
544
- var fd = new FormData();
545
- fd.append('file', files[idx]);
546
- fd.append('folder_path', folder);
547
- fetch(url, { method: 'POST', credentials: 'same-origin', body: fd })
548
- .then(function (r) { if (!r.ok) throw new Error('http ' + r.status); })
549
- .catch(function () { failed++; })
550
- .then(function () { next(idx + 1); });
1021
+ var templateId = inspiration && inspiration.template_id;
1022
+ var inspirationId = inspiration && inspiration.inspiration_id;
1023
+ if (!templateId || !inspirationId) throw new Error("the template wasn't created from the video.");
1024
+ view.flowStatus(mode === 'replicate' ? 'Recreating the scenes… (about a minute)' : 'Analyzing into an editable timeline…');
1025
+ var decRes = await fetch(origin + '/api/v1/inspirations/' + encodeURIComponent(inspirationId) + '/decompose', { method: 'POST', headers: ivHeaders(true), body: JSON.stringify({ user_prompt: userPrompt }) });
1026
+ if (!decRes.ok) { var dec = await ivJson(decRes); throw new Error((dec && dec.error) || ('scene analysis failed (' + decRes.status + ')')); }
1027
+ view.flowStatus('Finalizing your editable copy…');
1028
+ var forkRes = await fetch(origin + '/api/v1/compositions', { method: 'POST', headers: ivHeaders(true), body: JSON.stringify({ template_id: templateId }) });
1029
+ var fork = await ivJson(forkRes);
1030
+ if (!forkRes.ok) throw new Error((fork && fork.error) || ("couldn't create an editable copy (" + forkRes.status + ')'));
1031
+ var forkId = fork && fork.fork_id;
1032
+ var editorUrl = origin + '/editor/' + encodeURIComponent(templateId) + (forkId ? '/fork/' + encodeURIComponent(forkId) : '');
1033
+ view.flowResult('✅ Your video is ready — [Open it in the editor](' + editorUrl + ').');
1034
+ } catch (error) {
1035
+ view.flowResult('⚠️ I couldn’t finish creating the video: ' + ((error && error.message) ? error.message : String(error)));
551
1036
  }
552
- next(0);
553
- }
554
- if (uploadBtn) uploadBtn.addEventListener('click', function () { if (uploadInput) uploadInput.click(); });
555
- if (uploadInput) uploadInput.addEventListener('change', function () { uploadFiles(uploadInput.files); uploadInput.value = ''; });
556
- if (dropEl) {
557
- dropEl.addEventListener('dragover', function (e) { e.preventDefault(); dropEl.classList.add('is-drag'); });
558
- dropEl.addEventListener('dragleave', function (e) { if (e.target === dropEl) dropEl.classList.remove('is-drag'); });
559
- dropEl.addEventListener('drop', function (e) {
560
- e.preventDefault(); dropEl.classList.remove('is-drag');
561
- if (e.dataTransfer && e.dataTransfer.files) uploadFiles(e.dataTransfer.files);
562
- });
563
1037
  }
564
1038
 
1039
+ // ─── Files drawer ───
1040
+ // Directory browsing lives in the reusable component (src/frontend/file-directory.ts),
1041
+ // auto-mounted into #rkAichatFilesMount by /assets/file-directory-app.js. This
1042
+ // inline script only owns the chat-side glue: the attach chips + preview modal.
1043
+ // We expose those to the component as host hooks BEFORE the deferred module runs
1044
+ // (this classic <script> executes during parse, ahead of the module).
1045
+ var chipsEl = document.getElementById('rkAichatChips');
1046
+ var filesToggle = document.getElementById('rkFilesToggle');
1047
+ var historyToggle = document.getElementById('rkHistoryToggle');
1048
+ var newChatBtn = document.getElementById('rkNewChat');
1049
+ if (newChatBtn) newChatBtn.addEventListener('click', function () { if (!busy) newChat(); });
1050
+ var histBody = document.getElementById('rkAichatHistBody');
1051
+ var selected = [];
1052
+ window.__rkDirectoryHost = {
1053
+ onAttach: function (items) { (items || []).forEach(function (it) { attachFile(it); }); },
1054
+ onPreview: function (items, i) { openFilePreview(items || [], i || 0); }
1055
+ };
1056
+ function refreshFiles() { if (window.__rkDirectoryInstance) window.__rkDirectoryInstance.refresh(); }
1057
+
1058
+ // Editor dock "Back to Library": leave the editor cleanly — clear the persisted
1059
+ // open-state so the destination page loads with the chat panel closed and on a
1060
+ // fresh chat, then navigate. (Real anchor href="/library" is the fallback.)
1061
+ var backBtn = document.getElementById('rkAichatBack');
1062
+ if (backBtn) backBtn.addEventListener('click', function (e) {
1063
+ try { sessionStorage.removeItem('rk-chat-open'); } catch (err) {}
1064
+ e.preventDefault();
1065
+ window.location.assign('/library');
1066
+ });
1067
+
565
1068
  function attachFile(it) {
1069
+ // Files-only drawer (opened from the /chat page) has no chat composer of its
1070
+ // own — hand the picked file to the /chat page's composer via a DOM event.
1071
+ if (panel.classList.contains('is-files-only')) {
1072
+ try {
1073
+ document.dispatchEvent(new CustomEvent('rk-chat-attach-file', { detail: {
1074
+ id: String(it.id), name: it.name || 'file',
1075
+ contentType: it.contentType || 'application/octet-stream', viewUrl: it.viewUrl || ''
1076
+ } }));
1077
+ } catch (e) {}
1078
+ return;
1079
+ }
566
1080
  if (selected.some(function (f) { return f.id === it.id; })) { flashChip(it.id); return; }
567
1081
  selected.push(it);
568
1082
  renderChips();
@@ -571,12 +1085,16 @@ const RESKIN_CHROME_SCRIPT = `(() => {
571
1085
  function renderChips() {
572
1086
  if (!chipsEl) return;
573
1087
  chipsEl.innerHTML = '';
574
- selected.forEach(function (f) {
1088
+ selected.forEach(function (f, i) {
575
1089
  var chip = document.createElement('span');
576
1090
  chip.className = 'rk-aichat-chip';
577
1091
  chip.setAttribute('data-id', f.id);
578
- var label = document.createElement('span');
1092
+ var label = document.createElement('button');
1093
+ label.type = 'button';
1094
+ label.className = 'rk-aichat-chip-label';
1095
+ label.title = 'Preview ' + f.name;
579
1096
  label.textContent = f.name;
1097
+ if (f.viewUrl) label.addEventListener('click', function () { openFilePreview(selected, i); });
580
1098
  var x = document.createElement('button');
581
1099
  x.type = 'button';
582
1100
  x.setAttribute('aria-label', 'Remove ' + f.name);
@@ -598,36 +1116,282 @@ const RESKIN_CHROME_SCRIPT = `(() => {
598
1116
  }
599
1117
  function clearChips() { selected = []; renderChips(); }
600
1118
 
601
- function filesOpen() { return panel.classList.contains('has-files'); }
602
- function setFilesOpen(open) {
603
- panel.classList.toggle('has-files', open);
1119
+ // ─── left drawer mode: 'files' | 'history' | '' (closed) ───────────────────
1120
+ // Files and Chat history share the one left slot, so only one shows at a time.
1121
+ function leftMode() {
1122
+ if (panel.classList.contains('has-history')) return 'history';
1123
+ if (panel.classList.contains('has-files')) return 'files';
1124
+ return '';
1125
+ }
1126
+ function filesOpen() { return leftMode() === 'files'; }
1127
+ function setLeftMode(mode) {
1128
+ panel.classList.toggle('has-files', mode === 'files');
1129
+ panel.classList.toggle('has-history', mode === 'history');
604
1130
  if (filesToggle) {
605
- filesToggle.classList.toggle('is-on', open);
606
- filesToggle.setAttribute('aria-pressed', open ? 'true' : 'false');
1131
+ filesToggle.classList.toggle('is-on', mode === 'files');
1132
+ filesToggle.setAttribute('aria-pressed', mode === 'files' ? 'true' : 'false');
1133
+ }
1134
+ if (historyToggle) {
1135
+ historyToggle.classList.toggle('is-on', mode === 'history');
1136
+ historyToggle.setAttribute('aria-pressed', mode === 'history' ? 'true' : 'false');
607
1137
  }
608
- try { localStorage.setItem('rk-files-open', open ? '1' : '0'); } catch (e) {}
609
- if (open) renderFiles();
1138
+ var caBtn = document.getElementById('rkAichatAttach');
1139
+ if (caBtn) {
1140
+ caBtn.classList.toggle('is-on', mode === 'files');
1141
+ caBtn.setAttribute('aria-pressed', mode === 'files' ? 'true' : 'false');
1142
+ }
1143
+ try { localStorage.setItem('rk-left-mode', mode); } catch (e) {}
1144
+ if (mode === 'files') refreshFiles();
1145
+ if (mode === 'history') loadThreads();
610
1146
  if (!panel.hidden) anchorPanel();
611
1147
  }
612
1148
  function refreshFilesOnOpen() {
613
- if (filesOpen()) {
614
- // re-fetch whichever source(s) are in view so counts/listings are fresh
615
- if (fstate.root) loadRoot(fstate.root, true);
616
- else VROOTS.forEach(function (v) { loadRoot(v.key, true); });
617
- renderFiles();
618
- }
1149
+ // Re-fetch the current folder so listings are fresh when the drawer opens.
1150
+ if (filesOpen()) refreshFiles();
1151
+ }
1152
+
1153
+ // ─── Chat history — REAL editor-chat threads (past conversations) ──────────
1154
+ var threads = [], threadsState = 'idle', loadingThread = false;
1155
+ function authHeaders() { var h = { accept: 'application/json' }; if (API_KEY) h['vidfarm-api-key'] = API_KEY; return h; }
1156
+ function relTime(iso) {
1157
+ if (!iso) return '';
1158
+ var t = Date.parse(iso); if (isNaN(t)) return '';
1159
+ var s = Math.max(0, (Date.now() - t) / 1000);
1160
+ if (s < 60) return 'just now';
1161
+ if (s < 3600) return Math.floor(s / 60) + 'm ago';
1162
+ if (s < 86400) return Math.floor(s / 3600) + 'h ago';
1163
+ if (s < 604800) return Math.floor(s / 86400) + 'd ago';
1164
+ try { return new Date(t).toLocaleDateString([], { month: 'short', day: 'numeric' }); } catch (e) { return ''; }
1165
+ }
1166
+ function histNote(text, opts) {
1167
+ var wrap = document.createElement('div'); wrap.className = 'rk-aichat-fstate';
1168
+ var p = document.createElement('div'); p.textContent = text; wrap.appendChild(p);
1169
+ if (opts && opts.href) { var a = document.createElement('a'); a.href = opts.href; a.textContent = opts.linkText || 'Open'; wrap.appendChild(a); }
1170
+ if (opts && opts.retry) { var b = document.createElement('button'); b.type = 'button'; b.textContent = 'Try again'; b.addEventListener('click', function () { loadThreads(); }); wrap.appendChild(b); }
1171
+ return wrap;
1172
+ }
1173
+ function setActiveThread(id) {
1174
+ threadId = id;
1175
+ if (!histBody) return;
1176
+ var rows = histBody.querySelectorAll('.rk-aichat-frow');
1177
+ for (var i = 0; i < rows.length; i++) rows[i].classList.toggle('is-active', rows[i].getAttribute('data-id') === id);
1178
+ }
1179
+ function threadRow(t) {
1180
+ var b = document.createElement('button');
1181
+ b.type = 'button';
1182
+ b.className = 'rk-aichat-frow' + (t.id === threadId ? ' is-active' : '');
1183
+ b.setAttribute('data-id', t.id);
1184
+ var ic = document.createElement('span');
1185
+ ic.className = 'rk-aichat-fic rk-aichat-fic-file';
1186
+ ic.innerHTML = '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>';
1187
+ var main = document.createElement('span'); main.className = 'rk-aichat-fmain';
1188
+ var name = document.createElement('span'); name.className = 'rk-aichat-fname'; name.textContent = t.title || 'Untitled chat';
1189
+ var count = (typeof t.messageCount === 'number') ? t.messageCount : 0;
1190
+ var when = relTime(t.lastMessageAt || t.updatedAt);
1191
+ var meta = document.createElement('span'); meta.className = 'rk-aichat-fmeta';
1192
+ meta.textContent = (count ? count + ' message' + (count === 1 ? '' : 's') : '') + ((count && when) ? ' · ' : '') + (when || '');
1193
+ main.appendChild(name); main.appendChild(meta);
1194
+ var del = document.createElement('button');
1195
+ del.type = 'button'; del.className = 'rk-aichat-fadd'; del.setAttribute('aria-label', 'Delete chat'); del.textContent = '×';
1196
+ del.addEventListener('click', function (ev) { ev.stopPropagation(); deleteThread(t.id, b); });
1197
+ b.appendChild(ic); b.appendChild(main); b.appendChild(del);
1198
+ b.addEventListener('click', function () { openThread(t.id); });
1199
+ return b;
1200
+ }
1201
+ function renderHistory() {
1202
+ if (!histBody) return;
1203
+ histBody.innerHTML = '';
1204
+ if (BOOT_STATE === 'anon') { histBody.appendChild(histNote('Sign in to sync your saved chats.', { href: '/login', linkText: 'Sign in' })); return; }
1205
+ if (threadsState === 'loading' && !threads.length) { histBody.appendChild(histNote('Loading your chats…')); return; }
1206
+ if (threadsState === 'auth') { histBody.appendChild(histNote('Sign in to sync your saved chats.', { href: '/login', linkText: 'Sign in' })); return; }
1207
+ if (threadsState === 'error') { histBody.appendChild(histNote('Couldn’t load your chats.', { retry: true })); return; }
1208
+ if (!threads.length) { histBody.appendChild(histNote('No conversations yet. Start one below — it saves automatically.')); return; }
1209
+ for (var i = 0; i < threads.length; i++) histBody.appendChild(threadRow(threads[i]));
1210
+ }
1211
+ function loadThreads() {
1212
+ if (!histBody) return;
1213
+ if (BOOT_STATE === 'anon') { renderHistory(); return; }
1214
+ if (BOOT_STATE !== 'ready') { loadBoot(); return; } // loadBoot() calls back into loadThreads() when ready
1215
+ threadsState = 'loading'; renderHistory();
1216
+ var url = THREADS_URL + '?template_id=' + encodeURIComponent(TEMPLATE_ID) + '&limit=30&include_messages=false';
1217
+ fetch(url, { headers: authHeaders(), credentials: 'same-origin' })
1218
+ .then(function (r) {
1219
+ if (r.status === 401 || r.status === 403) { threadsState = 'auth'; return null; }
1220
+ if (!r.ok) throw new Error('http ' + r.status);
1221
+ return r.json();
1222
+ })
1223
+ .then(function (j) {
1224
+ if (!j) { renderHistory(); return; }
1225
+ threads = (j && j.threads) || []; threadsState = 'ready'; renderHistory();
1226
+ })
1227
+ .catch(function () { threadsState = 'error'; renderHistory(); });
1228
+ }
1229
+ function openThread(id) {
1230
+ if (busy || loadingThread) return;
1231
+ loadingThread = true;
1232
+ fetch(THREADS_URL + '/' + encodeURIComponent(id), { headers: authHeaders(), credentials: 'same-origin' })
1233
+ .then(function (r) { if (!r.ok) throw new Error('http ' + r.status); return r.json(); })
1234
+ .then(function (j) {
1235
+ var t = j && j.thread; if (!t) throw new Error('missing thread');
1236
+ convo = []; if (log) log.innerHTML = '';
1237
+ var msgs = t.messages || [];
1238
+ for (var i = 0; i < msgs.length; i++) {
1239
+ var m = msgs[i], role = (m.role === 'assistant') ? 'assistant' : 'user', txt = m.text || '';
1240
+ convo.push({ role: role, text: txt });
1241
+ if (role === 'user') { bubble('is-user', txt); }
1242
+ else {
1243
+ var v = appendAssistant();
1244
+ var ex = m.httpExchanges || [];
1245
+ for (var k = 0; k < ex.length; k++) { if (ex[k] && ex[k].request && ex[k].response) v.addHttp(ex[k]); }
1246
+ v.showText(); v.setText(txt); v.hideStatus(); v.renderMd();
1247
+ }
1248
+ }
1249
+ setActiveThread(id);
1250
+ loadingThread = false;
1251
+ logBottom();
1252
+ if (input) input.focus();
1253
+ })
1254
+ .catch(function () { loadingThread = false; });
1255
+ }
1256
+ function deleteThread(id, row) {
1257
+ if (!API_KEY) return;
1258
+ fetch(THREADS_URL + '/' + encodeURIComponent(id), { method: 'DELETE', headers: authHeaders(), credentials: 'same-origin' })
1259
+ .then(function (r) {
1260
+ if (!r.ok && r.status !== 404) throw new Error('http ' + r.status);
1261
+ threads = threads.filter(function (t) { return t.id !== id; });
1262
+ if (id === threadId) resetConversation();
1263
+ renderHistory();
1264
+ })
1265
+ .catch(function () {});
619
1266
  }
620
1267
 
621
1268
  if (filesToggle) {
622
- filesToggle.addEventListener('click', function () { setFilesOpen(!filesOpen()); });
1269
+ filesToggle.addEventListener('click', function () { setLeftMode(leftMode() === 'files' ? '' : 'files'); });
623
1270
  }
624
- // Honor the saved visibility preference (default: open).
1271
+ // Composer paperclip — opens the folder directory nav (Files drawer) so the
1272
+ // user can browse + attach a file, mirroring the header Files toggle. Works
1273
+ // in both the editor dock and the floating pop-panel.
1274
+ var composerAttach = document.getElementById('rkAichatAttach');
1275
+ if (composerAttach) {
1276
+ composerAttach.addEventListener('click', function () { setLeftMode(leftMode() === 'files' ? '' : 'files'); });
1277
+ }
1278
+ if (historyToggle) {
1279
+ historyToggle.addEventListener('click', function () { setLeftMode(leftMode() === 'history' ? '' : 'history'); });
1280
+ }
1281
+ // /chat composer's attach button ⇄ files-only drawer (open ↔ close toggle).
1282
+ var chatAttachBtn = document.getElementById('rk-chat-attach');
1283
+ if (chatAttachBtn) {
1284
+ chatAttachBtn.addEventListener('click', function () {
1285
+ if (!panel.hidden && panel.classList.contains('is-files-only')) closePanel();
1286
+ else openPanel(true);
1287
+ });
1288
+ }
1289
+ var filesCloseBtn = document.getElementById('rkFilesClose');
1290
+ if (filesCloseBtn) filesCloseBtn.addEventListener('click', function () {
1291
+ // In the /chat files-only drawer this is the only close affordance → shut the
1292
+ // panel. In the full pop-panel it just collapses the Files drawer back to chat.
1293
+ if (panel.classList.contains('is-files-only')) closePanel();
1294
+ else setLeftMode('');
1295
+ });
1296
+ // Honor the saved drawer mode (default: files open).
625
1297
  try {
626
- setFilesOpen(localStorage.getItem('rk-files-open') !== '0');
627
- } catch (e) { setFilesOpen(true); }
628
- renderFiles();
1298
+ var savedMode = localStorage.getItem('rk-left-mode');
1299
+ setLeftMode(savedMode === null ? 'files' : savedMode);
1300
+ } catch (e) { setLeftMode('files'); }
1301
+ renderHistory();
629
1302
 
630
- try { if (sessionStorage.getItem('rk-chat-open') === '1') openPanel(); } catch (e) {}
1303
+ try {
1304
+ var reopen = sessionStorage.getItem('rk-chat-open');
1305
+ if (isEditorDock) { /* handled below */ }
1306
+ else if (isChatPage) { if (reopen === 'files') openPanel(true); }
1307
+ else if (reopen === '1') openPanel();
1308
+ } catch (e) {}
1309
+
1310
+ // Editor dock: force the panel open and pinned as a left column. Reuses the
1311
+ // normal openPanel path so the live /chat-dock/boot fetch + threads + files
1312
+ // all wire up exactly as on the reskin pages.
1313
+ if (editorDockWide) {
1314
+ panel.classList.add('rk-aichat--editor');
1315
+ if (minBtn) minBtn.hidden = true;
1316
+ openPanel();
1317
+ panel.classList.remove('is-right');
1318
+ document.body.classList.add('rk-chat-left');
1319
+ // The editor dock force-opens the panel, but that's a property of the editor
1320
+ // shell, NOT a user choice to keep chat open — so don't let it persist. Otherwise
1321
+ // navigating out (e.g. Back to Library) would re-pop the panel on the next page.
1322
+ try { sessionStorage.removeItem('rk-chat-open'); } catch (e) {}
1323
+ // Start as a clean chat column (Files/History collapsed) WITHOUT persisting a
1324
+ // mode — setLeftMode writes localStorage, which the reskin pages share. The
1325
+ // toggle buttons still open the drawers on demand.
1326
+ panel.classList.remove('has-files', 'has-history');
1327
+ var ftog = document.getElementById('rkFilesToggle');
1328
+ if (ftog) { ftog.classList.remove('is-on'); ftog.setAttribute('aria-pressed', 'false'); }
1329
+ var htog = document.getElementById('rkHistoryToggle');
1330
+ if (htog) { htog.classList.remove('is-on'); htog.setAttribute('aria-pressed', 'false'); }
1331
+ var catog = document.getElementById('rkAichatAttach');
1332
+ if (catog) { catog.classList.remove('is-on'); catog.setAttribute('aria-pressed', 'false'); }
1333
+ }
1334
+ })();
1335
+
1336
+ // ── subtle per-video loading indicators ──────────────────────────────────────
1337
+ // A small spinner appears over ANY <video> while it is actively fetching data
1338
+ // (initial buffer OR a mid-playback rebuffer) and fades out the moment the video
1339
+ // has enough data to paint/play. Self-contained so it works on every reskin page
1340
+ // regardless of the chat dock. It only shows while the browser is genuinely
1341
+ // LOADING (networkState === 2), so idle preload="none" videos never spin.
1342
+ (function () {
1343
+ function host(v) { return v.parentElement; }
1344
+ function spinner(v, make) {
1345
+ var p = host(v);
1346
+ if (!p) return null;
1347
+ var s = p.querySelector(':scope > .rk-vspin');
1348
+ if (!s && make) {
1349
+ s = document.createElement('span');
1350
+ s.className = 'rk-vspin';
1351
+ s.setAttribute('aria-hidden', 'true');
1352
+ p.appendChild(s);
1353
+ }
1354
+ return s || null;
1355
+ }
1356
+ // NETWORK_LOADING === 2 && readyState < HAVE_FUTURE_DATA (3)
1357
+ function loading(v) { return v.networkState === 2 && v.readyState < 3; }
1358
+ function show(v) { var s = spinner(v, true); if (s) s.classList.add('is-on'); }
1359
+ function hide(v) { var s = spinner(v, false); if (s) s.classList.remove('is-on'); }
1360
+ function sync(v) { if (loading(v)) show(v); else hide(v); }
1361
+ function wire(v) {
1362
+ if (v.__rkVload) return;
1363
+ v.__rkVload = true;
1364
+ // ready / has-data events → definitely stop spinning
1365
+ ['loadeddata', 'canplay', 'canplaythrough', 'playing', 'error', 'abort', 'suspend', 'emptied']
1366
+ .forEach(function (ev) { v.addEventListener(ev, function () { hide(v); }); });
1367
+ // fetch / rebuffer events → spin only if actually loading
1368
+ ['loadstart', 'progress', 'waiting', 'stalled', 'seeking']
1369
+ .forEach(function (ev) { v.addEventListener(ev, function () { sync(v); }); });
1370
+ sync(v);
1371
+ }
1372
+ function scan(root) { (root || document).querySelectorAll('video').forEach(wire); }
1373
+ if (document.readyState === 'loading') {
1374
+ document.addEventListener('DOMContentLoaded', function () { scan(); });
1375
+ } else { scan(); }
1376
+ // catch lazily-inserted (TikTok viewer) and lazily-hydrated (data-vsrc → src) videos
1377
+ if ('MutationObserver' in window) {
1378
+ new MutationObserver(function (muts) {
1379
+ for (var i = 0; i < muts.length; i++) {
1380
+ var m = muts[i];
1381
+ if (m.type === 'attributes') {
1382
+ if (m.target && m.target.tagName === 'VIDEO') { wire(m.target); sync(m.target); }
1383
+ continue;
1384
+ }
1385
+ if (!m.addedNodes) continue;
1386
+ for (var j = 0; j < m.addedNodes.length; j++) {
1387
+ var n = m.addedNodes[j];
1388
+ if (!n || n.nodeType !== 1) continue;
1389
+ if (n.tagName === 'VIDEO') wire(n);
1390
+ else if (n.querySelectorAll) scan(n);
1391
+ }
1392
+ }
1393
+ }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] });
1394
+ }
631
1395
  })();`;
632
1396
  /** Wrap page content in a complete standalone reskin HTML document. */
633
1397
  export function reskinDocument(input) {
@@ -635,23 +1399,46 @@ export function reskinDocument(input) {
635
1399
  const active = input.activeSlug ?? null;
636
1400
  const pageCss = input.pageCss ? `\n/* page-scoped */\n${input.pageCss}\n` : "";
637
1401
  const chromeScript = chrome === "full" ? `\n<script>${RESKIN_CHROME_SCRIPT}</script>` : "";
638
- const script = (input.script ? `\n<script>${input.script}</script>` : "") + chromeScript;
1402
+ // Full-chrome pages carry the chat dock, whose Files drawer is the reusable
1403
+ // directory-explorer component — so its bundle loads on every such page.
1404
+ const baseModules = chrome === "full" ? ["/assets/file-directory-app.js"] : [];
1405
+ const moduleScripts = [...baseModules, ...(input.moduleScripts ?? [])]
1406
+ .map((src) => `\n<script type="module" src="${rkEscape(src)}"></script>`)
1407
+ .join("");
1408
+ const script = (input.script ? `\n<script>${input.script}</script>` : "") + chromeScript + moduleScripts;
639
1409
  const shell = chrome === "full"
640
1410
  ? `<div class="rk-app">
641
- ${renderSidebar(active)}
1411
+ ${renderSidebar(active, input.account)}
642
1412
  <div class="rk-content">
643
1413
  ${input.body}
644
1414
  </div>
645
1415
  ${renderChatDock(active)}
646
1416
  </div>`
647
1417
  : input.body;
1418
+ const pageTitle = rkBrandTitle(input.title);
1419
+ const pageDesc = rkBrandTitle(input.description ?? input.title);
648
1420
  return `<!doctype html>
649
1421
  <html lang="en">
650
1422
  <head>
651
1423
  <meta charset="utf-8">
652
1424
  <meta name="viewport" content="width=device-width, initial-scale=1">
653
- <title>${rkEscape(input.title.replace("vidfarm reskin", "vidfarm"))}</title>
654
- <meta name="description" content="${rkEscape((input.description ?? input.title).replace("vidfarm reskin", "vidfarm"))}">
1425
+ <link rel="icon" href="/assets/favicon.ico" sizes="any">
1426
+ <link rel="apple-touch-icon" href="/assets/logo-vidfarm.png">
1427
+ <title>${rkEscape(pageTitle)}</title>
1428
+ <meta name="description" content="${rkEscape(pageDesc)}">
1429
+ <meta name="theme-color" content="#f8f4eb">
1430
+ <meta name="robots" content="index, follow">
1431
+ <meta name="application-name" content="${BRAND_NAME}">
1432
+ <meta property="og:type" content="website">
1433
+ <meta property="og:site_name" content="${BRAND_NAME}">
1434
+ <meta property="og:title" content="${rkEscape(pageTitle)}">
1435
+ <meta property="og:description" content="${rkEscape(pageDesc)}">
1436
+ <meta property="og:url" content="${BRAND_ORIGIN}">
1437
+ <meta property="og:image" content="${BRAND_OG_IMAGE}">
1438
+ <meta name="twitter:card" content="summary_large_image">
1439
+ <meta name="twitter:title" content="${rkEscape(pageTitle)}">
1440
+ <meta name="twitter:description" content="${rkEscape(pageDesc)}">
1441
+ <meta name="twitter:image" content="${BRAND_OG_IMAGE}">
655
1442
  ${RESKIN_FONT_LINKS}
656
1443
  <style>${RESKIN_CSS}${pageCss}</style>
657
1444
  </head>