Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .nx/version-plans/flow-error-version-states.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
desktop: minor
---

Add AI agent feature with tool execution, streaming, and provider settings. Add flow error display, fix version history ordering, and fix execution state display on flow versions.
25 changes: 25 additions & 0 deletions apps/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Config, Console, Effect, pipe, Runtime, String } from 'effect';
import { app, BrowserWindow, dialog, Dialog, globalShortcut, ipcMain, nativeTheme, protocol, shell } from 'electron';
import { autoUpdater } from 'electron-updater';
import { copyFileSync, existsSync, mkdirSync, unlinkSync } from 'node:fs';
import fs from 'node:fs';
import os from 'node:os';
import nodePath from 'node:path';
import { Agent } from 'undici';
Expand Down Expand Up @@ -251,6 +252,30 @@ const onReady = Effect.gen(function* () {
app.relaunch();
app.exit(0);
});

// Agent logging
const logDir = path.join(app.getPath('userData'), 'logs', 'agent');
fs.mkdirSync(logDir, { recursive: true });

ipcMain.on('agent-log:write', (_event, fileName: string, jsonLine: string) => {
const filePath = path.join(logDir, path.basename(fileName));
void fs.promises.appendFile(filePath, jsonLine);
});

ipcMain.on('agent-log:cleanup', () => {
const maxAge = 7 * 24 * 60 * 60 * 1000;
fs.readdir(logDir, (err, files) => {
if (err) return;
const now = Date.now();
for (const file of files) {
const filePath = path.join(logDir, file);
fs.stat(filePath, (err, stats) => {
if (err) return;
if (now - stats.mtimeMs > maxAge) void fs.promises.unlink(filePath).catch(() => undefined);
});
}
});
});
});

const onActivate = Effect.gen(function* () {
Expand Down
5 changes: 5 additions & 0 deletions apps/desktop/src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,9 @@ contextBridge.exposeInMainWorld('electron', {
onProgress: (callback: (info: ProgressInfo) => void) =>
ipcRenderer.on('update:progress', (_, info) => void callback(info as ProgressInfo)),
},

agentLog: {
cleanup: () => void ipcRenderer.send('agent-log:cleanup'),
write: (fileName: string, jsonLine: string) => void ipcRenderer.send('agent-log:write', fileName, jsonLine),
},
});
5 changes: 5 additions & 0 deletions apps/desktop/src/renderer/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ declare global {

onProgress: (callback: (info: ProgressInfo) => void) => void;
};

agentLog: {
cleanup: () => void;
write: (fileName: string, jsonLine: string) => void;
};
};
}
}
3 changes: 3 additions & 0 deletions apps/desktop/src/renderer/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ setTheme();

pipe(configProviderFromMetaEnv({ VERSION: packageJson.version }), Layer.setConfigProvider, addGlobalLayer);

// Trigger cleanup of old agent log files (7-day retention)
window.electron.agentLog.cleanup();

const updateCheckAtom = runtimeAtom.atom(
Effect.gen(function* () {
const client = pipe(
Expand Down
3 changes: 3 additions & 0 deletions packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,20 @@
"@xyflow/react": "catalog:",
"effect": "catalog:",
"id128": "catalog:",
"openai": "catalog:",
"prettier": "catalog:",
"react": "catalog:",
"react-aria": "catalog:",
"react-aria-components": "catalog:",
"react-dom": "catalog:",
"react-error-boundary": "catalog:",
"react-icons": "catalog:",
"react-markdown": "catalog:",
"react-resizable-panels": "catalog:",
"react-scan": "catalog:",
"react-stately": "catalog:",
"react-timeago": "catalog:",
"remark-gfm": "catalog:",
"tailwind-merge": "catalog:",
"tailwind-variants": "catalog:",
"use-debounce": "catalog:"
Expand Down
70 changes: 70 additions & 0 deletions packages/client/src/app/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,76 @@

@source '..';

:root {
--surface-1: #fefefe;
--surface-2: #ffffff;
--surface-3: #f7f7f7;
--surface-4: #f5f5f5;
--surface-5: #f3f3f3;
--surface-6: #f0f0f0;
--surface-7: #ececec;
--border: #e0e0e0;
--border-1: #e0e0e0;
--divider: #ededed;
--text-primary: #2d2d2d;
--text-secondary: #404040;
--text-tertiary: #5c5c5c;
--text-muted: #737373;
--text-subtle: #8c8c8c;
--text-inverse: #ffffff;
--text-error: #ef4444;
--brand-400: #8e4cfb;
--brand-secondary: #33b4ff;
--brand-tertiary-2: #32bd7e;
--shimmer-highlight: rgba(0, 0, 0, 0.7);
}

.dark {
--surface-1: #1e1e1e;
--surface-2: #232323;
--surface-3: #242424;
--surface-4: #292929;
--surface-5: #363636;
--surface-6: #454545;
--surface-7: #454545;
--border: #2c2c2c;
--border-1: #3d3d3d;
--divider: #393939;
--text-primary: #e6e6e6;
--text-secondary: #cccccc;
--text-tertiary: #b3b3b3;
--text-muted: #787878;
--text-subtle: #7d7d7d;
--text-inverse: #1b1b1b;
--text-error: #ef4444;
--brand-400: #8e4cfb;
--brand-secondary: #33b4ff;
--brand-tertiary-2: #32bd7e;
--bg: #1b1b1b;
--shimmer-highlight: rgba(255, 255, 255, 0.85);
}

@keyframes thinking-shimmer {
0% {
background-position: 150% 0;
}
50% {
background-position: 0% 0;
}
100% {
background-position: -150% 0;
}
}

@keyframes toolcall-shimmer {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}

html,
body,
#root {
Expand Down
195 changes: 195 additions & 0 deletions packages/client/src/features/agent/agent-logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/** JSON stringify with BigInt support */
const safeStringify = (value: unknown): string =>
JSON.stringify(value, (_key: string, v: unknown) => (typeof v === 'bigint' ? v.toString() : v));

/** Truncate a string to maxLen, appending '...[truncated]' if needed */
const truncate = (s: string, maxLen = 2048): string => (s.length <= maxLen ? s : s.slice(0, maxLen) + '...[truncated]');

interface AgentLogIpc {
cleanup: () => void;
write: (fileName: string, jsonLine: string) => void;
}

interface LogEntry {
[key: string]: unknown;
event: string;
sessionId: string;
ts: string;
}

/** Get the agentLog IPC bridge if running inside Electron, null otherwise */
const getAgentLogIpc = (): AgentLogIpc | null => {
if (typeof window === 'undefined') return null;
const electron = (window as unknown as { electron?: { agentLog?: AgentLogIpc } }).electron;
return electron?.agentLog ?? null;
};

/**
* JSONL logger for agent conversations.
* Writes to local files via Electron IPC. Silent no-op when running outside Electron.
*/
export class AgentLogger {
private buffer: string[] = [];
private fileName: string;
private flushTimer: null | ReturnType<typeof setTimeout> = null;
private ipc: AgentLogIpc | null;
private sessionId: string;
private sessionStart: number;

constructor(flowId: string) {
this.sessionId = crypto.randomUUID();
this.sessionStart = performance.now();
this.ipc = getAgentLogIpc();
const shortFlowId = flowId.slice(0, 8);
const ts = new Date().toISOString().replace(/[:.]/g, '-');
this.fileName = `agent-${shortFlowId}-${ts}-${this.sessionId.slice(0, 8)}.jsonl`;
}

private write(entry: LogEntry) {
if (!this.ipc) return;
this.buffer.push(safeStringify(entry));
this.flushTimer ??= setTimeout(() => void this.flush(), 100);
}

private flush() {
if (!this.ipc || this.buffer.length === 0) return;
const batch = this.buffer.join('\n') + '\n';
this.buffer = [];
this.ipc.write(this.fileName, batch);
}

// --- Event methods ---

logSessionStart(flowId: string, messageContent: string) {
this.write({
event: 'session_start',
flowId,
sessionId: this.sessionId,
ts: new Date().toISOString(),
userMessagePreview: truncate(messageContent, 500),
});
}

logSessionEnd(success: boolean, aborted: boolean) {
this.write({
aborted,
durationMs: Math.round(performance.now() - this.sessionStart),
event: 'session_end',
sessionId: this.sessionId,
success,
ts: new Date().toISOString(),
});
// Flush synchronously on close
this.close();
}

logSystemPrompt(prompt: string, contextStats: { edges: number; nodes: number; variables: number }) {
this.write({
contextStats,
event: 'system_prompt',
promptLength: prompt.length,
sessionId: this.sessionId,
ts: new Date().toISOString(),
});
}

logUserMessage(content: string) {
this.write({
content: truncate(content),
event: 'user_message',
sessionId: this.sessionId,
ts: new Date().toISOString(),
});
}

logAssistantMessage(content: string) {
this.write({
content: truncate(content),
event: 'assistant_message',
sessionId: this.sessionId,
ts: new Date().toISOString(),
});
}

logApiRequest(model: string, messageCount: number, hasTools: boolean) {
this.write({
event: 'api_request',
hasTools,
messageCount,
model,
sessionId: this.sessionId,
ts: new Date().toISOString(),
});
}

logApiResponse(
latencyMs: number,
finishReason: null | string | undefined,
usage: null | undefined | { completion_tokens?: number; prompt_tokens?: number; total_tokens?: number },
) {
this.write({
event: 'api_response',
finishReason: finishReason ?? 'unknown',
latencyMs: Math.round(latencyMs),
sessionId: this.sessionId,
ts: new Date().toISOString(),
usage: usage ?? null,
});
}

logToolCallStart(toolCallId: string, toolName: string, args: Record<string, unknown>) {
this.write({
args: truncate(safeStringify(args)),
event: 'tool_call_start',
sessionId: this.sessionId,
toolCallId,
toolName,
ts: new Date().toISOString(),
});
}

logToolCallEnd(toolCallId: string, toolName: string, durationMs: number, result: string, error?: string) {
this.write({
durationMs: Math.round(durationMs),
error: error ?? undefined,
event: 'tool_call_end',
result: truncate(result),
sessionId: this.sessionId,
toolCallId,
toolName,
ts: new Date().toISOString(),
});
}

logValidation(orphanCount: number, orphanNames: string[]) {
this.write({
event: 'validation',
orphanCount,
orphanNames,
sessionId: this.sessionId,
ts: new Date().toISOString(),
});
}

logError(error: unknown, phase: string) {
const message = error instanceof Error ? error.message : String(error);
const stack = error instanceof Error ? error.stack : undefined;
this.write({
event: 'error',
message,
phase,
sessionId: this.sessionId,
stack,
ts: new Date().toISOString(),
});
}

/** Flush remaining buffer immediately */
close() {
if (this.flushTimer) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
this.flush();
}
}
Loading