forked from dyad-sh/dyad
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_handlers.ts
More file actions
2131 lines (1888 loc) · 63.7 KB
/
Copy pathapp_handlers.ts
File metadata and controls
2131 lines (1888 loc) · 63.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ipcMain, app, dialog } from "electron";
import { db, getDatabasePath } from "../../db";
import { apps, chats, messages } from "../../db/schema";
import { desc, eq, like } from "drizzle-orm";
import { createTypedHandler } from "./base";
import { appContracts } from "../types/app";
import type { AppFileSearchResult } from "../types/app";
import { miscContracts } from "../types/misc";
import { systemContracts } from "../types/system";
import fs from "node:fs";
import path from "node:path";
import { getDyadAppPath, getUserDataPath } from "../../paths/paths";
import { ChildProcess, spawn } from "node:child_process";
import { promises as fsPromises } from "node:fs";
// Import our utility modules
import { withLock } from "../utils/lock_utils";
import { getFilesRecursively } from "../utils/file_utils";
import {
runningApps,
processCounter,
removeAppIfCurrentProcess,
stopAppByInfo,
removeDockerVolumesForApp,
setCurrentlySelectedAppId,
startAppGarbageCollection,
} from "../utils/process_manager";
import { getEnvVar } from "../utils/read_env";
import { readSettings } from "../../main/settings";
import { addLog, clearLogs } from "../../lib/log_store";
import fixPath from "fix-path";
import killPort from "kill-port";
import util from "util";
import log from "electron-log";
import {
deploySupabaseFunction,
getSupabaseProjectName,
} from "../../supabase_admin/supabase_management_client";
import { createLoggedHandler } from "./safe_handle";
import { getLanguageModelProviders } from "../shared/language_model_helpers";
import { startProxy } from "../utils/start_proxy_server";
import { createFromTemplate } from "./createFromTemplate";
import {
gitCommit,
gitAdd,
gitInit,
gitListBranches,
gitRenameBranch,
} from "../utils/git_utils";
import { safeSend } from "../utils/safe_sender";
import type { AppOutput } from "../types/misc";
import { normalizePath } from "../../../shared/normalizePath";
import {
isServerFunction,
isSharedServerModule,
deployAllSupabaseFunctions,
extractFunctionNameFromPath,
} from "@/supabase_admin/supabase_utils";
import { getVercelTeamSlug } from "../utils/vercel_utils";
import { storeDbTimestampAtCurrentVersion } from "../utils/neon_timestamp_utils";
import { AppSearchResult } from "@/lib/schemas";
import { getAppPort } from "../../../shared/ports";
import {
getRgExecutablePath,
MAX_FILE_SEARCH_SIZE,
RIPGREP_EXCLUDED_GLOBS,
} from "../utils/ripgrep_utils";
const logger = log.scope("app_handlers");
const handle = createLoggedHandler(logger);
function sanitizeSnippetText(text: string) {
return text.replace(/\s+/g, " ").trim();
}
/**
* Converts a byte offset in UTF-8 encoded string to a character index.
* Ripgrep provides byte offsets, but JavaScript strings use character indices.
* This handles multi-byte UTF-8 characters (emojis, CJK, accented characters) correctly.
*/
function byteOffsetToCharIndex(text: string, byteOffset: number): number {
// Cap the byte offset to the actual byte length of the string
const totalBytes = Buffer.from(text, "utf8").length;
const safeByteOffset = Math.min(byteOffset, totalBytes);
// Find the character index by checking byte counts at each position
// This correctly handles multi-byte characters
for (let i = 0; i <= text.length; i++) {
const bytesUpToIndex = Buffer.from(text.slice(0, i), "utf8").length;
if (bytesUpToIndex >= safeByteOffset) {
return i;
}
}
return text.length;
}
function buildSnippetFromMatch({
lineText,
start,
end,
lineNumber,
}: {
lineText: string;
start: number;
end: number;
lineNumber: number;
}): NonNullable<AppFileSearchResult["snippets"]>[number] {
const safeLine = lineText.replace(/\r?\n$/, "");
// Convert byte offsets to character indices for proper UTF-8 handling
const startChar = byteOffsetToCharIndex(safeLine, start);
const endChar = byteOffsetToCharIndex(safeLine, end);
const before = sanitizeSnippetText(safeLine.slice(0, startChar));
const match = sanitizeSnippetText(safeLine.slice(startChar, endChar));
const after = sanitizeSnippetText(safeLine.slice(endChar));
return {
before,
match,
after,
line: lineNumber,
};
}
function getDefaultCommand(appId: number): string {
const port = getAppPort(appId);
return `(pnpm install && pnpm run dev --port ${port}) || (npm install --legacy-peer-deps && npm run dev -- --port ${port})`;
}
async function copyDir(
source: string,
destination: string,
filter?: (source: string) => boolean,
options?: { excludeNodeModules?: boolean },
) {
await fsPromises.cp(source, destination, {
recursive: true,
filter: (src: string) => {
if (
options?.excludeNodeModules &&
path.basename(src) === "node_modules"
) {
return false;
}
if (filter) {
return filter(src);
}
return true;
},
});
}
// Needed, otherwise electron in MacOS/Linux will not be able
// to find node/pnpm.
fixPath();
async function executeApp({
appPath,
appId,
event, // Keep event for local-node case
isNeon,
installCommand,
startCommand,
}: {
appPath: string;
appId: number;
event: Electron.IpcMainInvokeEvent;
isNeon: boolean;
installCommand?: string | null;
startCommand?: string | null;
}): Promise<void> {
const settings = readSettings();
const runtimeMode = settings.runtimeMode2 ?? "host";
if (runtimeMode === "docker") {
await executeAppInDocker({
appPath,
appId,
event,
isNeon,
installCommand,
startCommand,
});
} else {
await executeAppLocalNode({
appPath,
appId,
event,
isNeon,
installCommand,
startCommand,
});
}
}
async function executeAppLocalNode({
appPath,
appId,
event,
isNeon,
installCommand,
startCommand,
}: {
appPath: string;
appId: number;
event: Electron.IpcMainInvokeEvent;
isNeon: boolean;
installCommand?: string | null;
startCommand?: string | null;
}): Promise<void> {
const command = getCommand({ appId, installCommand, startCommand });
const spawnedProcess = spawn(command, [], {
cwd: appPath,
shell: true,
stdio: "pipe", // Ensure stdio is piped so we can capture output/errors and detect close
detached: false, // Ensure child process is attached to the main process lifecycle unless explicitly backgrounded
});
// Check if process spawned correctly
if (!spawnedProcess.pid) {
// Attempt to capture any immediate errors if possible
let errorOutput = "";
let spawnErr: any | null = null;
spawnedProcess.stderr?.on(
"data",
(data) => (errorOutput += data.toString()),
);
await new Promise<void>((resolve) => {
spawnedProcess.once("error", (err) => {
spawnErr = err;
resolve();
});
}); // Wait for error event
const details = [
spawnErr?.message ? `message=${spawnErr.message}` : null,
spawnErr?.code ? `code=${spawnErr.code}` : null,
spawnErr?.errno ? `errno=${spawnErr.errno}` : null,
spawnErr?.syscall ? `syscall=${spawnErr.syscall}` : null,
spawnErr?.path ? `path=${spawnErr.path}` : null,
spawnErr?.spawnargs
? `spawnargs=${JSON.stringify(spawnErr.spawnargs)}`
: null,
]
.filter(Boolean)
.join(", ");
logger.error(
`Failed to spawn process for app ${appId}. Command="${command}", CWD="${appPath}", ${details}\nSTDERR:\n${
errorOutput || "(empty)"
}`,
);
throw new Error(
`Failed to spawn process for app ${appId}.
Error output:
${errorOutput || "(empty)"}
Details: ${details || "n/a"}
`,
);
}
// Increment the counter and store the process reference with its ID
const currentProcessId = processCounter.increment();
runningApps.set(appId, {
process: spawnedProcess,
processId: currentProcessId,
isDocker: false,
lastViewedAt: Date.now(),
});
listenToProcess({
process: spawnedProcess,
appId,
isNeon,
event,
});
}
// =============================================================================
// App Output Batcher
// =============================================================================
// Batches stdout/stderr IPC messages to avoid flooding the renderer when apps
// emit high-volume logs. Messages are buffered and flushed every 100ms.
const APP_OUTPUT_FLUSH_INTERVAL_MS = 100;
const pendingOutputs = new Map<Electron.WebContents, AppOutput[]>();
let flushTimer: ReturnType<typeof setTimeout> | null = null;
function enqueueAppOutput(
sender: Electron.WebContents,
output: AppOutput,
): void {
let queue = pendingOutputs.get(sender);
if (!queue) {
queue = [];
pendingOutputs.set(sender, queue);
}
queue.push(output);
if (!flushTimer) {
flushTimer = setTimeout(flushAllAppOutputs, APP_OUTPUT_FLUSH_INTERVAL_MS);
}
}
function flushAllAppOutputs(): void {
flushTimer = null;
for (const [sender, outputs] of pendingOutputs) {
if (outputs.length > 0) {
safeSend(sender, "app:output-batch", outputs);
}
}
pendingOutputs.clear();
}
function listenToProcess({
process: spawnedProcess,
appId,
isNeon,
event,
}: {
process: ChildProcess;
appId: number;
isNeon: boolean;
event: Electron.IpcMainInvokeEvent;
}) {
// Log output
spawnedProcess.stdout?.on("data", async (data) => {
const message = util.stripVTControlCharacters(data.toString());
logger.debug(
`App ${appId} (PID: ${spawnedProcess.pid}) stdout: ${message}`,
);
// Add to central log store
addLog({
level: "info",
type: "server",
message,
timestamp: Date.now(),
appId,
});
// This is a hacky heuristic to pick up when drizzle is asking for user
// to select from one of a few choices. We automatically pick the first
// option because it's usually a good default choice. We guard this with
// isNeon because: 1) only Neon apps (for the official Dyad templates) should
// get this template and 2) it's safer to do this with Neon apps because
// their databases have point in time restore built-in.
if (isNeon && message.includes("created or renamed from another")) {
spawnedProcess.stdin?.write(`\r\n`);
logger.info(
`App ${appId} (PID: ${spawnedProcess.pid}) wrote enter to stdin to automatically respond to drizzle push input`,
);
}
// Check if this is an interactive prompt requiring user input
const inputRequestPattern = /\s*›\s*\([yY]\/[nN]\)\s*$/;
const isInputRequest = inputRequestPattern.test(message);
if (isInputRequest) {
// Send input-requested immediately (not batched) for responsive UX
safeSend(event.sender, "app:output", {
type: "input-requested",
message,
appId,
});
} else {
// Batch normal stdout for efficient IPC
enqueueAppOutput(event.sender, {
type: "stdout",
message,
appId,
});
const urlMatch = message.match(/(https?:\/\/localhost:\d+\/?)/);
if (urlMatch) {
const originalUrl = urlMatch[1];
const appInfo = runningApps.get(appId);
if (!appInfo) {
return;
}
// Reuse the existing proxy worker for this app if it already targets this URL.
if (
appInfo.proxyWorker &&
appInfo.originalUrl === originalUrl &&
appInfo.proxyUrl
) {
enqueueAppOutput(event.sender, {
type: "stdout",
message: `[dyad-proxy-server]started=[${appInfo.proxyUrl}] original=[${originalUrl}]`,
appId,
});
return;
}
if (appInfo.proxyWorker) {
await appInfo.proxyWorker.terminate();
appInfo.proxyWorker = undefined;
}
const proxyWorker = await startProxy(originalUrl, {
onStarted: (proxyUrl) => {
// Store proxy URL in running app info for re-emission on app switch
const latestAppInfo = runningApps.get(appId);
if (latestAppInfo) {
latestAppInfo.proxyUrl = proxyUrl;
latestAppInfo.originalUrl = originalUrl;
}
enqueueAppOutput(event.sender, {
type: "stdout",
message: `[dyad-proxy-server]started=[${proxyUrl}] original=[${originalUrl}]`,
appId,
});
},
});
const latestAppInfo = runningApps.get(appId);
if (latestAppInfo) {
latestAppInfo.proxyWorker = proxyWorker;
latestAppInfo.originalUrl = originalUrl;
} else {
await proxyWorker.terminate();
}
}
}
});
spawnedProcess.stderr?.on("data", async (data) => {
const message = util.stripVTControlCharacters(data.toString());
logger.error(
`App ${appId} (PID: ${spawnedProcess.pid}) stderr: ${message}`,
);
// Add to central log store
addLog({
level: "error",
type: "server",
message,
timestamp: Date.now(),
appId,
});
enqueueAppOutput(event.sender, {
type: "stderr",
message,
appId,
});
});
// Handle process exit/close
spawnedProcess.on("close", (code, signal) => {
logger.log(
`App ${appId} (PID: ${spawnedProcess.pid}) process closed with code ${code}, signal ${signal}.`,
);
// Flush any remaining batched output before signaling process exit
flushAllAppOutputs();
removeAppIfCurrentProcess(appId, spawnedProcess);
});
// Handle errors during process lifecycle (e.g., command not found)
spawnedProcess.on("error", (err) => {
logger.error(
`Error in app ${appId} (PID: ${spawnedProcess.pid}) process: ${err.message}`,
);
removeAppIfCurrentProcess(appId, spawnedProcess);
// Note: We don't throw here as the error is asynchronous. The caller got a success response already.
// Consider adding ipcRenderer event emission to notify UI of the error.
});
}
async function executeAppInDocker({
appPath,
appId,
event,
isNeon,
installCommand,
startCommand,
}: {
appPath: string;
appId: number;
event: Electron.IpcMainInvokeEvent;
isNeon: boolean;
installCommand?: string | null;
startCommand?: string | null;
}): Promise<void> {
const containerName = `dyad-app-${appId}`;
// First, check if Docker is available
try {
await new Promise<void>((resolve, reject) => {
const checkDocker = spawn("docker", ["--version"], { stdio: "pipe" });
checkDocker.on("close", (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error("Docker is not available"));
}
});
checkDocker.on("error", () => {
reject(new Error("Docker is not available"));
});
});
} catch {
throw new Error(
"Docker is required but not available. Please install Docker Desktop and ensure it's running.",
);
}
// Stop and remove any existing container with the same name
try {
await new Promise<void>((resolve) => {
const stopContainer = spawn("docker", ["stop", containerName], {
stdio: "pipe",
});
stopContainer.on("close", () => {
const removeContainer = spawn("docker", ["rm", containerName], {
stdio: "pipe",
});
removeContainer.on("close", () => resolve());
removeContainer.on("error", () => resolve()); // Container might not exist
});
stopContainer.on("error", () => resolve()); // Container might not exist
});
} catch (error) {
logger.info(
`Docker container ${containerName} not found. Ignoring error: ${error}`,
);
}
// Create a Dockerfile in the app directory if it doesn't exist
const dockerfilePath = path.join(appPath, "Dockerfile.dyad");
if (!fs.existsSync(dockerfilePath)) {
const dockerfileContent = `FROM node:22-alpine
# Install pnpm
RUN npm install -g pnpm
`;
try {
await fsPromises.writeFile(dockerfilePath, dockerfileContent, "utf-8");
} catch (error) {
logger.error(`Failed to create Dockerfile for app ${appId}:`, error);
throw new Error(`Failed to create Dockerfile: ${error}`);
}
}
// Build the Docker image
const buildProcess = spawn(
"docker",
["build", "-f", "Dockerfile.dyad", "-t", `dyad-app-${appId}`, "."],
{
cwd: appPath,
stdio: "pipe",
},
);
let buildError = "";
buildProcess.stderr?.on("data", (data) => {
buildError += data.toString();
});
await new Promise<void>((resolve, reject) => {
buildProcess.on("close", (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Docker build failed: ${buildError}`));
}
});
buildProcess.on("error", (err) => {
reject(new Error(`Docker build process error: ${err.message}`));
});
});
// Run the Docker container
const port = getAppPort(appId);
const process = spawn(
"docker",
[
"run",
"--rm",
"--name",
containerName,
"-p",
`${port}:${port}`,
"-v",
`${appPath}:/app`,
"-v",
`dyad-pnpm-${appId}:/app/.pnpm-store`,
"-e",
"PNPM_STORE_PATH=/app/.pnpm-store",
"-w",
"/app",
`dyad-app-${appId}`,
"sh",
"-c",
getCommand({ appId, installCommand, startCommand }),
],
{
stdio: "pipe",
detached: false,
},
);
// Check if process spawned correctly
if (!process.pid) {
// Attempt to capture any immediate errors if possible
let errorOutput = "";
let spawnErr: any = null;
process.stderr?.on("data", (data) => (errorOutput += data.toString()));
await new Promise<void>((resolve) => {
process.once("error", (err) => {
spawnErr = err;
resolve();
});
}); // Wait for error event
const details = [
spawnErr?.message ? `message=${spawnErr.message}` : null,
spawnErr?.code ? `code=${spawnErr.code}` : null,
spawnErr?.errno ? `errno=${spawnErr.errno}` : null,
spawnErr?.syscall ? `syscall=${spawnErr.syscall}` : null,
spawnErr?.path ? `path=${spawnErr.path}` : null,
spawnErr?.spawnargs
? `spawnargs=${JSON.stringify(spawnErr.spawnargs)}`
: null,
]
.filter(Boolean)
.join(", ");
logger.error(
`Failed to spawn Docker container for app ${appId}. ${details}\nSTDERR:\n${
errorOutput || "(empty)"
}`,
);
throw new Error(
`Failed to spawn Docker container for app ${appId}.
Details: ${details || "n/a"}
STDERR:
${errorOutput || "(empty)"}`,
);
}
// Increment the counter and store the process reference with its ID
const currentProcessId = processCounter.increment();
runningApps.set(appId, {
process,
processId: currentProcessId,
isDocker: true,
containerName,
lastViewedAt: Date.now(),
});
listenToProcess({
process,
appId,
isNeon,
event,
});
}
// Helper to kill process on a specific port (cross-platform, using kill-port)
async function killProcessOnPort(port: number): Promise<void> {
try {
await killPort(port, "tcp");
} catch {
// Ignore if nothing was running on that port
}
}
// Helper to stop any Docker containers publishing a given host port
async function stopDockerContainersOnPort(port: number): Promise<void> {
try {
// List container IDs that publish the given port
const list = spawn("docker", ["ps", "--filter", `publish=${port}`, "-q"], {
stdio: "pipe",
});
let stdout = "";
list.stdout?.on("data", (data) => {
stdout += data.toString();
});
await new Promise<void>((resolve) => {
list.on("close", () => resolve());
list.on("error", () => resolve());
});
const containerIds = stdout
.split("\n")
.map((s) => s.trim())
.filter(Boolean);
if (containerIds.length === 0) {
return;
}
// Stop each container best-effort
await Promise.all(
containerIds.map(
(id) =>
new Promise<void>((resolve) => {
const stop = spawn("docker", ["stop", id], { stdio: "pipe" });
stop.on("close", () => resolve());
stop.on("error", () => resolve());
}),
),
);
} catch (e) {
logger.warn(`Failed stopping Docker containers on port ${port}: ${e}`);
}
}
async function searchAppFilesWithRipgrep({
appPath,
query,
}: {
appPath: string;
query: string;
}): Promise<AppFileSearchResult[]> {
return new Promise((resolve, reject) => {
const results = new Map<string, AppFileSearchResult>();
const args = [
"--json",
"--no-config",
"--ignore-case",
"--fixed-strings",
"--max-filesize",
`${MAX_FILE_SEARCH_SIZE}`,
...RIPGREP_EXCLUDED_GLOBS.flatMap((glob) => ["--glob", glob]),
query,
".",
];
const rg = spawn(getRgExecutablePath(), args, { cwd: appPath });
let buffer = "";
rg.stdout.on("data", (data) => {
buffer += data.toString();
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.trim()) continue;
try {
const event = JSON.parse(line);
if (event.type !== "match" || !event.data) {
continue;
}
const matchPath = event.data.path?.text as string;
if (!matchPath) continue;
const absolutePath = path.isAbsolute(matchPath)
? matchPath
: path.join(appPath, matchPath);
const relativePath = normalizePath(
path.relative(appPath, absolutePath),
);
if (relativePath.startsWith("..")) {
continue; // outside app directory
}
const lineText = event.data.lines?.text as string;
const lineNumber = event.data.line_number as number;
const submatch = event.data.submatches?.[0];
if (
typeof lineText !== "string" ||
typeof lineNumber !== "number" ||
!submatch
) {
continue;
}
const snippet = buildSnippetFromMatch({
lineText,
start: submatch.start,
end: submatch.end,
lineNumber,
});
const existing = results.get(relativePath);
if (!existing) {
results.set(relativePath, {
path: relativePath,
matchesContent: true,
snippets: [snippet],
});
} else {
// Add snippet to existing result if it doesn't already exist (avoid duplicates)
if (!existing.snippets) {
existing.snippets = [];
}
// Only add if this line number isn't already in the snippets
const existingLine = existing.snippets.find(
(s) => s.line === snippet.line,
);
if (!existingLine) {
existing.snippets.push(snippet);
}
}
} catch (error) {
logger.warn("Failed to parse ripgrep output line:", line, error);
}
}
});
rg.stderr.on("data", (data) => {
const message = data.toString();
if (message.toLowerCase().includes("binary file skipped")) {
return;
}
logger.debug("ripgrep stderr:", message);
});
rg.on("close", (code) => {
// rg exits with code 1 when no matches are found; treat as success
if (code !== 0 && code !== 1) {
reject(new Error(`ripgrep exited with code ${code}`));
return;
}
resolve(Array.from(results.values()));
});
rg.on("error", (error) => {
reject(error);
});
});
}
export function registerAppHandlers() {
createTypedHandler(systemContracts.restartDyad, async () => {
app.relaunch();
app.quit();
});
createTypedHandler(appContracts.createApp, async (_, params) => {
const appPath = params.name;
const fullAppPath = getDyadAppPath(appPath);
if (fs.existsSync(fullAppPath)) {
throw new Error(`App already exists at: ${fullAppPath}`);
}
// Create a new app
const [app] = await db
.insert(apps)
.values({
name: params.name,
// Use the name as the path for now
path: appPath,
})
.returning();
// Create an initial chat for this app
const [chat] = await db
.insert(chats)
.values({
appId: app.id,
})
.returning();
await createFromTemplate({
fullAppPath,
});
// Initialize git repo and create first commit
await gitInit({ path: fullAppPath, ref: "main" });
// Stage all files
await gitAdd({ path: fullAppPath, filepath: "." });
// Create initial commit
const commitHash = await gitCommit({
path: fullAppPath,
message: "Init Dyad app",
});
// Update chat with initial commit hash
await db
.update(chats)
.set({
initialCommitHash: commitHash,
})
.where(eq(chats.id, chat.id));
return {
app: { ...app, resolvedPath: fullAppPath },
chatId: chat.id,
};
});
createTypedHandler(appContracts.copyApp, async (_, params) => {
const { appId, newAppName, withHistory } = params;
// 1. Check if an app with the new name already exists
const existingApp = await db.query.apps.findFirst({
where: eq(apps.name, newAppName),
});
if (existingApp) {
throw new Error(`An app named "${newAppName}" already exists.`);
}
// 2. Find the original app
const originalApp = await db.query.apps.findFirst({
where: eq(apps.id, appId),
});
if (!originalApp) {
throw new Error("Original app not found.");
}
const originalAppPath = getDyadAppPath(originalApp.path);
const newAppPath = getDyadAppPath(newAppName);
// 3. Copy the app folder
try {
await copyDir(
originalAppPath,
newAppPath,
(source: string) => {
if (!withHistory && path.basename(source) === ".git") {
return false;
}
return true;
},
{ excludeNodeModules: true },
);
} catch (error) {
logger.error("Failed to copy app directory:", error);
throw new Error("Failed to copy app directory.");
}
if (!withHistory) {
// Initialize git repo and create first commit
await gitInit({ path: newAppPath, ref: "main" });
// Stage all files
await gitAdd({ path: newAppPath, filepath: "." });
// Create initial commit
await gitCommit({
path: newAppPath,
message: "Init Dyad app",
});
}
// 4. Create a new app entry in the database
const [newDbApp] = await db
.insert(apps)
.values({
name: newAppName,
path: newAppName, // Use the new name for the path
// Explicitly set these to null because we don't want to copy them over.
// Note: we could just leave them out since they're nullable field, but this
// is to make it explicit we intentionally don't want to copy them over.
supabaseProjectId: null,
githubOrg: null,
githubRepo: null,
installCommand: originalApp.installCommand,
startCommand: originalApp.startCommand,
})
.returning();
return { app: newDbApp };
});
createTypedHandler(appContracts.getApp, async (_, appId) => {
const app = await db.query.apps.findFirst({
where: eq(apps.id, appId),
});
if (!app) {
throw new Error("App not found");
}
// Get app files
const appPath = getDyadAppPath(app.path);
let files: string[] = [];
try {
files = getFilesRecursively(appPath, appPath);
// Normalize the path to use forward slashes so file tree (UI)
// can parse it more consistently across platforms.
files = files.map((path) => normalizePath(path));
} catch (error) {
logger.error(`Error reading files for app ${appId}:`, error);
// Return app even if files couldn't be read
}
let supabaseProjectName: string | null = null;
const settings = readSettings();
// Check for multi-organization credentials or legacy single account
const hasSupabaseCredentials =
(app.supabaseOrganizationSlug &&
settings.supabase?.organizations?.[app.supabaseOrganizationSlug]