@mevdragon/vidfarm-devcli 0.17.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.
- package/.agents/skills/vidfarm-media/SKILL.md +43 -6
- package/SKILL.director.md +37 -23
- package/SKILL.platform.md +6 -6
- package/demo/dist/app.js +69 -69
- package/demo/dist/favicon.ico +0 -0
- package/dist/src/app.js +1832 -213
- package/dist/src/cli.js +238 -17
- package/dist/src/devcli/clip-store.js +29 -2
- package/dist/src/devcli/clips.js +116 -73
- package/dist/src/devcli/composition-edit.js +262 -0
- package/dist/src/devcli/timeline-edit.js +283 -0
- package/dist/src/editor-chat.js +29 -6
- package/dist/src/frontend/discover-client.js +130 -0
- package/dist/src/frontend/discover-store.js +23 -0
- package/dist/src/frontend/file-directory.js +744 -0
- package/dist/src/frontend/template-editor-chat.js +22 -19
- package/dist/src/landing-page.js +24 -7
- package/dist/src/page-shell.js +25 -1
- package/dist/src/reskin/agency-page.js +214 -170
- package/dist/src/reskin/calendar-page.js +503 -187
- package/dist/src/reskin/chat-page.js +739 -299
- package/dist/src/reskin/discover-page.js +1450 -279
- package/dist/src/reskin/document.js +1392 -16
- package/dist/src/reskin/help-page.js +139 -100
- package/dist/src/reskin/index-page.js +1 -1
- package/dist/src/reskin/inpaint-page.js +547 -0
- package/dist/src/reskin/job-runs-page.js +355 -127
- package/dist/src/reskin/library-page.js +1188 -317
- package/dist/src/reskin/login-page.js +124 -87
- package/dist/src/reskin/pricing-page.js +197 -166
- package/dist/src/reskin/settings-page.js +566 -187
- package/dist/src/reskin/theme.js +434 -17
- package/dist/src/services/clip-curation/gemini.js +5 -0
- package/dist/src/services/clip-curation/hunt.js +79 -1
- package/dist/src/services/clip-curation/index.js +2 -1
- package/dist/src/services/clip-curation/local-agent.js +4 -3
- package/dist/src/services/clip-curation/media-select.js +85 -0
- package/dist/src/services/clip-curation/query.js +5 -1
- package/dist/src/services/clip-curation/refine.js +50 -20
- package/dist/src/services/clip-curation/scan.js +10 -3
- package/dist/src/services/clip-curation/taxonomy.js +3 -1
- package/dist/src/services/clip-curation/taxonomy.v1.json +13 -1
- package/dist/src/services/clip-records.js +14 -1
- package/dist/src/services/clip-search.js +43 -13
- package/dist/src/services/file-directory.js +114 -0
- package/dist/src/services/storage.js +24 -1
- package/dist/src/services/upstream.js +5 -5
- package/dist/src/template-editor-shell.js +16 -2
- package/package.json +1 -1
- package/public/assets/discover-client-app.js +1 -0
- package/public/assets/file-directory-app.js +2 -0
- package/public/assets/homepage-client-app.js +12 -12
- package/public/assets/page-runtime-client-app.js +24 -24
- package/src/assets/favicon.ico +0 -0
- 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
|
|
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,47 +22,1423 @@ export function rkEscape(value) {
|
|
|
22
22
|
.replace(/"/g, """)
|
|
23
23
|
.replace(/'/g, "'");
|
|
24
24
|
}
|
|
25
|
-
|
|
26
|
-
|
|
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
|
+
}
|
|
36
|
+
/** The sidebar shows only the core app pages (not every reskinned page).
|
|
37
|
+
* Other pages stay reachable from the /reskin gallery (brand link). */
|
|
38
|
+
const SIDEBAR_NAV = [
|
|
39
|
+
{ slug: "discover", label: "Discover" },
|
|
40
|
+
{ slug: "chat", label: "Chat" },
|
|
41
|
+
{ slug: "library", label: "Library" },
|
|
42
|
+
{ slug: "calendar", label: "Calendar" },
|
|
43
|
+
{ slug: "help", label: "Guides" },
|
|
44
|
+
{ slug: "settings", label: "Settings" }
|
|
45
|
+
];
|
|
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) {
|
|
69
|
+
const items = SIDEBAR_NAV.map((p) => {
|
|
27
70
|
const active = p.slug === activeSlug ? " is-active" : "";
|
|
28
|
-
return `<a class="rk-sidebar-item${active}" href="
|
|
71
|
+
return `<a class="rk-sidebar-item${active}" href="/${p.slug}"${p.slug === activeSlug ? ` aria-current="page"` : ""}>${p.label}</a>`;
|
|
29
72
|
}).join("");
|
|
30
|
-
|
|
31
|
-
|
|
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.
|
|
32
77
|
return `<aside class="rk-sidebar">
|
|
33
|
-
<a class="rk-sidebar-brand" href="/
|
|
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>
|
|
34
83
|
<nav class="rk-sidebar-nav" aria-label="Reskin pages">
|
|
35
|
-
<a class="rk-sidebar-item${homeActive}" href="/reskin">Gallery</a>
|
|
36
|
-
<div class="rk-sidebar-sep"></div>
|
|
37
84
|
${items}
|
|
38
85
|
</nav>
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
86
|
+
${renderSidebarAccount(account)}
|
|
87
|
+
</aside>`;
|
|
88
|
+
}
|
|
89
|
+
/** Draggable chat FAB (defaults to the old sidebar-foot spot, bottom-left) +
|
|
90
|
+
* the popup AI chat panel it toggles. Sample chat only — this is the design
|
|
91
|
+
* sandbox, so the panel demos the UI rather than hitting a live agent. The
|
|
92
|
+
* old "compare with live page" link survives as the ↗ tool in the panel head. */
|
|
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>`;
|
|
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">
|
|
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>
|
|
109
|
+
</button>
|
|
110
|
+
<aside class="rk-aichat has-files" id="rkAichat" hidden aria-label="AI chat panel">
|
|
111
|
+
<div class="rk-aichat-files" id="rkAichatFiles" aria-label="Files">
|
|
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>
|
|
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>
|
|
123
|
+
</div>
|
|
124
|
+
<div class="rk-aichat-main">
|
|
125
|
+
<header class="rk-aichat-head">
|
|
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>
|
|
132
|
+
</button>
|
|
133
|
+
<button class="rk-aichat-tool" id="rkAichatMin" type="button" title="Minimize" aria-label="Minimize chat">—</button>
|
|
134
|
+
</header>
|
|
135
|
+
<div class="rk-aichat-log" id="rkAichatLog">
|
|
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>
|
|
137
|
+
</div>
|
|
138
|
+
<div class="rk-aichat-chips" id="rkAichatChips"></div>
|
|
139
|
+
<form class="rk-aichat-composer" id="rkAichatForm">
|
|
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>
|
|
147
|
+
</form>
|
|
42
148
|
</div>
|
|
43
149
|
</aside>`;
|
|
44
150
|
}
|
|
151
|
+
/** Chrome behavior: FAB drag (click-vs-drag threshold, viewport clamp, position
|
|
152
|
+
* persisted in localStorage) + panel toggle. The panel anchors to whichever
|
|
153
|
+
* half of the viewport the FAB sits in so it is never cut off; when it opens
|
|
154
|
+
* on the left it replaces the sidebar nav (body.rk-chat-left). Open state
|
|
155
|
+
* survives page navigation via sessionStorage. Plain IIFE — no backticks or
|
|
156
|
+
* dollar-brace inside (it is embedded in a template literal). */
|
|
157
|
+
export const RESKIN_CHROME_SCRIPT = `(() => {
|
|
158
|
+
var fab = document.getElementById('rkFab');
|
|
159
|
+
var panel = document.getElementById('rkAichat');
|
|
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;
|
|
167
|
+
var minBtn = document.getElementById('rkAichatMin');
|
|
168
|
+
var form = document.getElementById('rkAichatForm');
|
|
169
|
+
var input = document.getElementById('rkAichatInput');
|
|
170
|
+
var log = document.getElementById('rkAichatLog');
|
|
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;
|
|
177
|
+
|
|
178
|
+
function clamp(v, lo, hi) { return Math.max(lo, Math.min(hi, v)); }
|
|
179
|
+
|
|
180
|
+
// offsetWidth/offsetLeft (not getBoundingClientRect) so the hover/drag/open
|
|
181
|
+
// transforms never skew the clamp math
|
|
182
|
+
function placeFab(x, y) {
|
|
183
|
+
x = clamp(x, MARGIN, window.innerWidth - fab.offsetWidth - MARGIN);
|
|
184
|
+
y = clamp(y, MARGIN, window.innerHeight - fab.offsetHeight - MARGIN);
|
|
185
|
+
fab.style.left = x + 'px';
|
|
186
|
+
fab.style.top = y + 'px';
|
|
187
|
+
fab.style.bottom = 'auto';
|
|
188
|
+
return { x: x, y: y };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
var saved = JSON.parse(localStorage.getItem('rk-fab-pos') || 'null');
|
|
193
|
+
if (saved && typeof saved.x === 'number') placeFab(saved.x, saved.y);
|
|
194
|
+
} catch (e) {}
|
|
195
|
+
|
|
196
|
+
function anchorPanel() {
|
|
197
|
+
var r = fab.getBoundingClientRect();
|
|
198
|
+
var onRight = r.left + r.width / 2 > window.innerWidth / 2;
|
|
199
|
+
panel.classList.toggle('is-right', onRight);
|
|
200
|
+
document.body.classList.toggle('rk-chat-left', !panel.hidden && !onRight);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function openPanel(filesOnly) {
|
|
204
|
+
panel.hidden = false;
|
|
205
|
+
panel.classList.toggle('is-files-only', !!filesOnly);
|
|
206
|
+
fab.classList.add('is-open');
|
|
207
|
+
fab.setAttribute('aria-expanded', 'true');
|
|
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();
|
|
225
|
+
refreshFilesOnOpen();
|
|
226
|
+
if (!filesOnly && input) input.focus();
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function closePanel() {
|
|
230
|
+
// Editor dock (wide) is a permanent column — minimize / Escape can't close it.
|
|
231
|
+
if (editorDockWide) return;
|
|
232
|
+
panel.hidden = true;
|
|
233
|
+
panel.classList.remove('is-files-only');
|
|
234
|
+
fab.classList.remove('is-open');
|
|
235
|
+
fab.setAttribute('aria-expanded', 'false');
|
|
236
|
+
document.body.classList.remove('rk-chat-left');
|
|
237
|
+
try { sessionStorage.removeItem('rk-chat-open'); } catch (e) {}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
var drag = null;
|
|
241
|
+
fab.addEventListener('pointerdown', function (e) {
|
|
242
|
+
drag = { sx: e.clientX, sy: e.clientY, ox: fab.offsetLeft, oy: fab.offsetTop, moved: false, last: null };
|
|
243
|
+
fab.setPointerCapture(e.pointerId);
|
|
244
|
+
});
|
|
245
|
+
fab.addEventListener('pointermove', function (e) {
|
|
246
|
+
if (!drag) return;
|
|
247
|
+
var dx = e.clientX - drag.sx;
|
|
248
|
+
var dy = e.clientY - drag.sy;
|
|
249
|
+
if (!drag.moved && Math.hypot(dx, dy) < 6) return;
|
|
250
|
+
drag.moved = true;
|
|
251
|
+
fab.classList.add('is-dragging');
|
|
252
|
+
drag.last = placeFab(drag.ox + dx, drag.oy + dy);
|
|
253
|
+
});
|
|
254
|
+
fab.addEventListener('pointerup', function () {
|
|
255
|
+
if (!drag) return;
|
|
256
|
+
var moved = drag.moved;
|
|
257
|
+
if (drag.last) {
|
|
258
|
+
try { localStorage.setItem('rk-fab-pos', JSON.stringify(drag.last)); } catch (e) {}
|
|
259
|
+
}
|
|
260
|
+
fab.classList.remove('is-dragging');
|
|
261
|
+
drag = null;
|
|
262
|
+
if (!moved) openPanel();
|
|
263
|
+
});
|
|
264
|
+
fab.addEventListener('pointercancel', function () {
|
|
265
|
+
fab.classList.remove('is-dragging');
|
|
266
|
+
drag = null;
|
|
267
|
+
});
|
|
268
|
+
fab.addEventListener('click', function (e) {
|
|
269
|
+
if (e.detail === 0 && panel.hidden) openPanel();
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
if (minBtn) minBtn.addEventListener('click', closePanel);
|
|
273
|
+
document.addEventListener('keydown', function (e) {
|
|
274
|
+
if (e.key === 'Escape' && !panel.hidden) closePanel();
|
|
275
|
+
});
|
|
276
|
+
window.addEventListener('resize', function () {
|
|
277
|
+
if (fab.style.top) {
|
|
278
|
+
var pos = placeFab(fab.offsetLeft, fab.offsetTop);
|
|
279
|
+
try { localStorage.setItem('rk-fab-pos', JSON.stringify(pos)); } catch (e) {}
|
|
280
|
+
}
|
|
281
|
+
if (!panel.hidden) anchorPanel();
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
function bubble(kind, text) {
|
|
285
|
+
var el = document.createElement('div');
|
|
286
|
+
el.className = 'rk-aichat-msg ' + kind;
|
|
287
|
+
el.textContent = text;
|
|
288
|
+
log.appendChild(el);
|
|
289
|
+
log.scrollTop = log.scrollHeight;
|
|
290
|
+
return el;
|
|
291
|
+
}
|
|
292
|
+
function logBottom() { if (log) log.scrollTop = log.scrollHeight; }
|
|
293
|
+
|
|
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
|
+
})();
|
|
299
|
+
|
|
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) {}
|
|
339
|
+
}
|
|
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;
|
|
348
|
+
}
|
|
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 };
|
|
354
|
+
}
|
|
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 ''; }
|
|
368
|
+
}
|
|
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; })
|
|
374
|
+
.then(function (j) {
|
|
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();
|
|
388
|
+
})
|
|
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;
|
|
432
|
+
}
|
|
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
|
+
}
|
|
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();
|
|
470
|
+
return wrap;
|
|
471
|
+
}
|
|
472
|
+
function escapeHtml(s) { return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); }
|
|
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">×</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;
|
|
542
|
+
var b = document.createElement('button');
|
|
543
|
+
b.type = 'button';
|
|
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); });
|
|
553
|
+
return b;
|
|
554
|
+
}
|
|
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';
|
|
568
|
+
}
|
|
569
|
+
|
|
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;
|
|
584
|
+
}
|
|
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('');
|
|
607
|
+
}
|
|
608
|
+
|
|
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 = '×';
|
|
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();
|
|
681
|
+
}
|
|
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();
|
|
760
|
+
}
|
|
761
|
+
|
|
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.');
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
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');
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
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.");
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
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)));
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
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
|
+
|
|
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
|
+
}
|
|
1080
|
+
if (selected.some(function (f) { return f.id === it.id; })) { flashChip(it.id); return; }
|
|
1081
|
+
selected.push(it);
|
|
1082
|
+
renderChips();
|
|
1083
|
+
if (input) input.focus();
|
|
1084
|
+
}
|
|
1085
|
+
function renderChips() {
|
|
1086
|
+
if (!chipsEl) return;
|
|
1087
|
+
chipsEl.innerHTML = '';
|
|
1088
|
+
selected.forEach(function (f, i) {
|
|
1089
|
+
var chip = document.createElement('span');
|
|
1090
|
+
chip.className = 'rk-aichat-chip';
|
|
1091
|
+
chip.setAttribute('data-id', f.id);
|
|
1092
|
+
var label = document.createElement('button');
|
|
1093
|
+
label.type = 'button';
|
|
1094
|
+
label.className = 'rk-aichat-chip-label';
|
|
1095
|
+
label.title = 'Preview ' + f.name;
|
|
1096
|
+
label.textContent = f.name;
|
|
1097
|
+
if (f.viewUrl) label.addEventListener('click', function () { openFilePreview(selected, i); });
|
|
1098
|
+
var x = document.createElement('button');
|
|
1099
|
+
x.type = 'button';
|
|
1100
|
+
x.setAttribute('aria-label', 'Remove ' + f.name);
|
|
1101
|
+
x.textContent = '×';
|
|
1102
|
+
x.addEventListener('click', function () {
|
|
1103
|
+
selected = selected.filter(function (s) { return s.id !== f.id; });
|
|
1104
|
+
renderChips();
|
|
1105
|
+
});
|
|
1106
|
+
chip.appendChild(label); chip.appendChild(x);
|
|
1107
|
+
chipsEl.appendChild(chip);
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
function flashChip(id) {
|
|
1111
|
+
var chip = chipsEl && chipsEl.querySelector('[data-id="' + id + '"]');
|
|
1112
|
+
if (!chip) return;
|
|
1113
|
+
chip.style.transition = 'none';
|
|
1114
|
+
chip.style.transform = 'scale(1.08)';
|
|
1115
|
+
setTimeout(function () { chip.style.transition = 'transform .18s'; chip.style.transform = 'none'; }, 20);
|
|
1116
|
+
}
|
|
1117
|
+
function clearChips() { selected = []; renderChips(); }
|
|
1118
|
+
|
|
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');
|
|
1130
|
+
if (filesToggle) {
|
|
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');
|
|
1137
|
+
}
|
|
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();
|
|
1146
|
+
if (!panel.hidden) anchorPanel();
|
|
1147
|
+
}
|
|
1148
|
+
function refreshFilesOnOpen() {
|
|
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 () {});
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
if (filesToggle) {
|
|
1269
|
+
filesToggle.addEventListener('click', function () { setLeftMode(leftMode() === 'files' ? '' : 'files'); });
|
|
1270
|
+
}
|
|
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).
|
|
1297
|
+
try {
|
|
1298
|
+
var savedMode = localStorage.getItem('rk-left-mode');
|
|
1299
|
+
setLeftMode(savedMode === null ? 'files' : savedMode);
|
|
1300
|
+
} catch (e) { setLeftMode('files'); }
|
|
1301
|
+
renderHistory();
|
|
1302
|
+
|
|
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
|
+
}
|
|
1395
|
+
})();`;
|
|
45
1396
|
/** Wrap page content in a complete standalone reskin HTML document. */
|
|
46
1397
|
export function reskinDocument(input) {
|
|
47
1398
|
const chrome = input.chrome ?? "full";
|
|
48
1399
|
const active = input.activeSlug ?? null;
|
|
49
1400
|
const pageCss = input.pageCss ? `\n/* page-scoped */\n${input.pageCss}\n` : "";
|
|
50
|
-
const
|
|
1401
|
+
const chromeScript = chrome === "full" ? `\n<script>${RESKIN_CHROME_SCRIPT}</script>` : "";
|
|
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;
|
|
51
1409
|
const shell = chrome === "full"
|
|
52
1410
|
? `<div class="rk-app">
|
|
53
|
-
${renderSidebar(active)}
|
|
1411
|
+
${renderSidebar(active, input.account)}
|
|
54
1412
|
<div class="rk-content">
|
|
55
1413
|
${input.body}
|
|
56
1414
|
</div>
|
|
1415
|
+
${renderChatDock(active)}
|
|
57
1416
|
</div>`
|
|
58
1417
|
: input.body;
|
|
1418
|
+
const pageTitle = rkBrandTitle(input.title);
|
|
1419
|
+
const pageDesc = rkBrandTitle(input.description ?? input.title);
|
|
59
1420
|
return `<!doctype html>
|
|
60
1421
|
<html lang="en">
|
|
61
1422
|
<head>
|
|
62
1423
|
<meta charset="utf-8">
|
|
63
1424
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
64
|
-
<
|
|
65
|
-
<
|
|
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}">
|
|
66
1442
|
${RESKIN_FONT_LINKS}
|
|
67
1443
|
<style>${RESKIN_CSS}${pageCss}</style>
|
|
68
1444
|
</head>
|