Files
lune/web/src/desktop/main.tsx
Adnan Zahir 4ab9d580b8 0.1.3: upload a vault to a team from the app, detach first; AGPL-3.0
- The Lune window shows Upload on a vault that isn't on a team, for the team
  owner and anyone who manages a vault there. The hub now lets those people
  create vaults too (was owner only); /api/me and the canvas say can_create.
- A vault on its own remote (GitHub, GitLab, Gitea…) must be detached first
  (`lunesync vault detach`, or the Upload sheet's Detach): it shares what's
  waiting one last time, then lives on this device only. Upload refuses
  anything else, and a check-in no longer silently moves a same-named vault
  off its own remote onto the hub.
- Upload logic moved from the CLI into core (lune_core::upload).
- Canvas: "1 person loses access".
- License: AGPL-3.0-only. README and SPEC §8 updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 16:44:36 +07:00

443 lines
20 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The Lune window in the Mac app: connect this Mac, see each vault plainly, and make the few decisions only a person
// can (a held big change, a possible secret, a note changed in two places). Talks to the app, not to the hub.
import { StrictMode, useCallback, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { invoke } from '@tauri-apps/api/core';
import '../styles.css';
import './desktop.css';
import moon from './moon.svg';
type Level = 'current' | 'behind' | 'offline' | 'secret';
interface VaultStatus {
name: string;
path: string;
team: string | null;
elsewhere: string | null;
level: Level;
headline: string;
last_synced: number | null;
waiting: number;
read_only: boolean;
running: boolean;
held: { message: string; removed: number; rewritten: number; total: number }[];
secrets: { path: string; found: string[] }[];
tidy: { note: string; copy: string; label: string }[];
case_clashes: string[];
}
interface Overview {
version: string;
connected: boolean;
teams: string[];
device: string;
folder: string;
level: Level;
summary: string;
vaults: VaultStatus[];
pending: { kind: 'join' | 'pair'; hub: string } | null;
update: string | null;
recent: string[];
}
interface Comparison {
note: string;
copy: string;
label: string;
copy_is_mine: boolean;
note_text: string | null;
copy_text: string | null;
}
const host = (url: string | null) => (url ? url.replace(/^https?:\/\//, '') : '');
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
function Dot({ level }: { level: Level }) {
return <span className={`dot dot-${level}`} aria-hidden="true" />;
}
/** Connecting: from the link the website opened (no code), or a hub address and code typed by hand. */
function Connect({ o, done, cancel }: { o: Overview; done: (msg: string) => void; cancel?: () => void }) {
const [name, setName] = useState(o.device);
const [folder, setFolder] = useState(o.folder);
const [hubUrl, setHubUrl] = useState('');
const [code, setCode] = useState('');
const [manual, setManual] = useState(!!cancel && !o.pending);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const fromLink = o.pending && !manual;
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setError('');
try {
done(await invoke<string>('connect', { name, folder, hubUrl: fromLink ? null : hubUrl, code: fromLink ? null : code }));
} catch (err) {
setError(String(err));
} finally {
setBusy(false);
}
};
const pick = async () => {
const path = await invoke<string | null>('choose_folder');
if (path) setFolder(path);
};
if (!o.pending && !manual) {
return (
<section className="welcome">
<img className="moon" src={moon} alt="" />
<h1 className="disp">Connect this Mac to your team</h1>
<p>Open your invite link and choose <b>Open Lune to join</b>. Already on the team? Open the team canvas in your browser and choose <b>Connect this Mac</b>.</p>
<button className="btn btn-ghost" onClick={() => setManual(true)}>I have a pairing code instead</button>
</section>
);
}
return (
<form className="welcome" onSubmit={submit}>
<span className="eyebrow">{fromLink ? (o.pending!.kind === 'join' ? 'Invite' : 'Connect') : 'Pairing code'}</span>
<h1 className="disp">
{fromLink ? (o.pending!.kind === 'join' ? `Join the team at ${host(o.pending!.hub)}` : `Connect to ${host(o.pending!.hub)}`) : 'Connect with a code'}
</h1>
{!fromLink && (
<>
<label htmlFor="hub">Team address</label>
<input id="hub" className="field" value={hubUrl} onChange={(e) => setHubUrl(e.target.value)} placeholder="lune.example.com" autoFocus />
<label htmlFor="code">Code from one of your devices</label>
<input id="code" className="field code" value={code} onChange={(e) => setCode(e.target.value)} placeholder="K7QD-4MXA" />
</>
)}
<label htmlFor="name">This Mac's name</label>
<input id="name" className="field" value={name} onChange={(e) => setName(e.target.value)} maxLength={40} />
<p className="muted">Your team sees it next to your changes.</p>
<label>Shared vaults go in</label>
<div className="folder-row">
<span className="folder" title={folder}><bdi>{folder}</bdi></span>
<button type="button" className="btn btn-small" onClick={pick}>Change…</button>
</div>
{error && <p className="error" role="alert">{error}</p>}
<button className="btn btn-primary" type="submit" disabled={busy || !name.trim() || (!fromLink && (!hubUrl.trim() || !code.trim()))}>
{busy ? 'Connecting…' : fromLink && o.pending!.kind === 'join' ? 'Join' : 'Connect'}
</button>
{fromLink ? (
<button type="button" className="btn btn-ghost" onClick={() => setManual(true)}>Use a pairing code instead</button>
) : o.pending ? (
<button type="button" className="btn btn-ghost" onClick={() => setManual(false)}>Back to the link</button>
) : (
<button type="button" className="btn btn-ghost" onClick={() => (cancel ? cancel() : setManual(false))}>Back</button>
)}
</form>
);
}
function SecretCard({ vault, s, act }: { vault: string; s: VaultStatus['secrets'][number]; act: (cmd: string, args: Record<string, unknown>, msg: string) => void }) {
const [pointer, setPointer] = useState('');
return (
<div className="need need-secret">
<b>{s.path} wasn't shared: it may contain a secret</b>
{s.found.map((f) => <span key={f} className="muted">{f}</span>)}
<label className="lbl" htmlFor={`p-${s.path}`}>Replace it with where to find it</label>
<input id={`p-${s.path}`} className="field" value={pointer} onChange={(e) => setPointer(e.target.value)} placeholder='e.g. "search prod-deploy in Secrets Manager"' />
<div className="actions">
<button className="btn btn-small" onClick={() => act('not_a_secret', { vault, path: s.path }, `OK — ${s.path} will be shared`)}>Not a secret</button>
<button className="btn btn-small btn-primary" disabled={!pointer.trim()} onClick={() => act('secret_pointer', { vault, path: s.path, pointer }, 'Replaced — sharing now')}>Replace</button>
</div>
</div>
);
}
function VaultCard({ v, several, canUpload, upload, act, compare }: {
v: VaultStatus; several: boolean; canUpload: boolean; upload: (v: VaultStatus) => void;
act: (cmd: string, args: Record<string, unknown>, msg: string) => void; compare: (vault: string, copy: string) => void;
}) {
return (
<article className="vault" data-vault={v.name}>
<div className="vault-head">
<Dot level={v.level} />
<div className="vault-name">
<b>{v.name}{several && v.team && <span className="team-tag">{host(v.team)}</span>}</b>
<span className="muted">{v.headline}</span>
</div>
{canUpload && !v.team && <button className="btn btn-small" onClick={() => upload(v)}>Upload</button>}
<button className="btn btn-small btn-ghost" onClick={() => act('open_folder', { vault: v.name }, '')}>Open folder</button>
</div>
{v.held.map((h) => (
<div key={h.message} className="need">
<b>A big change is waiting for you</b>
<span className="muted">"{h.message}" removes {h.removed} and rewrites {h.rewritten} of {plural(h.total, 'note')}. Nothing from this Mac is shared until you decide.</span>
<div className="actions">
<button className="btn btn-small" onClick={() => act('held_undo', { vault: v.name }, 'Brought everything back')}>Undo</button>
<button className="btn btn-small btn-primary" onClick={() => act('held_share', { vault: v.name }, 'Sharing it')}>Share anyway</button>
</div>
</div>
))}
{v.secrets.map((s) => <SecretCard key={s.path} vault={v.name} s={s} act={act} />)}
{v.tidy.map((t) => (
<div key={t.copy} className="need">
<b>{t.note} was changed in two places</b>
<span className="muted">Both versions are kept; pick one when you have a moment.</span>
<div className="actions">
<button className="btn btn-small btn-primary" onClick={() => compare(v.name, t.copy)}>Compare</button>
</div>
</div>
))}
</article>
);
}
/** Side by side (stacked in this narrow window); differing lines tinted. */
function CompareSheet({ vault, copy, close, done }: { vault: string; copy: string; close: () => void; done: (msg: string) => void }) {
const [c, setC] = useState<Comparison | null>(null);
const [error, setError] = useState('');
useEffect(() => { invoke<Comparison>('compare', { vault, copy }).then(setC).catch((e) => setError(String(e))); }, [vault, copy]);
const keep = async (which: 'note' | 'copy' | 'both') => {
try {
await invoke('tidy', { vault, copy, keep: which });
done(which === 'both' ? 'Kept both as separate notes' : 'Tidied — every device gets it shortly');
} catch (e) {
setError(String(e));
}
};
const column = (title: string, text: string | null, other: string | null, tint: string) => {
const others = new Set((other ?? '').split('\n'));
return (
<div className="cmp-col">
<div className="cmp-head">{title}</div>
<div className="cmp-body">
{text === null ? <span className="muted">Not shown (not a text note, or very large).</span>
: text.split('\n').map((line, i) => <div key={i} style={others.has(line) ? undefined : { background: tint, margin: '0 -14px', padding: '0 14px' }}>{line || ' '}</div>)}
</div>
</div>
);
};
const mine = c?.copy_is_mine;
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label="Compare two versions">
<div><span className="eyebrow">{vault} · {c?.note ?? ''}</span><h2 className="disp">Two versions of the same lines</h2></div>
{error && <p className="error">{error}</p>}
{c && (
<div className="cmp">
{column(mine ? 'The other version (in place)' : 'In place', c.note_text, c.copy_text, '#FBEBD3')}
{column(mine ? "This Mac's version" : `${c.label}'s version`, c.copy_text, c.note_text, '#E8E1FB')}
</div>
)}
<div className="actions">
<button className="btn" onClick={close}>Not now</button>
{c && (
<>
<button className="btn" onClick={() => keep('both')}>Keep both</button>
<button className="btn" onClick={() => keep('note')}>{mine ? 'Keep the other' : 'Keep the one in place'}</button>
<button className="btn btn-primary" onClick={() => keep('copy')}>{mine ? "Keep this Mac's" : `Keep ${c.label}'s`}</button>
</>
)}
</div>
</div>
</div>
);
}
/**
* Putting a vault on a team. A vault that still syncs somewhere else is detached from there first, so its notes
* don't end up in two places; then it goes up with its history.
*/
function UploadSheet({ v, teams, close, done }: { v: VaultStatus; teams: string[]; close: () => void; done: (msg: string) => void }) {
const [team, setTeam] = useState(teams[0]);
const [error, setError] = useState('');
const [busy, setBusy] = useState('');
const [detached, setDetached] = useState(false);
const elsewhere = v.elsewhere && !detached ? v.elsewhere : null;
const run = async (what: string, f: () => Promise<string>) => {
setBusy(what);
setError('');
try {
return await f();
} catch (e) {
setError(String(e));
} finally {
setBusy('');
}
};
const detach = async () => {
const said = await run('Detaching…', () => invoke<string>('detach_vault', { vault: v.name }));
if (said) setDetached(true);
};
const upload = async (fresh: boolean) => {
const said = await run('Uploading…', () => invoke<string>('upload_vault', { vault: v.name, team, fresh }));
if (said) done(said);
};
const secret = error.includes('fresh start');
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget && !busy) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`Upload ${v.name}`}>
<div><span className="eyebrow">{v.name}</span><h2 className="disp">Upload to a team</h2></div>
{elsewhere ? (
<>
<p className="muted">{v.name} syncs with <b>{elsewhere}</b> now. Detach it from there first, so its notes don't end up in two places. It stays on this Mac with all its history; {elsewhere} keeps its copy as it is.</p>
<p className="muted">Other devices that sync it with {elsewhere} won't follow. Once it's on the team, connect them to the team instead.</p>
</>
) : (
<>
<p className="muted">{v.name} {detached ? 'is detached and ' : ''}is only on this Mac. Uploading puts it on the team with its history; you can then give people access on the team canvas.</p>
{teams.length > 1 && (
<>
<label htmlFor="up-team">Team</label>
<select id="up-team" className="field" value={team} onChange={(e) => setTeam(e.target.value)}>
{teams.map((t) => <option key={t} value={t}>{host(t)}</option>)}
</select>
</>
)}
</>
)}
{error && <p className="error" role="alert">{error}</p>}
<div className="actions">
<button className="btn" disabled={!!busy} onClick={close}>{detached ? 'Later' : 'Cancel'}</button>
{elsewhere ? (
<button className="btn btn-primary" disabled={!!busy} onClick={detach}>{busy || `Detach from ${elsewhere}`}</button>
) : secret ? (
<button className="btn btn-primary" disabled={!!busy} onClick={() => upload(true)}>{busy || 'Upload current notes only'}</button>
) : (
<button className="btn btn-primary" disabled={!!busy} onClick={() => upload(false)}>{busy || `Upload to ${host(team)}`}</button>
)}
</div>
</div>
</div>
);
}
/** Leaving a team on this Mac. A team whose hub is gone can be forgotten here instead. */
function LeaveSheet({ team, close, done }: { team: string; close: () => void; done: (msg: string) => void }) {
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const leave = async (forget: boolean) => {
setBusy(true);
setError('');
try {
done(await invoke<string>('leave_team', { team, forget }));
} catch (e) {
setError(String(e));
} finally {
setBusy(false);
}
};
const unreachable = error.includes("can't reach");
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label={`Leave ${host(team)}?`}>
<h2 className="disp">Leave {host(team)}?</h2>
<p className="muted">This Mac hands anything not yet shared to that team, then stops syncing its vaults. The team can add you back later.</p>
{error && <p className="error">{error}</p>}
{unreachable && <p className="muted">If that team is gone for good, forget it on this Mac only: its folders stay where they are, no longer synced.</p>}
<div className="actions">
<button className="btn" onClick={close}>Cancel</button>
{unreachable
? <button className="btn btn-danger" disabled={busy} onClick={() => leave(true)}>Forget it on this Mac</button>
: <button className="btn btn-danger" disabled={busy} onClick={() => leave(false)}>{busy ? 'Leaving…' : 'Leave'}</button>}
</div>
</div>
</div>
);
}
function App() {
const [o, setO] = useState<Overview | null>(null);
const [error, setError] = useState('');
const [toast, setToast] = useState('');
const [comparing, setComparing] = useState<{ vault: string; copy: string } | null>(null);
const [joining, setJoining] = useState(false);
const [leaving, setLeaving] = useState<string | null>(null);
const [uploading, setUploading] = useState<VaultStatus | null>(null);
const [uploadTeams, setUploadTeams] = useState<string[]>([]);
const load = useCallback(() => invoke<Overview>('overview').then(setO).catch((e) => setError(String(e))), []);
useEffect(() => {
load();
const t = setInterval(load, 2000);
return () => clearInterval(t);
}, [load]);
// Which teams this Mac may upload to is learned at each check-in, so it's asked for now and then, not every refresh.
useEffect(() => {
const ask = () => invoke<string[]>('upload_teams').then(setUploadTeams).catch(() => setUploadTeams([]));
ask();
const t = setInterval(ask, 15000);
return () => clearInterval(t);
}, [o?.teams.join(' ')]);
useEffect(() => {
if (!toast) return;
const t = setTimeout(() => setToast(''), 4000);
return () => clearTimeout(t);
}, [toast]);
const act = async (cmd: string, args: Record<string, unknown>, msg: string) => {
try {
await invoke(cmd, args);
if (msg) setToast(msg);
load();
} catch (e) {
setToast(String(e));
}
};
if (!o) return <main className="app">{error && <p className="error">{error}</p>}</main>;
return (
<main className="app">
<header className="top">
<img className="moon-small" src={moon} alt="" />
<div className="top-text">
<b className="disp">Lune</b>
<span className="muted"><Dot level={o.level} /> {o.summary}</span>
</div>
</header>
{o.update && (
<div className="banner">
<span>Lune {o.update} is ready.</span>
<button className="btn btn-small btn-primary" onClick={() => invoke('restart')}>Restart to update</button>
</div>
)}
{!o.connected || o.pending || joining ? (
<Connect o={o} done={(msg) => { setJoining(false); setToast(msg); load(); }} cancel={o.connected ? () => setJoining(false) : undefined} />
) : (
<>
<section className="vaults">
{o.vaults.length === 0 && <p className="muted center">Your vaults are on their way. They'll appear in {o.folder}.</p>}
{o.vaults.map((v) => (
<VaultCard key={v.path} v={v} several={o.teams.length > 1} canUpload={uploadTeams.length > 0} upload={setUploading} act={act} compare={(vault, copy) => setComparing({ vault, copy })} />
))}
</section>
<footer className="foot">
<span className="muted">{o.device} · Lune {o.version}</span>
<ul className="teams">
{o.teams.map((t) => (
<li key={t}>
<span>{host(t)}</span>
<span>
<button className="btn btn-small btn-ghost" onClick={() => act('open_canvas', { team: t }, '')}>Open canvas</button>
<button className="btn btn-small btn-ghost" onClick={() => setLeaving(t)}>Leave</button>
</span>
</li>
))}
</ul>
<div className="actions">
<button className="btn btn-small" onClick={() => act('share_now', {}, 'Sharing now')}>Share now</button>
<button className="btn btn-small" onClick={() => setJoining(true)}>Join another team</button>
</div>
{o.recent.length > 0 && (
<details className="recent">
<summary>Recent activity</summary>
<pre>{o.recent.join('\n')}</pre>
</details>
)}
</footer>
</>
)}
{comparing && <CompareSheet {...comparing} close={() => setComparing(null)} done={(msg) => { setComparing(null); setToast(msg); load(); }} />}
{uploading && <UploadSheet v={uploading} teams={uploadTeams} close={() => { setUploading(null); load(); }} done={(msg) => { setUploading(null); setToast(msg); load(); }} />}
{leaving && <LeaveSheet team={leaving} close={() => setLeaving(null)} done={(msg) => { setLeaving(null); setToast(msg); load(); }} />}
{toast && <div className="toast-d" role="status">{toast}</div>}
</main>
);
}
createRoot(document.getElementById('root')!).render(<StrictMode><App /></StrictMode>);