Skip to content
Draft
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
222 changes: 222 additions & 0 deletions desktop/main/chat-share.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
/* ATO-581 — the chat row's "Share chat…": one redacted file, and a secret
gist only after an explicit yes.

The agent writes the file (`atag share --session <id> --out <file>
--format html|md --json`, src/cli/share-command.ts): only the person's
messages and the agent's replies, with keys, local paths, emails, IP
addresses and reasoning removed. The desktop picks where (a save
dialog), then says what was removed and offers three ways on: Done,
Show in folder, Create secret gist….

The gist is the only way off the machine and it is asked twice: the
offer, then a confirm that says who can open a secret gist (anyone with
the link), with Cancel as the default button. Only then does it run
`gh gist create <file> --desc <title>`: a SECRET gist (no `--public`,
pinned by test/chat-share.test.mjs) on the account `gh` is signed in
to; the token never leaves gh. GitHub shows Markdown as a page and HTML
as source, so an HTML save uploads a Markdown copy written by the same
command. Same flow as ChatGPT / Claude "Share chat" (a preview, then a
link) and Claude Code `/export`, minus any server of ours. */

import type { BrowserWindow, Dialog, IpcMain, MessageBoxOptions, SaveDialogOptions } from "electron";
import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";

import type { CliResult } from "./agent-cli.js";

/** `atag share --json`'s line. */
export interface ShareWire {
ok: true;
file: string;
sessionId: string;
format: "html" | "md";
messages: number;
removed: { secrets?: number; paths?: number; personal?: number; reasoning?: number };
}

export interface GhResult { code: number; stdout: string; stderr: string; missing?: boolean }

export interface ChatShareDeps {
ipcMain: Pick<IpcMain, "handle">;
dialog: Pick<Dialog, "showSaveDialog" | "showMessageBox">;
window: () => BrowserWindow | null;
/** `atag <args>` (agent-cli.ts atagRun). */
runAgent: (args: string[]) => Promise<CliResult>;
/** `gh <args>`, with the app's PATH (state-dir.ts agentEnv). */
runGh: (args: string[]) => Promise<GhResult>;
/** The agent runs on another computer: its chats are not in this computer's store. */
isRemote: () => boolean;
showInFolder: (path: string) => void;
copyText: (text: string) => void;
openUrl: (url: string) => void;
readText?: (path: string) => Promise<string>;
}

export type ChatShareResult =
| { ok: true; path: string; gistUrl?: string; gistError?: string }
| { ok: false; reason: "canceled" | "bad-id" }
| { ok: false; reason: "failed"; error: string };

export const SHARE_FILTERS: NonNullable<SaveDialogOptions["filters"]> = [
{ name: "Web page", extensions: ["html"] },
{ name: "Markdown", extensions: ["md"] },
];

/** The exact argv handed to `gh`: a secret gist, never `--public`. */
export function shareGistArgs(file: string, title: string): string[] {
return ["gist", "create", file, "--desc", `Atomic Agent chat: ${title || "untitled"}`];
}

/** The `atag share` argv for one chat and one file. */
export function shareAgentArgs(id: string, format: "html" | "md", out?: string): string[] {
return ["share", "--session", id, "--format", format, ...(out ? ["--out", out] : []), "--json"];
}

/** `.md` / `.markdown` is Markdown; anything else is the HTML page (and gets `.html`). */
export function shareTarget(filePath: string): { format: "html" | "md"; path: string } {
if (/\.(md|markdown)$/i.test(filePath)) return { format: "md", path: filePath };
if (/\.html?$/i.test(filePath)) return { format: "html", path: filePath };
return { format: "html", path: `${filePath}.html` };
}

/** The last JSON line `atag share --json` printed, or null. */
export function parseShareWire(stdout: string): ShareWire | null {
const lines = String(stdout || "").trim().split("\n").reverse();
for (const line of lines) {
try {
const v = JSON.parse(line) as Partial<ShareWire>;
if (v && v.ok === true && typeof v.file === "string") return v as ShareWire;
} catch { /* not the JSON line */ }
}
return null;
}

/** "Removed: 2 keys, 5 folder paths…" in plain words; "" when nothing was. */
export function removedLine(removed: ShareWire["removed"] | undefined): string {
const r = removed ?? {};
const parts: string[] = [];
const add = (n: number | undefined, one: string, many: string): void => {
if (typeof n === "number" && n > 0) parts.push(`${n} ${n === 1 ? one : many}`);
};
add(r.secrets, "key or secret", "keys or secrets");
add(r.paths, "folder path", "folder paths");
add(r.personal, "email, IP or link part", "emails, IPs or link parts");
add(r.reasoning, "reasoning block", "reasoning blocks");
return parts.length ? `Removed: ${parts.join(", ")}.` : "Nothing needed removing.";
}

/** The chat title: the Markdown file's first `# ` line (already redacted by the agent). */
export function titleFromMarkdown(md: string): string {
const m = /^#\s+(.+)$/m.exec(md);
return m ? (m[1] ?? "").trim().slice(0, 120) : "";
}

/** What the window shows for a failed `atag share`. */
export function shareErrorText(res: CliResult): string {
const text = `${res.stderr || ""}\n${res.error || ""}`;
if (/unknown command:\s*share/.test(text)) return "This agent version cannot share chats. Update Atomic Agent.";
const line = text.split("\n").map((l) => l.trim()).filter(Boolean)[0];
return line || "The agent did not write the file.";
}

const GIST_URL = /https:\/\/gist\.github\.com\/\S+/;

/** `gh gist create`'s answer, as a link or a reason. */
export function gistOutcome(res: GhResult): { url: string } | { error: string } {
if (res.missing) return { error: "GitHub CLI (gh) is not installed. Install it from cli.github.com, then run `gh auth login` in Terminal." };
if (res.code !== 0) {
const reason = res.stderr.trim().split("\n").at(-1) ?? "";
return { error: `gh gist create failed${reason ? `: ${reason}` : ""}. Is gh signed in? Try \`gh auth status\` in Terminal.` };
}
const url = GIST_URL.exec(res.stdout)?.[0] ?? GIST_URL.exec(res.stderr)?.[0];
return url ? { url } : { error: "gh did not print a gist link." };
}

async function box(deps: ChatShareDeps, opts: MessageBoxOptions): Promise<number> {
const owner = deps.window();
const res = owner ? await deps.dialog.showMessageBox(owner, opts) : await deps.dialog.showMessageBox(opts);
return res.response;
}

/** Save dialog → `atag share` → what was removed → (opt-in) secret gist. */
export async function shareChat(deps: ChatShareDeps, id: unknown): Promise<ChatShareResult> {
if (typeof id !== "string" || !id || id.length > 256 || id.startsWith("-")) return { ok: false, reason: "bad-id" };
if (deps.isRemote()) return { ok: false, reason: "failed", error: "Share works for chats stored on this computer. This window is connected to an agent on another one." };
const owner = deps.window();
const opts: SaveDialogOptions = { title: "Share chat", defaultPath: `chat-${id.slice(0, 8)}.html`, filters: SHARE_FILTERS };
const picked = owner ? await deps.dialog.showSaveDialog(owner, opts) : await deps.dialog.showSaveDialog(opts);
if (picked.canceled || !picked.filePath) return { ok: false, reason: "canceled" };
const target = shareTarget(picked.filePath);

const saved = await deps.runAgent(shareAgentArgs(id, target.format, target.path));
const wire = saved.ok ? parseShareWire(saved.stdout) : null;
if (!wire) return { ok: false, reason: "failed", error: shareErrorText(saved) };

const next = await box(deps, {
type: "info",
message: "Saved a redacted copy of this chat",
detail: `${wire.messages} messages: yours and the agent's replies. Tool output and reasoning are never included. ${removedLine(wire.removed)}\n\n${wire.file}`,
buttons: ["Done", "Show in folder", "Create secret gist…"],
defaultId: 0,
cancelId: 0,
});
if (next === 1) deps.showInFolder(wire.file);
if (next !== 2) return { ok: true, path: wire.file };

/* GitHub draws Markdown as a page and HTML as source: an HTML save uploads a Markdown copy. That copy is
written NOW, before the confirm, so the confirm names the exact file and message count that go up, and
that same file is uploaded (never one regenerated after the yes, which could hold newer messages). */
let up = wire;
if (wire.format !== "md") {
const md = await deps.runAgent(shareAgentArgs(id, "md"));
const mdWire = md.ok ? parseShareWire(md.stdout) : null;
if (!mdWire) return { ok: true, path: wire.file, gistError: shareErrorText(md) };
up = mdWire;
}
const mdFile = up.file;
const what = up === wire
? `What goes up is the file you saved (${up.messages} messages):\n${mdFile}`
: `GitHub shows Markdown as a page, so what goes up is a Markdown copy of the same chat (${up.messages} messages, redacted the same way):\n${mdFile}`;

const sure = await box(deps, {
type: "warning",
message: "Upload this chat as a secret GitHub gist?",
detail: "It goes to the GitHub account the gh command is signed in to. A secret gist is not listed on your profile or in search, "
+ "but anyone with the link can open it. You can delete it later at gist.github.com.\n\n"
+ `${what}\n\nOpen that file first if you want to read exactly what goes up.`,
buttons: ["Cancel", "Upload"],
defaultId: 0,
cancelId: 0,
});
if (sure !== 1) return { ok: true, path: wire.file };

const title = titleFromMarkdown(await (deps.readText ?? ((p) => readFile(p, "utf8")))(mdFile).catch(() => ""));
const outcome = gistOutcome(await deps.runGh(shareGistArgs(mdFile, title)));
if ("error" in outcome) return { ok: true, path: wire.file, gistError: outcome.error };
deps.copyText(outcome.url);
const open = await box(deps, {
type: "info",
message: "Uploaded as a secret gist",
detail: `The link is copied: ${outcome.url}\nSend it to your colleague. Delete the gist on GitHub to stop sharing.`,
buttons: ["Done", "Open link"],
defaultId: 0,
cancelId: 0,
});
if (open === 1) deps.openUrl(outcome.url);
return { ok: true, path: wire.file, gistUrl: outcome.url };
}

/** `gh <args>` with the given environment (the app's PATH reaches Homebrew's gh); a minute at most. */
export function ghRunner(env: () => NodeJS.ProcessEnv): (args: string[]) => Promise<GhResult> {
return (args) => new Promise((resolve) => {
execFile("gh", args, { env: env(), timeout: 60_000, windowsHide: true, encoding: "utf8" }, (error, stdout, stderr) => {
if (error && (error as NodeJS.ErrnoException).code === "ENOENT") { resolve({ code: 127, stdout: "", stderr: "", missing: true }); return; }
const code = error ? (typeof error.code === "number" ? error.code : 1) : 0;
resolve({ code, stdout: String(stdout), stderr: String(stderr) });
});
});
}

export function registerChatShareIpc(deps: ChatShareDeps): void {
deps.ipcMain.handle("agent:shareSession", (_event, id: unknown) => shareChat(deps, id));
}
5 changes: 5 additions & 0 deletions desktop/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { DESKTOP_STATE_SEEDED, DESKTOP_STATE_WAS_FRESH, SHARED_CONFIG_FROM_DESKT
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, Notification, powerMonitor, powerSaveBlocker, safeStorage, screen, shell, systemPreferences, Tray } from "electron";
import { registerDoctorDataIpc } from "./doctor-data.js";
import { printHtmlToPdf, registerChatExportIpc } from "./chat-export.js";
import { ghRunner, registerChatShareIpc } from "./chat-share.js";
import { cleanWebhookCreate, webhookNameOk } from "./webhooks-ipc.js";
import { registerSettingsReferenceIpc } from "./settings-reference.js";
import { NOTIFY_DEFAULTS, readNotifyConfig, TurnNotifier } from "./turn-notify.js";
Expand Down Expand Up @@ -1545,6 +1546,10 @@ function wireIpc(client: AgentClient): void {
);
// ATO-1054: the chat row's Export… (chat-export.ts): Markdown, PDF, Word or HTML.
registerChatExportIpc({ ipcMain, dialog, window: () => win, fetchExport: (id, format) => client.exportSession(id, format), printPdf: printHtmlToPdf });
// ATO-581: the chat row's Share chat… (chat-share.ts): a redacted file, a secret gist only after two yeses.
registerChatShareIpc({ ipcMain, dialog, window: () => win, runAgent: (args) => atagRun(args, 60_000), runGh: ghRunner(agentEnv),
isRemote: () => client.isRemote, showInFolder: (p) => shell.showItemInFolder(p),
copyText: (t) => (require("electron") as typeof import("electron")).clipboard.writeText(t), openUrl: (u) => { if (/^https:\/\//.test(u)) void shell.openExternal(u); } });
/* Backlog 18 (its second review): the last coding mode the window set. A
switch's restart puts it back on the new agent before the turns waiting
for that restart go (restartsAgent below). */
Expand Down
2 changes: 2 additions & 0 deletions desktop/preload/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ contextBridge.exposeInMainWorld("atomic", {
setSessionArchived: (id: string, archived: boolean) => ipcRenderer.invoke("agent:setSessionArchived", id, archived),
// ATO-1054: save one chat as Markdown / PDF / Word / HTML (asks where in a save dialog)
exportSession: (id: string) => ipcRenderer.invoke("agent:exportSession", id),
// ATO-581: Share chat… — a redacted file, then (asked twice) a secret gist
shareSession: (id: string) => ipcRenderer.invoke("agent:shareSession", id),
codingMode: (mode?: string) => ipcRenderer.invoke("agent:codingMode", mode),

/** One turn of the agent loop, streamed back over `onChat`. */
Expand Down
2 changes: 2 additions & 0 deletions desktop/renderer/chat-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ function chatMenuItems(opts) {
...(o.archivable === true ? [o.archived ? {verb: 'unarchive', label: 'Unarchive', icon: 'archive'} : {verb: 'archive', label: 'Archive', icon: 'archive'}] : []),
// ATO-1054: "Export…" saves the chat as Markdown / PDF / Word (chat-export.js), for a stored chat.
...(o.exportable === true ? [{verb: 'export', label: 'Export…', icon: 'download'}] : []),
// ATO-581: "Share chat…" saves a redacted copy and offers a secret gist (chat-share.js), for a stored chat.
...(o.exportable === true ? [{verb: 'share', label: 'Share chat…', icon: 'upload'}] : []),
{verb: 'delask', label: 'Delete…', icon: 'trash', danger: true},
];
}
Expand Down
32 changes: 32 additions & 0 deletions desktop/renderer/chat-share.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* ---------------- ATO-581: sharing a chat ----------------
Loaded before renderer.js; declares only.

The chat row's "…" menu has Share chat… for a chat the agent has stored.
Main (main/chat-share.ts) asks where to save, has the agent write one
redacted file (`atag share`), says what was removed, and offers a secret
GitHub gist only after a second, explicit confirm. This side only starts
it and says how it went. */

/* The toast for a result from window.atomic.shareSession:
null when nothing needs saying (the person closed the save dialog). */
function chatShareToast(res) {
if (!res) return {t: 'Could not share the chat', s: 'No answer from the app', kind: 'bad'};
if (res.ok && res.gistUrl) return {t: 'Secret gist link copied', s: String(res.gistUrl)};
if (res.ok && res.gistError) return {t: 'Saved, but not uploaded', s: String(res.gistError), kind: 'bad'};
if (res.ok) return {t: 'Redacted chat saved', s: String(res.path || '')};
if (res.reason === 'canceled') return null;
return {t: 'Could not share the chat', s: String(res.error || res.reason || ''), kind: 'bad'};
}

/* ---- renderer side (globals from renderer.js, read at call time) ---- */

function chatShare(id) {
if (!id) return;
if (!BR || !BR.shareSession) { toast('Could not share the chat', 'Update Atomic Agent to share chats', 'bad'); return; }
BR.shareSession(id).then((res) => {
const m = chatShareToast(res);
if (m) toast(m.t, m.s, m.kind);
}, (e) => toast('Could not share the chat', String(e), 'bad'));
}

if (typeof module !== 'undefined') module.exports = {chatShareToast};
1 change: 1 addition & 0 deletions desktop/renderer/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
<script src="chat-rename.js"></script>
<!-- ATO-1054: the chat row's Export… -->
<script src="chat-export.js"></script>
<script src="chat-share.js"></script>
<!-- ATO-1034: chat folders, kept in ~/.atomic-agent/chat-folders.json. -->
<script src="chat-folders.js"></script>
<!-- ATO-1150: search and archive in the chat list (the pure half is chat-list.js). -->
Expand Down
1 change: 1 addition & 0 deletions desktop/renderer/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -7745,6 +7745,7 @@ function act(a) {
// ATO-455: the row menu's Rename opens the inline box over the row's name (chat-rename.js).
if (k === 'rename') { close(); renameStart(v, 'row'); return; }
if (k === 'export') { close(); render(); chatExport(v); return; } // ATO-1054 (chat-export.js)
if (k === 'share') { close(); render(); chatShare(v); return; } // ATO-581 (chat-share.js)
/* ATO-1034: folders (chat-folders.js). Folder ids never hold a colon, so
`fput:<folder>:<chat>` splits at its first one; an empty folder is "no folder". */
if (k === 'ftoggle') { const f = folderById(FOLDERS.state, v); if (!f) return;
Expand Down
2 changes: 1 addition & 1 deletion desktop/test/chat-export.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ test('the IPC channel is agent:exportSession', () => {
});

test('the row menu has Export… for a stored chat only, before Delete…', () => {
assert.deepEqual(chatMenuItems({ folders: true, exportable: true }).map((i) => i.verb), ['pin', 'unread', 'rename', 'fpick', 'export', 'delask']);
assert.deepEqual(chatMenuItems({ folders: true, exportable: true }).map((i) => i.verb), ['pin', 'unread', 'rename', 'fpick', 'export', 'share', 'delask']);
assert.ok(!chatMenuItems({}).some((i) => i.verb === 'export'));
});

Expand Down
Loading
Loading