@kenkaiiii/ggcoder 5.101.0 → 5.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/assets/skills/gg-guide/references/code-mode.md +11 -0
  2. package/dist/app-sidecar/live-preview/dev-url.d.ts +32 -0
  3. package/dist/app-sidecar/live-preview/dev-url.js +97 -0
  4. package/dist/app-sidecar/live-preview/dev-url.js.map +1 -0
  5. package/dist/app-sidecar/live-preview/frame-server.d.ts +31 -0
  6. package/dist/app-sidecar/live-preview/frame-server.js +193 -0
  7. package/dist/app-sidecar/live-preview/frame-server.js.map +1 -0
  8. package/dist/app-sidecar/live-preview/manager.d.ts +44 -0
  9. package/dist/app-sidecar/live-preview/manager.js +215 -0
  10. package/dist/app-sidecar/live-preview/manager.js.map +1 -0
  11. package/dist/app-sidecar/live-preview/proxy.d.ts +30 -0
  12. package/dist/app-sidecar/live-preview/proxy.js +235 -0
  13. package/dist/app-sidecar/live-preview/proxy.js.map +1 -0
  14. package/dist/app-sidecar/live-preview/routes.d.ts +4 -0
  15. package/dist/app-sidecar/live-preview/routes.js +52 -0
  16. package/dist/app-sidecar/live-preview/routes.js.map +1 -0
  17. package/dist/app-sidecar/live-preview/servers.d.ts +36 -0
  18. package/dist/app-sidecar/live-preview/servers.js +228 -0
  19. package/dist/app-sidecar/live-preview/servers.js.map +1 -0
  20. package/dist/app-sidecar/prompt-routes.js +21 -3
  21. package/dist/app-sidecar/prompt-routes.js.map +1 -1
  22. package/dist/app-sidecar.js +73 -30
  23. package/dist/app-sidecar.js.map +1 -1
  24. package/dist/core/agent-session/verification-tracker.js +2 -10
  25. package/dist/core/agent-session/verification-tracker.js.map +1 -1
  26. package/dist/core/live-preview.d.ts +24 -0
  27. package/dist/core/live-preview.js +76 -0
  28. package/dist/core/live-preview.js.map +1 -0
  29. package/dist/core/prompt-commands.js +14 -5
  30. package/dist/core/prompt-commands.js.map +1 -1
  31. package/dist/core/session-history.js +15 -3
  32. package/dist/core/session-history.js.map +1 -1
  33. package/dist/tools/bash.d.ts +2 -2
  34. package/dist/tools/bash.js +359 -354
  35. package/dist/tools/bash.js.map +1 -1
  36. package/dist/tools/live-preview.d.ts +21 -0
  37. package/dist/tools/live-preview.js +37 -0
  38. package/dist/tools/live-preview.js.map +1 -0
  39. package/package.json +4 -4
@@ -55,6 +55,15 @@ A Code-mode window is one session on one project folder. You type in the compose
55
55
  - Commands in the added folder's `.gg/commands` show up in the `/` menu.
56
56
  - To drop one again, click **Remove folder** (it appears right after **Add folder** once a folder is added). The **Added folders** panel lists each folder with its own **Remove** key.
57
57
 
58
+ ## Live preview
59
+
60
+ - Click **Live preview** in the **More** panel (the ⋯ key on the bottom bar). GG finds this project's running dev server, whether GG started it or you ran it in your own terminal, opens the app in your normal browser and puts its chat at the bottom of the page. Nothing to install. The key's light is on while the preview runs.
61
+ - If no dev server is running for the project, click **Start dev server**: GG starts it in the background and opens the preview. **Other address** lets you type one instead, for example `localhost:3000`. https dev servers aren't supported yet.
62
+ - Each window previews only its own project, so several projects can each have a preview open at once. When a project runs more than one server, such as a site and its API, GG picks the one that serves a web page.
63
+ - On the page, click the pointer key next to the message box, then click any element, or just right-click it (Shift+right-click keeps the browser's menu). Your message goes to GG with that element. Esc drops the picked element and lets you pick another; Esc again leaves pick mode. The minus key tucks the chat away.
64
+ - The preview has its own chat, separate from the window's conversation. The panel shows the link with **Open** and **Stop**. Closing the window stops it.
65
+ - The preview runs on its own port, so sign-in redirects and saved browser data from your dev server's port don't carry over.
66
+
58
67
  ## Slash commands
59
68
 
60
69
  Type `/` to open the menu. You only see commands in a Code-mode window.
@@ -200,6 +209,8 @@ Q: How do I add tasks and run them?
200
209
  A: Ask GG to add tasks, then open **Tasks** in the deck and click **Run** or **Run all**.
201
210
  Q: How do I add my own slash command?
202
211
  A: Put a Markdown file in the project's `.gg/commands/` folder. Its file name becomes the command, unless a `name:` line at the top sets another name.
212
+ Q: How do I see my web app and talk to GG from it?
213
+ A: Click **Live preview** in the **More** panel (the ⋯ key). If your dev server isn't running yet, click **Start dev server**. Your app opens in the browser with GG's chat on it; right-click an element to ask about it.
203
214
  Q: How do I work on two folders at once?
204
215
  A: Click **Add folder** in the **More** panel (the ⋯ key on the bottom bar) and pick the folder. To drop it, click **Remove folder** and then **Remove** next to it.
205
216
  Q: Where can I keep private notes?
@@ -0,0 +1,32 @@
1
+ import type { BackgroundProcess } from "../../core/process-manager.js";
2
+ import type { Probe } from "./servers.js";
3
+ export type DevUrlResult = {
4
+ kind: "found";
5
+ url: string;
6
+ command: string;
7
+ } | {
8
+ kind: "https";
9
+ url: string;
10
+ command: string;
11
+ } | {
12
+ kind: "none";
13
+ };
14
+ /** The last local URL in some log text, normalised to localhost; null when none. */
15
+ export declare function lastLocalUrl(text: string): {
16
+ url: string;
17
+ https: boolean;
18
+ } | null;
19
+ export interface DetectOptions {
20
+ /** The window's project. */
21
+ cwd?: string;
22
+ /** Ports of servers running from inside `cwd` that GG didn't start (servers.ts). */
23
+ scan?: (cwd: string) => Promise<number[]>;
24
+ /** What answers on a port; without it the newest printed URL wins unchecked. */
25
+ probe?: (port: number) => Promise<Probe>;
26
+ }
27
+ /**
28
+ * The project's dev server: from the window's background process logs, then from
29
+ * servers running inside the project that the user started themselves. With a
30
+ * probe, only one serving a web page counts (a frontend, never its API).
31
+ */
32
+ export declare function detectDevUrl(processes: readonly BackgroundProcess[], read?: (file: string) => Promise<string>, opts?: DetectOptions): Promise<DevUrlResult>;
@@ -0,0 +1,97 @@
1
+ // Finds the window's dev server: a local URL its background processes printed
2
+ // (Vite's "Local:", Next's "- Local:", etc.), or a server the user started in
3
+ // the project themselves; one serving a web page beats an API.
4
+ import fs from "node:fs/promises";
5
+ const TAIL_BYTES = 64 * 1024;
6
+ // eslint-disable-next-line no-control-regex
7
+ const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g;
8
+ const LOCAL_URL = /\b(https?):\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]):(\d{2,5})(\/[^\s'"<>`)\]]*)?/gi;
9
+ /** The last local URL in some log text, normalised to localhost; null when none. */
10
+ export function lastLocalUrl(text) {
11
+ let last = null;
12
+ for (const m of text.replace(ANSI, "").matchAll(LOCAL_URL))
13
+ last = m;
14
+ if (!last)
15
+ return null;
16
+ const [, scheme, , port, rest] = last;
17
+ const p = Number(port);
18
+ if (!Number.isInteger(p) || p < 1 || p > 65535)
19
+ return null;
20
+ // 0.0.0.0 and ::1 are the same machine; a browser reaches either as localhost.
21
+ const pathPart = (rest ?? "/").replace(/[.,;:]+$/, "") || "/";
22
+ return {
23
+ url: `${scheme.toLowerCase()}://localhost:${p}${pathPart}`,
24
+ https: /^https$/i.test(scheme),
25
+ };
26
+ }
27
+ async function readTail(file) {
28
+ const handle = await fs.open(file, "r");
29
+ try {
30
+ const { size } = await handle.stat();
31
+ const start = Math.max(0, size - TAIL_BYTES);
32
+ const buf = Buffer.alloc(size - start);
33
+ await handle.read(buf, 0, buf.length, start);
34
+ return buf.toString("utf8");
35
+ }
36
+ finally {
37
+ await handle.close();
38
+ }
39
+ }
40
+ /** One local URL per background process that printed one: running first, newest first. */
41
+ async function logCandidates(processes, read) {
42
+ const ordered = [...processes].sort((a, b) => Number(a.exitCode !== null) - Number(b.exitCode !== null) || b.startedAt - a.startedAt);
43
+ const found = [];
44
+ for (const p of ordered) {
45
+ const text = await read(p.logFile).catch(() => "");
46
+ const url = lastLocalUrl(text);
47
+ if (url)
48
+ found.push({ ...url, command: p.command, live: p.exitCode === null, printed: true });
49
+ }
50
+ return found;
51
+ }
52
+ const portOf = (url) => Number(new URL(url).port || 80);
53
+ // Only a web page (or one still compiling) can be previewed: an API never is. An https dev
54
+ // server is reported rather than skipped.
55
+ const RANK = { html: 0, https: 1, slow: 2, http: 9, none: 9 };
56
+ /**
57
+ * The project's dev server: from the window's background process logs, then from
58
+ * servers running inside the project that the user started themselves. With a
59
+ * probe, only one serving a web page counts (a frontend, never its API).
60
+ */
61
+ export async function detectDevUrl(processes, read = readTail, opts = {}) {
62
+ const candidates = await logCandidates(processes, read);
63
+ if (opts.scan && opts.cwd) {
64
+ const seen = new Set(candidates.map((c) => portOf(c.url)));
65
+ for (const port of await opts.scan(opts.cwd).catch(() => [])) {
66
+ if (seen.has(port))
67
+ continue;
68
+ seen.add(port);
69
+ candidates.push({
70
+ url: `http://localhost:${port}/`,
71
+ https: false,
72
+ command: "a dev server started outside GG Coder",
73
+ live: true,
74
+ printed: false,
75
+ });
76
+ }
77
+ }
78
+ const result = (c) => ({
79
+ kind: c.https ? "https" : "found",
80
+ url: c.url,
81
+ command: c.command,
82
+ });
83
+ const probe = opts.probe;
84
+ if (!probe)
85
+ return candidates[0] ? result(candidates[0]) : { kind: "none" };
86
+ const ranked = await Promise.all(candidates
87
+ .filter((c) => c.live)
88
+ .slice(0, 12)
89
+ .map(async (c) => ({ c, rank: RANK[c.https ? "https" : await probe(portOf(c.url))] })));
90
+ const best = ranked.reduce((a, b) => (b.rank < RANK.none && (!a || b.rank < a.rank) ? b : a), null);
91
+ if (best)
92
+ return result(best.c);
93
+ // Nothing answers: the newest printed address, so the preview shows "start your dev server".
94
+ const printed = candidates.find((c) => c.printed);
95
+ return printed ? result(printed) : { kind: "none" };
96
+ }
97
+ //# sourceMappingURL=dev-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dev-url.js","sourceRoot":"","sources":["../../../src/app-sidecar/live-preview/dev-url.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,8EAA8E;AAC9E,+DAA+D;AAC/D,OAAO,EAAE,MAAM,kBAAkB,CAAC;AASlC,MAAM,UAAU,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7B,4CAA4C;AAC5C,MAAM,IAAI,GAAG,0EAA0E,CAAC;AACxF,MAAM,SAAS,GACb,2FAA2F,CAAC;AAE9F,oFAAoF;AACpF,MAAM,UAAU,YAAY,CAAC,I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AE,MAAM,EAAE,CAAC;AACtD,CAAC"}
@@ -0,0 +1,31 @@
1
+ import http from "node:http";
2
+ import type { SessionContext } from "../session-types.js";
3
+ export declare const LIVE_HEADER = "x-gg-live";
4
+ export interface FrameConfig {
5
+ /** The dev server the agent is told about (not the proxy). */
6
+ devUrl: string;
7
+ /** Origins the page proxy is reachable at; the only parents the frame talks to. */
8
+ proxyOrigins: string[];
9
+ }
10
+ export interface FrameServerOptions {
11
+ assetsDir: string;
12
+ session: () => SessionContext | null;
13
+ config: () => FrameConfig;
14
+ /** SSE frames broadcast so far, so a reloaded page rebuilds its transcript. */
15
+ replay: () => readonly string[];
16
+ usage: (provider: "anthropic" | "moonshot") => Promise<unknown>;
17
+ }
18
+ export interface FrameServer {
19
+ server: http.Server;
20
+ listen: (port: number) => Promise<number>;
21
+ close: () => Promise<void>;
22
+ origin: () => string;
23
+ }
24
+ /**
25
+ * Whether an API request comes from the frame itself. Exported for tests.
26
+ * The custom header can't be sent cross-origin without a preflight, and we
27
+ * answer every preflight without CORS headers, so browsers block it.
28
+ */
29
+ export declare function fromFrame(req: http.IncomingMessage, frameOrigin: string): boolean;
30
+ export declare function frameCsp(proxyOrigins: readonly string[]): string;
31
+ export declare function createFrameServer(opts: FrameServerOptions): FrameServer;
@@ -0,0 +1,193 @@
1
+ // Live preview's frame server. It serves the chat (a cross-origin iframe on the
2
+ // previewed page) and the only route from it to the preview session. The page
3
+ // itself is untrusted: its scripts can't read or drive this origin, every API
4
+ // call needs a custom header (so a cross-origin preflight we never approve)
5
+ // and, when the browser sends one, this server's own Origin.
6
+ import fs from "node:fs/promises";
7
+ import http from "node:http";
8
+ import path from "node:path";
9
+ export const LIVE_HEADER = "x-gg-live";
10
+ // The frame's API, and the session route each maps to. Nothing else reaches the session.
11
+ const ROUTES = {
12
+ "/api/events": { method: "GET", to: "/events" },
13
+ "/api/state": { method: "GET", to: "/state" },
14
+ "/api/models": { method: "GET", to: "/models" },
15
+ "/api/model": { method: "POST", to: "/model" },
16
+ "/api/prompt": { method: "POST", to: "/prompt" },
17
+ "/api/cancel": { method: "POST", to: "/cancel" },
18
+ "/api/enhance": { method: "POST", to: "/enhance" },
19
+ "/api/git/overview": { method: "GET", to: "/git/overview" },
20
+ };
21
+ const TYPES = {
22
+ ".html": "text/html; charset=utf-8",
23
+ ".js": "text/javascript; charset=utf-8",
24
+ ".css": "text/css; charset=utf-8",
25
+ ".json": "application/json",
26
+ ".svg": "image/svg+xml",
27
+ ".png": "image/png",
28
+ ".jpg": "image/jpeg",
29
+ ".gif": "image/gif",
30
+ ".webp": "image/webp",
31
+ ".woff2": "font/woff2",
32
+ ".woff": "font/woff",
33
+ ".ttf": "font/ttf",
34
+ ".mp3": "audio/mpeg",
35
+ };
36
+ function send(res, status, body) {
37
+ res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
38
+ res.end(JSON.stringify(body));
39
+ }
40
+ /**
41
+ * Whether an API request comes from the frame itself. Exported for tests.
42
+ * The custom header can't be sent cross-origin without a preflight, and we
43
+ * answer every preflight without CORS headers, so browsers block it.
44
+ */
45
+ export function fromFrame(req, frameOrigin) {
46
+ if (req.headers[LIVE_HEADER] !== "1")
47
+ return false;
48
+ const origin = req.headers.origin;
49
+ if (origin !== undefined && origin !== frameOrigin)
50
+ return false;
51
+ // Browsers always send Origin on POST: a POST without one isn't from the frame.
52
+ if (req.method !== "GET" && origin === undefined)
53
+ return false;
54
+ const site = req.headers["sec-fetch-site"];
55
+ return site === undefined || site === "same-origin";
56
+ }
57
+ export function frameCsp(proxyOrigins) {
58
+ return [
59
+ "default-src 'self'",
60
+ "script-src 'self'",
61
+ "style-src 'self' 'unsafe-inline'",
62
+ "img-src * data: blob:",
63
+ "media-src 'self' data: blob:",
64
+ "font-src 'self' data:",
65
+ "connect-src 'self'",
66
+ "object-src 'none'",
67
+ "base-uri 'none'",
68
+ "form-action 'none'",
69
+ `frame-ancestors ${proxyOrigins.join(" ") || "'none'"}`,
70
+ ].join("; ");
71
+ }
72
+ export function createFrameServer(opts) {
73
+ const port = () => server.address()?.port ?? 0;
74
+ const origin = () => `http://127.0.0.1:${port()}`;
75
+ const root = path.resolve(opts.assetsDir);
76
+ async function serveFile(res, rel, extra = {}) {
77
+ const file = path.resolve(root, `.${rel}`);
78
+ if (file !== root && !file.startsWith(root + path.sep)) {
79
+ send(res, 404, { error: "not found" });
80
+ return;
81
+ }
82
+ const body = await fs.readFile(file).catch(() => null);
83
+ if (!body) {
84
+ send(res, 404, { error: "not found" });
85
+ return;
86
+ }
87
+ res.writeHead(200, {
88
+ "content-type": TYPES[path.extname(file)] ?? "application/octet-stream",
89
+ // Hashed assets can be kept; the entry points change with every build.
90
+ "cache-control": rel.startsWith("/assets/")
91
+ ? "public, max-age=31536000, immutable"
92
+ : "no-store",
93
+ "x-content-type-options": "nosniff",
94
+ ...extra,
95
+ });
96
+ res.end(body);
97
+ }
98
+ function api(req, res, url) {
99
+ if (!fromFrame(req, origin())) {
100
+ send(res, 403, { error: "forbidden" });
101
+ return;
102
+ }
103
+ if (url.pathname === "/api/config" && req.method === "GET") {
104
+ send(res, 200, opts.config());
105
+ return;
106
+ }
107
+ if (url.pathname === "/api/usage" && req.method === "GET") {
108
+ const provider = url.searchParams.get("provider");
109
+ if (provider !== "anthropic" && provider !== "moonshot") {
110
+ send(res, 400, { error: "unsupported usage provider" });
111
+ return;
112
+ }
113
+ opts.usage(provider).then((body) => send(res, 200, body), () => send(res, 500, { error: "Usage is temporarily unavailable." }));
114
+ return;
115
+ }
116
+ const route = ROUTES[url.pathname];
117
+ if (!route || route.method !== req.method) {
118
+ send(res, 404, { error: `${url.pathname} isn't available in the live preview` });
119
+ return;
120
+ }
121
+ const ctx = opts.session();
122
+ if (!ctx) {
123
+ send(res, 503, { error: "Live preview has stopped. Start it again from GG Coder." });
124
+ return;
125
+ }
126
+ req.url = route.to;
127
+ ctx.handle(req, res, route.to, route.method);
128
+ // The events route answers synchronously with its `ready` frame; what the
129
+ // session said before this page loaded follows it, then live events.
130
+ if (route.to === "/events")
131
+ for (const frame of opts.replay())
132
+ res.write(frame);
133
+ }
134
+ const server = http.createServer((req, res) => {
135
+ // Only the address the frame is loaded from: blocks DNS rebinding and keeps one Origin.
136
+ if (req.headers.host !== `127.0.0.1:${port()}`) {
137
+ send(res, 403, { error: "forbidden host" });
138
+ return;
139
+ }
140
+ // Preflights get no CORS grant, so cross-origin pages can't send the custom header.
141
+ if (req.method === "OPTIONS") {
142
+ res.writeHead(204).end();
143
+ return;
144
+ }
145
+ const url = new URL(req.url ?? "/", origin());
146
+ if (url.pathname.startsWith("/api/")) {
147
+ api(req, res, url);
148
+ return;
149
+ }
150
+ if (req.method !== "GET" && req.method !== "HEAD") {
151
+ send(res, 405, { error: "method not allowed" });
152
+ return;
153
+ }
154
+ if (url.pathname === "/page.js") {
155
+ void serveFile(res, "/page.js");
156
+ return;
157
+ }
158
+ if (url.pathname === "/frame" || url.pathname === "/frame.html") {
159
+ void serveFile(res, "/frame.html", {
160
+ "content-security-policy": frameCsp(opts.config().proxyOrigins),
161
+ });
162
+ return;
163
+ }
164
+ if (url.pathname.startsWith("/assets/")) {
165
+ void serveFile(res, url.pathname);
166
+ return;
167
+ }
168
+ send(res, 404, { error: "not found" });
169
+ });
170
+ const sockets = new Set();
171
+ server.on("connection", (s) => {
172
+ sockets.add(s);
173
+ s.on("close", () => sockets.delete(s));
174
+ });
175
+ return {
176
+ server,
177
+ origin,
178
+ listen: (p) => new Promise((resolve, reject) => {
179
+ server.once("error", reject);
180
+ server.listen(p, "127.0.0.1", () => {
181
+ server.off("error", reject);
182
+ resolve(port());
183
+ });
184
+ }),
185
+ close: () => new Promise((resolve) => {
186
+ // Open event streams would hold close() open forever.
187
+ for (const s of sockets)
188
+ s.destroy();
189
+ server.close(() => resolve());
190
+ }),
191
+ };
192
+ }
193
+ //# sourceMappingURL=frame-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frame-server.js","sourceRoot":"","sources":["../../../src/app-sidecar/live-preview/frame-server.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,CAAC,CAAC;IACzC,CAAC,CAAC,CAAC;IAEH,OAAO;QACL,MAAM;QACN,MAAM;QACN,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,CACZ,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC9B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YAC7B,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE;gBACjC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;gBAC5B,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QACJ,KAAK,EAAE,GAAG,EAAE,CACV,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YACtB,sDAAsD;YACtD,KAAK,MAAM,CAAC,IAAI,OAAO;gBAAE,CAAC,CAAC,OAAO,EAAE,CAAC;YACrC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;QAChC,CAAC,CAAC;KACL,CAAC;AACJ,CAAC"}
@@ -0,0 +1,44 @@
1
+ import type { SessionContext } from "../session-types.js";
2
+ import { type DetectOptions } from "./dev-url.js";
3
+ export interface LivePreviewStatus {
4
+ running: boolean;
5
+ /** The link to open in the browser. */
6
+ url: string | null;
7
+ /** The dev server it shows. */
8
+ target: string | null;
9
+ /** No dev server runs for this project: start one, or type its address. */
10
+ needsUrl?: boolean;
11
+ error?: string;
12
+ }
13
+ export interface LivePreviewManagerDeps {
14
+ /** Create (and register) a session in `cwd` that the app never shows as a window. */
15
+ createSession: (cwd: string) => Promise<SessionContext>;
16
+ closeSession: (id: string) => Promise<void>;
17
+ usage: (provider: "anthropic" | "moonshot") => Promise<unknown>;
18
+ /** The built overlay; null when this build doesn't have it. */
19
+ assetsDir: string | null;
20
+ /** Finds servers the user started in the project, and checks what answers (servers.ts). */
21
+ scan?: DetectOptions["scan"];
22
+ probe?: DetectOptions["probe"];
23
+ log?: (message: string, fields?: Record<string, string>) => void;
24
+ /** A window's preview started or stopped (by the user or by the agent). */
25
+ onChange?: (windowId: string, status: LivePreviewStatus) => void;
26
+ }
27
+ /** Where the built overlay is, or null when it was never built. */
28
+ export declare function findLivePreviewAssets(candidates?: readonly string[]): string | null;
29
+ /** A user-typed dev server address as a URL, or an error to show. */
30
+ export declare function parseDevUrl(raw: string): URL | {
31
+ error: string;
32
+ };
33
+ export interface LivePreviewManager {
34
+ start: (window: SessionContext, opts?: {
35
+ url?: string;
36
+ }) => Promise<LivePreviewStatus>;
37
+ stop: (windowId: string) => Promise<LivePreviewStatus>;
38
+ status: (windowId: string) => LivePreviewStatus;
39
+ /** A session went away: stop the preview it owned or was. */
40
+ onSessionClosed: (id: string) => Promise<void>;
41
+ isPreviewSession: (id: string) => boolean;
42
+ stopAll: () => Promise<void>;
43
+ }
44
+ export declare function createLivePreviewManager(deps: LivePreviewManagerDeps): LivePreviewManager;
@@ -0,0 +1,215 @@
1
+ // Live preview, per window: a dedicated agent session for the window's project,
2
+ // the page proxy in front of its dev server and the frame server for the chat.
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { detectDevUrl } from "./dev-url.js";
7
+ import { createFrameServer } from "./frame-server.js";
8
+ import { createPreviewProxy, defaultDownPage } from "./proxy.js";
9
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
10
+ const ASSET_DIRS = [
11
+ // Single-file desktop sidecar: resources live beside app-sidecar.mjs.
12
+ path.resolve(MODULE_DIR, "live-preview"),
13
+ // Running from the repo (tauri dev): gg-app's own build output.
14
+ path.resolve(MODULE_DIR, "../../../../../gg-app/dist-live-preview"),
15
+ ];
16
+ /** Where the built overlay is, or null when it was never built. */
17
+ export function findLivePreviewAssets(candidates = ASSET_DIRS) {
18
+ for (const dir of candidates) {
19
+ if (fs.existsSync(path.join(dir, "page.js")) && fs.existsSync(path.join(dir, "frame.html")))
20
+ return dir;
21
+ }
22
+ return null;
23
+ }
24
+ // Enough to rebuild a long chat after a reload, without growing forever.
25
+ const REPLAY_LIMIT = 5000;
26
+ /** A user-typed dev server address as a URL, or an error to show. */
27
+ export function parseDevUrl(raw) {
28
+ const text = raw.trim();
29
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `http://${text}`;
30
+ let url;
31
+ try {
32
+ url = new URL(withScheme);
33
+ }
34
+ catch {
35
+ return { error: `"${text}" isn't a web address.` };
36
+ }
37
+ if (url.protocol === "https:")
38
+ return { error: httpsError(url.href) };
39
+ if (url.protocol !== "http:")
40
+ return { error: `"${text}" isn't a web address.` };
41
+ if (url.hostname === "0.0.0.0" || url.hostname === "[::1]")
42
+ url.hostname = "localhost";
43
+ return url;
44
+ }
45
+ const httpsError = (url) => `Your dev server runs on https (${url}). Live preview supports http dev servers only for now.`;
46
+ const linkFor = (port, target) => `http://localhost:${port}${target.pathname}${target.search}`;
47
+ /** Listen on the port this project used before, so its address (and storage) stays the same. */
48
+ async function listenNear(listen, port) {
49
+ if (port) {
50
+ try {
51
+ return await listen(port);
52
+ }
53
+ catch {
54
+ /* taken by something else now: any free port */
55
+ }
56
+ }
57
+ return listen(0);
58
+ }
59
+ export function createLivePreviewManager(deps) {
60
+ const log = deps.log ?? (() => { });
61
+ const previews = new Map();
62
+ const starting = new Map();
63
+ // Per project for the app's lifetime: reopening keeps the same address.
64
+ const ports = new Map();
65
+ const statusOf = (p) => p
66
+ ? { running: true, url: linkFor(p.proxyPort, p.target), target: p.target.href }
67
+ : { running: false, url: null, target: null };
68
+ async function teardown(p) {
69
+ previews.delete(p.windowId);
70
+ p.session.clients.delete(p.recorder);
71
+ await Promise.all([p.proxy.close(), p.frame.close()]);
72
+ await deps.closeSession(p.session.id).catch(() => { });
73
+ log("live preview stopped", { window: p.windowId });
74
+ deps.onChange?.(p.windowId, statusOf(undefined));
75
+ }
76
+ async function launch(window, target) {
77
+ const assetsDir = deps.assetsDir;
78
+ if (!assetsDir) {
79
+ return { ...statusOf(undefined), error: "Live preview isn't included in this build." };
80
+ }
81
+ const session = await deps.createSession(window.cwd);
82
+ // Record what the session broadcasts, so a reloaded page rebuilds its chat.
83
+ const replay = [];
84
+ const recorder = {
85
+ id: -1,
86
+ res: {
87
+ write: (frame) => {
88
+ replay.push(frame);
89
+ if (replay.length > REPLAY_LIMIT)
90
+ replay.splice(0, replay.length - REPLAY_LIMIT);
91
+ return true;
92
+ },
93
+ end: () => { },
94
+ },
95
+ };
96
+ session.clients.add(recorder);
97
+ const remembered = ports.get(window.cwd);
98
+ let proxyPort = 0;
99
+ const frame = createFrameServer({
100
+ assetsDir,
101
+ session: () => (previews.get(window.id)?.session === session ? session : null),
102
+ config: () => ({
103
+ devUrl: target.href,
104
+ proxyOrigins: proxyPort
105
+ ? [`http://localhost:${proxyPort}`, `http://127.0.0.1:${proxyPort}`]
106
+ : [],
107
+ }),
108
+ replay: () => replay,
109
+ usage: deps.usage,
110
+ });
111
+ let proxy = null;
112
+ try {
113
+ const framePort = await listenNear(frame.listen, remembered?.frame);
114
+ const inject = `<script defer src="http://127.0.0.1:${framePort}/page.js"></script>`;
115
+ proxy = createPreviewProxy({
116
+ target,
117
+ inject,
118
+ downPage: (t) => defaultDownPage(t, inject),
119
+ });
120
+ proxyPort = await listenNear(proxy.listen, remembered?.proxy);
121
+ ports.set(window.cwd, { proxy: proxyPort, frame: framePort });
122
+ }
123
+ catch (err) {
124
+ session.clients.delete(recorder);
125
+ await Promise.all([proxy?.close(), frame.close()]);
126
+ await deps.closeSession(session.id).catch(() => { });
127
+ throw err;
128
+ }
129
+ const preview = {
130
+ windowId: window.id,
131
+ cwd: window.cwd,
132
+ target,
133
+ session,
134
+ recorder,
135
+ proxy,
136
+ frame,
137
+ proxyPort,
138
+ };
139
+ previews.set(window.id, preview);
140
+ log("live preview started", {
141
+ window: window.id,
142
+ session: session.id,
143
+ target: target.href,
144
+ port: String(proxyPort),
145
+ });
146
+ deps.onChange?.(window.id, statusOf(preview));
147
+ return statusOf(preview);
148
+ }
149
+ async function startOnce(window, opts) {
150
+ let target;
151
+ if (opts.url !== undefined && opts.url.trim()) {
152
+ const parsed = parseDevUrl(opts.url);
153
+ if (!(parsed instanceof URL))
154
+ return { ...statusOf(previews.get(window.id)), error: parsed.error };
155
+ target = parsed;
156
+ }
157
+ else {
158
+ const found = await detectDevUrl(window.session.listBackgroundProcesses(), undefined, {
159
+ cwd: window.cwd,
160
+ scan: deps.scan,
161
+ probe: deps.probe,
162
+ });
163
+ const current = previews.get(window.id);
164
+ if (found.kind === "https")
165
+ return { ...statusOf(current), error: httpsError(found.url) };
166
+ if (found.kind === "none") {
167
+ if (current)
168
+ return statusOf(current);
169
+ return {
170
+ ...statusOf(undefined),
171
+ needsUrl: true,
172
+ error: "No web app is running for this project.",
173
+ };
174
+ }
175
+ target = new URL(found.url);
176
+ }
177
+ const current = previews.get(window.id);
178
+ if (current) {
179
+ if (current.target.origin === target.origin)
180
+ return statusOf(current);
181
+ await teardown(current);
182
+ }
183
+ return launch(window, target);
184
+ }
185
+ return {
186
+ start: (window, opts = {}) => {
187
+ // A double click, or the agent and the user at once: one preview.
188
+ const pending = starting.get(window.id);
189
+ if (pending)
190
+ return pending;
191
+ const run = startOnce(window, opts).finally(() => starting.delete(window.id));
192
+ starting.set(window.id, run);
193
+ return run;
194
+ },
195
+ stop: async (windowId) => {
196
+ await starting.get(windowId)?.catch(() => { });
197
+ const p = previews.get(windowId);
198
+ if (p)
199
+ await teardown(p);
200
+ return statusOf(undefined);
201
+ },
202
+ status: (windowId) => statusOf(previews.get(windowId)),
203
+ onSessionClosed: async (id) => {
204
+ for (const p of [...previews.values()]) {
205
+ if (p.windowId === id || p.session.id === id)
206
+ await teardown(p);
207
+ }
208
+ },
209
+ isPreviewSession: (id) => [...previews.values()].some((p) => p.session.id === id),
210
+ stopAll: async () => {
211
+ await Promise.all([...previews.values()].map((p) => teardown(p).catch(() => { })));
212
+ },
213
+ };
214
+ }
215
+ //# sourceMappingURL=manager.js.map