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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ native/stt-server-zig/zig-out/
.env.release.local
native/stt-server-rust/target/
native/native-host-rust/target/
native/agent-server-rust/target/
237 changes: 236 additions & 1 deletion apps/desktop/main.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const fs = require("node:fs/promises");
const fsSync = require("node:fs");
const http = require("node:http");
const https = require("node:https");
const net = require("node:net");
const os = require("node:os");
const path = require("node:path");
const readline = require("node:readline");
Expand Down Expand Up @@ -43,6 +44,7 @@ const TRANSCRIPT_UPLOAD_EXTENSIONS = new Set([".json", ".jsonl", ".srt", ".txt"]
const NOTE_UPLOAD_EXTENSIONS = new Set([".md"]);
const SUMMARY_TEMPLATES = require("./summaryTemplates.json");
const DEFAULT_SUMMARY_TEMPLATE_ID = "general-meeting";
const DEFAULT_AGENT_SERVER_PORT = 49731;
const CUSTOM_SUMMARY_TEMPLATE_ID_PATTERN = /^custom:[A-Za-z0-9_-]{1,80}$/;
const MAX_CUSTOM_SUMMARY_TEMPLATES = 30;
const MAX_SUMMARY_TEMPLATE_SECTIONS = 12;
Expand Down Expand Up @@ -1461,6 +1463,66 @@ function withDerivedSourceContextPaths(status, directoryPath, availablePaths = {
};
}

function agentContextJobStatusPath(directoryPath) {
return path.join(contextPacketPaths(directoryPath).contextDirectoryPath, "agent-jobs", "generate-context.json");
}

function sourceContextStatusFromAgentJob(directoryPath) {
try {
const raw = fsSync.readFileSync(agentContextJobStatusPath(directoryPath), "utf8");
const job = JSON.parse(raw);
const state = optionalNonEmptyString(job?.state);
if (state === "succeeded") {
return {
state: "ready",
detail: null,
retryable: false,
updatedAt: optionalNonEmptyString(job.updatedAt),
packetId: optionalNonEmptyString(job.packetId),
objectCount: parseInt(job.objectCount, 10) || 0,
relationCount: parseInt(job.relationCount, 10) || 0,
warningCount: parseInt(job.warningCount, 10) || 0,
agentBriefPath: null,
projectContextPath: null,
contextDirectoryPath: null,
};
}
if (state === "failed") {
return {
state: "failed",
detail: optionalNonEmptyString(job.error) || "Source context generation failed.",
retryable: true,
updatedAt: optionalNonEmptyString(job.updatedAt),
packetId: null,
objectCount: 0,
relationCount: 0,
warningCount: 0,
agentBriefPath: null,
projectContextPath: null,
contextDirectoryPath: null,
};
}
if (state === "queued" || state === "running") {
return {
state: "generating",
detail: null,
retryable: false,
updatedAt: optionalNonEmptyString(job.updatedAt),
packetId: null,
objectCount: 0,
relationCount: 0,
warningCount: 0,
agentBriefPath: null,
projectContextPath: null,
contextDirectoryPath: null,
};
}
} catch {
return null;
}
return null;
}

function sourceContextStatusFromMetadata(metadata, directoryPath, options = {}) {
const verifyFiles = options.verifyFiles !== false;
const paths = contextPacketPaths(directoryPath);
Expand Down Expand Up @@ -1503,6 +1565,10 @@ function sourceContextStatusFromMetadata(metadata, directoryPath, options = {})
}

if (stored && stored.state !== "ready") {
const jobStatus = sourceContextStatusFromAgentJob(directoryPath);
if (jobStatus) {
return jobStatus.state === "ready" ? withDerivedSourceContextPaths(jobStatus, directoryPath) : jobStatus;
}
return stored;
}

Expand Down Expand Up @@ -3201,7 +3267,7 @@ async function generateSourceContext(noteID) {
const settings = await readElectronSettings();
const summarySettings = normalizeSummarySettings(settings.summary);
try {
const payload = await nativeCaptureRequest("generateSourceContext", {
const payload = await agentServerRequest("generateContext", {
targetDirectory: note.directoryPath,
summarySettings,
});
Expand Down Expand Up @@ -3240,6 +3306,17 @@ async function generateSourceContext(noteID) {
}
}

function scheduleAutomaticSourceContextGeneration(noteID) {
if (!noteID) {
return;
}
setTimeout(() => {
generateSourceContext(noteID).catch((error) => {
console.error(`Automatic source context generation failed for ${noteID}:`, error);
});
}, 0);
}

async function openAgentBrief(noteID) {
const directoryPath = resolveBundleDirectory(noteID);
const paths = contextPacketPaths(directoryPath);
Expand Down Expand Up @@ -3387,6 +3464,10 @@ function rustSTTServerPath() {
return path.join(repoRoot(), "native", "stt-server-rust", "target", "release", "MirrorNoteSTTServer");
}

function rustAgentServerPath() {
return path.join(repoRoot(), "native", "agent-server-rust", "target", "release", "MirrorNoteAgentServer");
}

function iconPath() {
const candidates = [
path.join(repoRoot(), "branding", "app-icon-1024.png"),
Expand Down Expand Up @@ -3537,6 +3618,32 @@ function resolveSTTServerLaunch() {
throw new Error("MirrorNoteSTTServer was not found. Run npm run native:build.");
}

function resolveAgentServerLaunch() {
if (process.env.MIRROR_NOTE_AGENT_SERVER_PATH) {
return { command: process.env.MIRROR_NOTE_AGENT_SERVER_PATH, args: [] };
}

const packaged = packagedHelperPath("MirrorNoteAgentServer");
if (packaged) {
return { command: packaged, args: [] };
}

const rustServer = rustAgentServerPath();
if (fsSync.existsSync(rustServer)) {
return { command: rustServer, args: [] };
}

throw new Error("MirrorNoteAgentServer was not found. Run npm run native:build.");
}

function agentServerPort() {
const raw = Number(process.env.MIRROR_NOTE_AGENT_SERVER_PORT || DEFAULT_AGENT_SERVER_PORT);
if (Number.isInteger(raw) && raw > 0 && raw < 65536) {
return raw;
}
return DEFAULT_AGENT_SERVER_PORT;
}

function resolveNativeHostEnvironment() {
const env = { ...process.env };
const packagedSTTServer = packagedHelperPath("MirrorNoteSTTServer");
Expand Down Expand Up @@ -3798,6 +3905,127 @@ let nativeCaptureRequest = function nativeCaptureRequest(command, payload = {})
return nativeCapture.request(command, payload);
};

class AgentServerBridge {
constructor() {
this.launching = null;
this.requestSequence = 0;
}

async request(command, payload = {}) {
try {
return await this.send(command, payload);
} catch (error) {
if (!this.isConnectionError(error)) {
throw error;
}
await this.ensureStarted();
return this.send(command, payload);
}
}

isConnectionError(error) {
return ["ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.code);
}

async ensureStarted() {
if (this.launching) {
return this.launching;
}
this.launching = (async () => {
const launch = resolveAgentServerLaunch();
const child = spawn(launch.command, launch.args, {
cwd: nativeHelperWorkingDirectory(),
env: resolveNativeHostEnvironment(),
detached: true,
stdio: "ignore",
});
child.unref();
await this.waitUntilReady();
})();
try {
await this.launching;
} finally {
this.launching = null;
}
}

async waitUntilReady() {
const deadline = Date.now() + 5000;
let lastError = null;
while (Date.now() < deadline) {
try {
await this.send("capabilities", {});
return;
} catch (error) {
lastError = error;
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
throw lastError || new Error("MirrorNoteAgentServer did not become ready.");
}

send(command, payload = {}) {
const id = `agent-${Date.now()}-${++this.requestSequence}`;
const request = {
id,
command,
...payload,
};
const port = agentServerPort();

return new Promise((resolve, reject) => {
const socket = net.createConnection({ host: "127.0.0.1", port });
let buffer = "";
const timeout = setTimeout(() => {
const error = new Error("MirrorNoteAgentServer request timed out.");
error.code = "ETIMEDOUT";
socket.destroy(error);
}, 120000);

socket.setEncoding("utf8");
socket.on("connect", () => {
socket.write(`${JSON.stringify(request)}\n`, "utf8");
});
socket.on("data", (chunk) => {
buffer += chunk;
const newlineIndex = buffer.indexOf("\n");
if (newlineIndex === -1) {
return;
}
const line = buffer.slice(0, newlineIndex).trim();
clearTimeout(timeout);
socket.end();
if (!line) {
reject(new Error("MirrorNoteAgentServer returned an empty response."));
return;
}
let message;
try {
message = JSON.parse(line);
} catch (error) {
reject(error);
return;
}
if (message.ok) {
resolve(message.payload || {});
} else {
reject(new Error(message.error || "MirrorNoteAgentServer request failed."));
}
});
socket.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
});
}
}

const agentServer = new AgentServerBridge();

let agentServerRequest = function agentServerRequest(command, payload = {}) {
return agentServer.request(command, payload);
};

async function selectedTranscriptionConfiguration() {
const settings = await readElectronSettings();
const selectedModel = await resolveSelectedInstalledModel();
Expand Down Expand Up @@ -4469,6 +4697,7 @@ async function handleStopCapture() {
const payload = await nativeCapture.request("stopSession");
if (stoppingNoteId) {
await enqueueListenerSessionStateWrite(stoppingNoteId, { state: "completed", detail: "" }, "completion").catch(() => {});
scheduleAutomaticSourceContextGeneration(stoppingNoteId);
activeListenerSessionNoteId = null;
}
setMenuBarCaptureState("completed", "", "");
Expand Down Expand Up @@ -4868,6 +5097,12 @@ if (process.env.MIRROR_NOTE_TEST_EXPORTS === "1") {
set nativeCaptureRequest(value) {
nativeCaptureRequest = value;
},
get agentServerRequest() {
return agentServerRequest;
},
set agentServerRequest(value) {
agentServerRequest = value;
},
},
};
} else {
Expand Down
31 changes: 31 additions & 0 deletions apps/desktop/main/native-launch.node-test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,37 @@ assert.deepEqual(sourceContextStatusFromMetadata({}, contextTempDirectory), {
contextDirectoryPath: generatedContextPaths.contextDirectoryPath,
});

const failedJobContextDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "mirrornote-source-context-job-"));
const failedJobPaths = contextPacketPaths(failedJobContextDirectory);
fs.mkdirSync(path.join(failedJobPaths.contextDirectoryPath, "agent-jobs"), { recursive: true });
fs.writeFileSync(path.join(failedJobPaths.contextDirectoryPath, "agent-jobs", "generate-context.json"), JSON.stringify({
jobId: "job-failed",
command: "generateContext",
state: "failed",
targetDirectory: failedJobContextDirectory,
queuedAt: "2026-05-04T00:00:00.000Z",
updatedAt: "2026-05-04T00:00:02.000Z",
error: "provider unavailable",
}, null, 2));
assert.deepEqual(sourceContextStatusFromMetadata({
sourceContext: {
state: "generating",
updatedAt: "2026-05-04T00:00:01.000Z",
},
}, failedJobContextDirectory), {
state: "failed",
detail: "provider unavailable",
retryable: true,
updatedAt: "2026-05-04T00:00:02.000Z",
packetId: null,
objectCount: 0,
relationCount: 0,
warningCount: 0,
agentBriefPath: null,
projectContextPath: null,
contextDirectoryPath: null,
});

const interruptedLedgerRecords = parseSTTChunkLedgerJSONL([
JSON.stringify({
sessionID: "session-a",
Expand Down
5 changes: 3 additions & 2 deletions docs/distribution.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,16 @@ When an update downloads, the updater prompts the user to restart the app.
## What `release:prepare:mac` Does

- builds the Vite renderer
- builds native helpers (`native-host-rust` + `stt-server-rust`)
- builds native helpers (`native-host-rust` + `stt-server-rust` + `agent-server-rust`)
- prepares the Silero VAD model used by the embedded STT helper
- generates `MirrorNote.icns`
- stages release resources in `.build/release-macos/`

The helper split is intentional:

- `MirrorNoteNativeHost` owns macOS capture, meeting bundles, artifact writes, and source context generation.
- `MirrorNoteNativeHost` owns macOS capture, meeting bundles, and artifact writes.
- `MirrorNoteSTTServer` owns local STT runtime checks, embedded whisper.cpp model loading, Metal-backed macOS acceleration, and segment extraction.
- `MirrorNoteAgentServer` owns local agent jobs, starting with source context generation and persistent job status.

See [native-helper-boundaries.md](native-helper-boundaries.md) for the process contract.

Expand Down
Loading