From fc98db023d1ecce174a038ad14c9587cec802026 Mon Sep 17 00:00:00 2001 From: Johannes Wilm Date: Wed, 11 Nov 2026 15:36:49 +0100 Subject: [PATCH 01/13] Your name: a desktop start takes the operating system account's name instead of "You" Comments, board stickies and live sessions are signed with `Prefs.user_name`, which nothing ever filled, so every install signs as "You" until somebody types a name. A desktop start with a settings folder now asks the machine what the account is called - first and last name, or display name, on Windows; the GECOS name of the passwd entry that our uid names on Linux and the BSDs; `/usr/bin/id -F` on macOS; the logon name wherever none of those exist - and puts it through `pref.userName`, the command the Preferences field uses, so it is trimmed, cleaned of control characters and capped at 64 characters the same way, renames you in a live session at once, marks no document dirty and adds no undo step. It asks only while the stored name is still the placeholder: a name typed in Preferences always wins. A run with no settings folder, and one started for an agent (`--control`, the control port), never asks, so what those runs save and show stays the same on every machine. Both lookups that go through the machine's directory services are bounded by 2 s and run off the start-up thread: macOS's `id` child is killed and waited for at the deadline rather than left behind for the next start to add to, and the Windows Runtime call cannot be interrupted by anyone, so its deadline is a wait. The wait is a helper of its own (`wait_with_deadline`) so that path can be tested at all: no unit test can make Directory Services unresponsive, so it is handed a `sleep` child and checks that the deadline ends the wait and that the child is left reaped, not as a zombie (`kill -0` finds no such process afterwards). On Windows the account is `User::GetDefault()` first - the account this process runs as - falling back to `FindAllAsync()` only when that errors and only if it names exactly one user, so a machine with two signed-in accounts gets no guess. The passwd entry is matched by our uid alone, the logon name never being a key into the file: an account from a directory service has no line in it under its uid *or* its name, so a match by name can only ever land on somebody else's local entry (CodeRabbit's finding here, autocraft-bot's on the DeckCraft sibling). A record the file itself comments out - a line beginning `#`, which `getpwuid` skips - is not an account: a commented-out `#ada:x:1000:...` would otherwise answer for uid 1000 and outrank the live entry below it (CodeRabbit, again on the DeckCraft sibling). `/usr/bin/id` runs by absolute path: a GNU coreutils `id` earlier in `PATH` has no `-F`. The uid is the one the kernel gives for this process, `rustix::process::getuid` (`rustix` already in the build, this adding only its `process` module, as a unix-only target dependency), rather than who owns `/proc/self`, which proc(5) assigns to root for a non-dumpable process, or the environment's logon name, which can say anything; the web and agent runs never reach this file at all. Only the GECOS half before the first comma is decoded, so a Latin-1 in the office field cannot cost the name; a GECOS full name with nothing in it that any cleaning could keep - empty, blanks, control characters - is refused as no name at all, so the logon name has its turn rather than one stray control character in the field leaving "You" (CodeRabbit's finding on the DeckCraft sibling, taken here before it arrived); and the deadline test spawns `sleep` itself, so the process it checks is the process the wait kills. `docs/collab-protocol.md` records that clearing the name is not a lasting choice: the next desktop start refills it from the account, so it stays cleared only for that run. --- Cargo.lock | 1 + ROADMAP.md | 2 + apps/figcraft/Cargo.toml | 17 +- apps/figcraft/src/main.rs | 151 +++++++++++++ apps/figcraft/src/services.rs | 6 + apps/figcraft/src/user_name.rs | 309 +++++++++++++++++++++++++++ apps/figcraft/src/user_name_tests.rs | 140 ++++++++++++ contributors/people.toml | 3 + docs/collab-protocol.md | 7 +- docs/mcp.md | 8 +- 10 files changed, 638 insertions(+), 6 deletions(-) create mode 100644 apps/figcraft/src/user_name.rs create mode 100644 apps/figcraft/src/user_name_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 4a2423c33..c6a793ef4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2816,6 +2816,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "rfd", + "rustix 1.1.5", "serde_json", "wat", "webbrowser", diff --git a/ROADMAP.md b/ROADMAP.md index 788aca315..c7b26714b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -134,6 +134,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log +- **2026-11-11** · M9: a first desktop start signs work with the operating system account's name instead of the default "You". `apps/figcraft/src/user_name.rs` resolves it: on Windows the account's first and last name, else its display name (the Windows Runtime's `Windows.System.User`, a safe API); on Linux and the BSDs the full name in the account's `/etc/passwd` entry (its GECOS field, in the line whose uid field is the uid the kernel gives for this process, which no name can stand in for); on macOS `/usr/bin/id -F`; everywhere else, and as the fallback, the logon name (`USERNAME`/`USER`/`LOGNAME`). It fills Preferences ▸ Your name on any desktop run that has a settings folder and no name chosen yet, so a name set there wins and is never asked over; clearing it there puts the default back, and the next start fills the account's name again, because FigCraft has no empty name to keep (WordCraft #4368 does keep one). The browser build, `figcraft-cli`, the MCP server and a `--control` run never ask, so what an agent signs stays the same on every machine. The two lookups that go through the machine's directory services (Windows Runtime, `/usr/bin/id -F`) run on their own thread with a 2 s deadline, so a directory service that never answers cannot hold up opening the window. The name is cleaned by `pref.userName`, as one typed in Preferences is (trimmed, control characters out, 64 characters). Same change as wordcraft's PR #6286. Tests: `user_name_tests` (6), `system_name_tests` (7). Numbers unchanged. - **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. - **2026-11-05** · M2, #1823: Suggest auto layout is its own command. `layout.suggest` used to run `layout.add` and made one row of everything. It now splits a frame's layers into rows or columns by the gaps between them, wraps each band of several layers in a hugging frame without fill and repeats inside it, so the design gets as many auto layout frames as it needs and keeps its placement where the gaps are even (the frame keeps its size). Uneven gaps, bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes are reported as `warnings`, and instances and layers inside them are refused. `layout.add` is unchanged. Tests in `layout_suggest_tests.rs`. Numbers unchanged. - **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row. @@ -392,6 +393,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | 2026-11-16 | patch | M9, #2365: native and browser clients accept the complete legacy `Welcome` layout without its later reconnect secret, preserving explicit access and rejecting incomplete or trailing data. A host that supplies no secret is rejoined with the share link instead of an unauthenticated `Resume`. Numbers unchanged. | | 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), the exported frame itself hugs where it hugs in the design, a clip is written only on a frame fixed on both axes, and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | | 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. | +| 2026-11-11 | patch | M9: a first desktop start takes the operating system account's name as the name from Preferences ▸ Your name, so comments and board work are signed with it instead of the default "You" (`apps/figcraft/src/user_name.rs`: Windows Runtime first and last name, else display name; `/etc/passwd` GECOS name on Linux and the BSDs; `id -F` on macOS; the logon name as the fallback). Asked whenever the name in the preferences is still the default and the run has a settings folder, never by the browser build, `figcraft-cli`, the MCP server or a `--control` run, and bounded by 2 s so a silent directory service cannot hold up the window. Tests: `user_name_tests` (6), `system_name_tests` (7). Numbers unchanged | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | | 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. | diff --git a/apps/figcraft/Cargo.toml b/apps/figcraft/Cargo.toml index e058e2a4d..623de1177 100644 --- a/apps/figcraft/Cargo.toml +++ b/apps/figcraft/Cargo.toml @@ -39,10 +39,18 @@ image = { workspace = true } env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] } # The system's reduce-motion setting (UISettings.AnimationsEnabled), interface language -# (GlobalizationPreferences.Languages) and controllers for prototypes (Gaming.Input.Gamepad). +# (GlobalizationPreferences.Languages), controllers for prototypes (Gaming.Input.Gamepad) and the +# account's name a first start signs work with (`user_name`: Windows.System.User). `System_UserProfile` +# already pulls in `System`; it is named to say why the app asks the account for its name. [target.'cfg(windows)'.dependencies] craft-update = { workspace = true } -windows = { version = "0.62", default-features = false, features = ["UI_ViewManagement", "System_UserProfile", "Foundation_Collections", "Gaming_Input"] } +windows = { version = "0.62", default-features = false, features = [ + "UI_ViewManagement", + "System_UserProfile", + "System", + "Foundation_Collections", + "Gaming_Input", +] } # The custom title bar's window styles (src/window_frame.rs): safe Win32 wrappers (MIT); the `user` # feature is User32.dll only. Same version as DesignCraft and PhotoCraft. # `shell` is the process identity the Nightly sets for its own taskbar group (process_identity.rs). @@ -53,6 +61,11 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user", "s # accesskit already; this only makes it direct. [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] } +# The account's uid, for the `user_name` passwd lookup: the environment's logon name can say +# anything, and a non-dumpable process's `/proc/self` belongs to root (proc(5)), so neither says +# which account this process runs as. `getuid` through `libc` needs unsafe, which the workspace +# forbids; rustix is already in the build at this version, and this adds only its `process` module. +rustix = { version = "1.1", default-features = false, features = ["std", "process"] } # Finder double-clicks, Open With, Dock drops and `open -a FigCraft file.figcraft` arrive as a # kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This crate (also used by GridCraft, diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index bbad93a50..2d850ec27 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -38,6 +38,7 @@ mod profile_root; mod recovery; mod services; mod startup; +mod user_name; mod window_frame; #[cfg(all(test, target_os = "macos"))] @@ -411,6 +412,12 @@ fn main() -> eframe::Result { if let Some(prefs) = svc.prefs.clone() { session.prefs = prefs; } + // A desktop run that holds no chosen name signs comments, board stickies and live sessions with + // the system account's name rather than the default "You" ([`user_name`]). Asked here, where + // what this run is stays known: whether it has a settings folder to keep a name in, and whether + // an agent started it. Nothing has been commented or drawn yet, so the name is in place before + // anything can be signed. + use_system_user_name(&mut session, asks_for_user_name(svc.has_settings(), port.is_some()), user_name::system); figcraft_engine::keymap::set_custom(&session.prefs.shortcuts); let first_run = svc.prefs.is_none() && args.join.is_none(); // Initialise the interface language before opening files, as startup can now show an import @@ -614,6 +621,43 @@ fn opens_new_file(first_run: bool, control: bool) -> bool { !first_run && control } +/// Whether this start should ask the system for a name to sign work with ([`user_name`]): the run +/// has a settings folder, so a name taken now is kept with the preferences and never asked for +/// again, and it was not started for an agent (`--control`, `FIGCRAFT_CONTROL_PORT`), which has to +/// sign the same way on every machine. A machine that gives the app nowhere to keep anything +/// (`FIGCRAFT_CONFIG_DIR` set empty) asks nothing either. The browser build, `figcraft-cli` and the +/// commands over the control channel never come through here at all. +fn asks_for_user_name(settings: bool, control: bool) -> bool { + settings && !control +} + +/// The system account's name ([`user_name`]) as the name from Preferences, while that is still the +/// default: on a start before the person has named themselves, and on preferences saved back when +/// "You" was the only name there. `ask` is the caller's decision ([`asks_for_user_name`]), so no +/// part of this reads the environment and the tests cover both kinds of run. A name set in +/// Preferences ▸ Your name always wins, and the system is asked only until one is saved. +/// +/// A blank stored name counts as that default too, because that is what `pref.userName` keeps: +/// clearing Preferences ▸ Your name puts the default back, there being no empty name to hold. So, +/// unlike WordCraft (#4368, where a name cleared in Options stays empty), a FigCraft name cleared +/// on a desktop start is filled from the account again; the name to keep is one typed there. +/// +/// The name goes through `pref.userName`, as one typed in Preferences does, so it is cleaned the +/// same way: trimmed, control characters out, capped at `figcraft_engine::live::MAX_NAME`. That +/// command is not journaled and touches no document, so nothing becomes dirty and no undo step +/// appears, and a live session renames you at once, as typing the name does. +fn use_system_user_name(session: &mut Session, ask: bool, system: impl FnOnce() -> Option) { + let stored = session.prefs.user_name.trim(); + if !ask || !(stored.is_empty() || stored == figcraft_engine::cmd::comment::DEFAULT_AUTHOR) { + return; + } + if let Some(name) = system() + && let Err(e) = session.execute("pref.userName", &json!({"name": name})) + { + log::debug!("user name: the system's isn't usable: {e}"); + } +} + /// The title bar FigCraft starts with, decided by the shared craft-window crate so every Craft app /// agrees on who draws the frame per desktop. The override variable is `FIGCRAFT_TITLEBAR` /// (`app` / `system`). macOS keeps its inset traffic lights unchanged (craft-window returns the @@ -813,3 +857,110 @@ mod macos_menu_tests { } } } + +#[cfg(test)] +mod system_name_tests { + use figcraft_engine::Session; + use serde_json::json; + + use super::{asks_for_user_name, use_system_user_name}; + + /// The name comments are signed with until the user sets theirs. + const DEFAULT: &str = figcraft_engine::cmd::comment::DEFAULT_AUTHOR; + + #[test] + fn the_system_user_name_replaces_only_the_default() { + let mut s = Session::new(); + use_system_user_name(&mut s, true, || Some(" Ada\u{7} Lovelace\n".into())); + assert_eq!(s.prefs.user_name, "Ada Lovelace", "cleaned as a name typed in Preferences is"); + assert_eq!(figcraft_engine::live::display_name(&s.prefs), "Ada Lovelace", "and it names you in a live session"); + // A name chosen since, this run or an earlier one, is never asked over. + let mut asked = false; + use_system_user_name(&mut s, true, || { + asked = true; + Some("Grace Hopper".into()) + }); + assert!(!asked, "the system isn't asked once a name is there"); + assert_eq!(s.prefs.user_name, "Ada Lovelace"); + } + + #[test] + fn a_name_from_preferences_wins_and_a_blank_one_counts_as_the_default() { + let mut s = Session::new(); + s.execute("pref.userName", &json!({"name": "Grace Hopper"})).unwrap(); + let mut asked = false; + use_system_user_name(&mut s, true, || { + asked = true; + Some("Ada Lovelace".into()) + }); + assert!(!asked, "a name the person set asks nothing"); + assert_eq!(s.prefs.user_name, "Grace Hopper"); + // Preferences saved before this change hold the default, and a hand-edited settings file + // can hold nothing: both are the missing name the system fills. + for stored in [DEFAULT, "", " "] { + let mut s = Session::new(); + s.prefs.user_name = stored.into(); + use_system_user_name(&mut s, true, || Some("Ada Lovelace".into())); + assert_eq!(s.prefs.user_name, "Ada Lovelace", "{stored:?}"); + } + } + + #[test] + fn a_comment_signed_with_the_system_name_is_still_yours() { + // Which comments are yours is the name in the message against the name in the preferences, + // so taking the system's name signs and owns them like any other name. + let mut s = Session::new(); + use_system_user_name(&mut s, true, || Some("Ada Lovelace".into())); + let c = s.execute("comment.add", &json!({"x": 0, "y": 0, "text": "Mine"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(s.doc().unwrap().comment(c).unwrap().first.author, "Ada Lovelace"); + s.execute("comment.edit", &json!({"id": c, "text": "Still mine"})).unwrap(); + s.execute("comment.delete", &json!({"id": c})).unwrap(); + } + + #[test] + fn only_a_run_with_a_settings_folder_and_no_agent_asks() { + assert!(asks_for_user_name(true, false), "a desktop run with somewhere to keep the name"); + assert!(!asks_for_user_name(false, false), "nowhere to keep a name"); + assert!(!asks_for_user_name(true, true), "--control: started for an agent"); + assert!(!asks_for_user_name(false, true), "neither a settings folder nor a person"); + } + + #[test] + fn a_cleared_name_is_the_default_and_is_taken_from_the_account_again() { + // Clearing Preferences ▸ Your name puts the default back (`pref.userName` has no empty name + // to hold), so the next desktop start reads it as "no name chosen" and fills the account's. + // WordCraft (#4368) keeps a cleared name empty; FigCraft has no cleared state to honour, so + // the name to keep is one typed there. + let mut s = Session::new(); + s.execute("pref.userName", &json!({"name": "Grace Hopper"})).unwrap(); + s.execute("pref.userName", &json!({"name": " "})).unwrap(); + assert_eq!(s.prefs.user_name, DEFAULT, "cleared: the default, not an empty name"); + use_system_user_name(&mut s, asks_for_user_name(true, false), || Some("Ada Lovelace".into())); + assert_eq!(s.prefs.user_name, "Ada Lovelace", "the account names the run again"); + use_system_user_name(&mut s, asks_for_user_name(true, false), || Some("Someone Else".into())); + assert_eq!(s.prefs.user_name, "Ada Lovelace", "and is never asked over a chosen name"); + } + + #[test] + fn a_run_without_a_settings_folder_or_an_agents_run_never_asks() { + for (settings, control, why) in [(false, false, "no settings folder"), (true, true, "started for an agent")] { + let mut asked = false; + let mut s = Session::new(); + use_system_user_name(&mut s, asks_for_user_name(settings, control), || { + asked = true; + Some("Ada Lovelace".into()) + }); + assert!(!asked, "{why}: no lookup at all"); + assert_eq!(s.prefs.user_name, DEFAULT, "{why}: the default signs"); + } + } + + #[test] + fn no_usable_system_name_keeps_the_default() { + for system in [None, Some(String::new()), Some(" \t\n".into()), Some("\u{0}\u{1b}".into())] { + let mut s = Session::new(); + use_system_user_name(&mut s, true, || system.clone()); + assert_eq!(s.prefs.user_name, DEFAULT, "{system:?}"); + } + } +} diff --git a/apps/figcraft/src/services.rs b/apps/figcraft/src/services.rs index e23294567..79e2e340e 100644 --- a/apps/figcraft/src/services.rs +++ b/apps/figcraft/src/services.rs @@ -124,6 +124,12 @@ impl Desktop { } } + /// Whether this run has a settings folder to read preferences from and keep them in + /// ([`config_dir`]; they may not be there yet, on a first start). + pub fn has_settings(&self) -> bool { + self.dir.is_some() + } + /// winit reports no system theme on Linux and the BSDs: there the freedesktop colour scheme /// answers instead, read once and then watched in the background, calling `wake` when it /// changes (an idle window draws no frames). Elsewhere this does nothing. diff --git a/apps/figcraft/src/user_name.rs b/apps/figcraft/src/user_name.rs new file mode 100644 index 000000000..c8c48e141 --- /dev/null +++ b/apps/figcraft/src/user_name.rs @@ -0,0 +1,309 @@ +//! The user name a desktop start takes while none has been chosen: the system account's, so +//! comments, board stickies and live sessions carry the designer's name rather than the default +//! "You" (`figcraft_engine::cmd::comment::DEFAULT_AUTHOR`). A name set in Preferences ▸ Your name +//! is saved and wins from then on (`crate::use_system_user_name`). +//! +//! - Windows: the account's first and last name, else its display name (only a domain or work +//! account has one), read through the Windows Runtime's `Windows.System.User`: a safe API, +//! where the Win32 `GetUserNameExW` needs unsafe, which our workspace forbids. Without either +//! (an account with no name, or account info access turned off in Settings › Privacy), the +//! logon name. +//! - Linux, the BSDs: the full name in the running account's `/etc/passwd` entry — the line whose +//! uid field is our uid, asked of the kernel rather than inferred: an environment variable can say +//! anything, and the line named by the logon name can only ever be somebody else's. The name is +//! the GECOS field up to its first comma, as `chfn` sets it. Accounts from a directory service +//! (LDAP, SSSD) have no line in that file at all, under their uid or their name, and take the +//! logon name. +//! - macOS: the full name Directory Services keeps for the account, from the system's own lookup +//! (`/usr/bin/id -F`), else the logon name. `objc2-app-kit` binds no `NSFullUserName`, and reading +//! Directory Services directly needs unsafe, which our workspace forbids. A directory service +//! that doesn't answer must not hold up the start, so like the Windows call it is asked on its +//! own thread with a timeout ([`LOOKUP_TIMEOUT`]), and its `id` process is stopped and waited +//! for when that deadline passes instead of being left running for the next start to repeat. +//! - Runs the app keeps no preferences for (no settings folder: `FIGCRAFT_CONFIG_DIR` set empty), +//! runs started for an agent (`--control`, `FIGCRAFT_CONTROL_PORT`) and the browser build, +//! `figcraft-cli` and the MCP server, which never call this, keep the default: what they sign or +//! save must stay the same on every machine (the desktop start passes that decision as `ask`). +//! +//! Every source is untrusted: the name still goes through `pref.userName`, as one typed in +//! Preferences does, which trims it, drops control characters and caps it at +//! `figcraft_engine::live::MAX_NAME`. + +use std::ffi::OsString; + +/// The variables holding the logon name; the first with a usable one wins. +#[cfg(target_os = "windows")] +const LOGON_VARS: &[&str] = &["USERNAME"]; +#[cfg(not(target_os = "windows"))] +const LOGON_VARS: &[&str] = &["USER", "LOGNAME"]; + +/// How long a host account lookup may take before the logon name is used instead. Both the +/// Windows Runtime call and macOS's `id -F` go through the directory services of the machine, and +/// neither is guaranteed to answer when one of them is misconfigured or unreachable. The Windows +/// call is left to its own thread when it overruns, a Windows Runtime call not being one anyone can +/// interrupt; the `id` process is stopped and waited for at the same deadline. +#[cfg(any(target_os = "windows", target_os = "macos", all(test, unix)))] +const LOOKUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); + +/// The most of `/etc/passwd` read: far more than any real one holds. +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +const MAX_PASSWD_BYTES: u64 = 4 << 20; + +/// The name of the account running FigCraft: its full name where the system has one, else its +/// logon name; `None` without either. +pub fn system() -> Option { + let login = logon_name(|var| std::env::var_os(var)); + #[cfg(target_os = "windows")] + { + if let Some(name) = windows_account_name() { + return Some(name); + } + } + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + { + if let Some(name) = passwd_full_name() { + return Some(name); + } + } + #[cfg(target_os = "macos")] + { + if let Some(name) = directory_services_full_name() { + return Some(name); + } + } + login +} + +/// The logon name: the first of [`LOGON_VARS`] that holds a Unicode, non-blank one. +fn logon_name(var: impl Fn(&str) -> Option) -> Option { + LOGON_VARS.iter().find_map(|name| Some(var(name)?.into_string().ok()?.trim().to_owned()).filter(|v| !v.is_empty())) +} + +/// The account's name from the Windows Runtime ([`account_name`]), bounded by [`ask_with_timeout`]. +/// `None` when there is none, or on any failure (logged). +#[cfg(target_os = "windows")] +fn windows_account_name() -> Option { + ask_with_timeout("account lookup", || match account_name() { + Ok(name) => Some(name).filter(|n| !n.trim().is_empty()), + Err(e) => { + log::debug!("user name: account lookup failed: {e}"); + None + } + }) +} + +/// `ask`'s answer, asked on a thread of its own so a host lookup that never answers can't hold up +/// opening the window: `what` names it in the log, [`LOOKUP_TIMEOUT`] bounds the wait. A lookup +/// still running when the timeout passes carries on and finishes on its own, its own thread +/// waiting for it (so an `id -F` child is still waited for and reaped); the start doesn't. +#[cfg(any(target_os = "windows", target_os = "macos"))] +fn ask_with_timeout(what: &str, ask: impl FnOnce() -> Option + Send + 'static) -> Option { + let (tx, rx) = std::sync::mpsc::channel(); + if let Err(e) = std::thread::Builder::new().name("user-name".into()).spawn(move || { + let _ = tx.send(ask()); + }) { + log::debug!("user name: no {what} thread: {e}"); + return None; + } + match rx.recv_timeout(LOOKUP_TIMEOUT) { + Ok(answer) => answer, + Err(_) => { + log::debug!("user name: {what} gave no answer within {LOOKUP_TIMEOUT:?}"); + None + } + } +} + +/// The account's name ([`chosen`] from its first, last and display names). Empty when the account +/// has none of them. +#[cfg(target_os = "windows")] +fn account_name() -> windows::core::Result { + use windows::System::{KnownUserProperties, User}; + // The account this process runs as. `GetDefault` names that one; `FindAllAsync` enumerates the + // session's users, so it is the fallback, and only when it answers with exactly one — a + // machine with two signed-in accounts (fast user switching) gets no name from us rather than a + // guess at which of them this is. + let user = match User::GetDefault() { + Ok(user) => user, + Err(e) => { + log::debug!("user name: no default account: {e}"); + let users = User::FindAllAsync()?.join()?; + if users.Size()? != 1 { + return Ok(String::new()); + } + users.GetAt(0)? + } + }; + let first = user_property(&user, "first name", KnownUserProperties::FirstName); + let last = user_property(&user, "last name", KnownUserProperties::LastName); + Ok(chosen(&first, &last, || user_property(&user, "display name", KnownUserProperties::DisplayName)).unwrap_or_default()) +} + +/// One of `user`'s text properties (`what` names it in the log); empty when the account doesn't +/// have it, or when the lookup fails (logged), so the next source is still tried. +#[cfg(target_os = "windows")] +fn user_property(user: &windows::System::User, what: &str, name: fn() -> windows::core::Result) -> String { + use windows::Foundation::IReference; + use windows::core::{HSTRING, Interface}; + let read = || -> windows::core::Result { + let value = user.GetPropertyAsync(&name()?)?.join()?; + Ok(value.cast::>()?.Value()?.to_string()) + }; + read().unwrap_or_else(|e| { + log::debug!("user name: account {what}: {e}"); + String::new() + }) +} + +/// Which of the account's names is the user name: its first and last name ([`joined`]), else its +/// display name (asked only then) — Windows has a display name only for a domain or work account, +/// a first and last name for any account. `None` when all are blank. +#[cfg(any(test, target_os = "windows"))] +fn chosen(first: &str, last: &str, display: impl FnOnce() -> String) -> Option { + joined(first, last).or_else(|| Some(display().trim().to_owned()).filter(|n| !n.is_empty())) +} + +/// A first and a last name as one name (`Ada` + `Lovelace` → `Ada Lovelace`), either alone when +/// the other is blank; `None` when both are. +#[cfg(any(test, target_os = "windows"))] +fn joined(first: &str, last: &str) -> Option { + let name = [first.trim(), last.trim()].into_iter().filter(|part| !part.is_empty()).collect::>().join(" "); + Some(name).filter(|n| !n.is_empty()) +} + +/// The running account's full name in `/etc/passwd` ([`full_name`]), in the line whose uid field is +/// the one the kernel gives for this process; `None` when the file can't be read or has no line for +/// it. The uid comes from the system rather than from the environment or from procfs ownership: a +/// logon name can say anything, and a non-dumpable process's `/proc/self` reads as root (proc(5)). +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +fn passwd_full_name() -> Option { + use std::io::Read; + let uid = rustix::process::getuid().as_raw().to_string(); + let mut passwd = Vec::new(); + match std::fs::File::open("/etc/passwd").and_then(|f| f.take(MAX_PASSWD_BYTES).read_to_end(&mut passwd)) { + Ok(_) => full_name(&passwd, &uid), + Err(e) => { + log::debug!("user name: /etc/passwd: {e}"); + None + } + } +} + +/// The full name in the entry of a `passwd` file (`name:password:UID:GID:GECOS:home:shell` lines) +/// whose uid field reads exactly `uid`, as the system's own lookup reads it. The name is the +/// GECOS field up to its first comma (the rest is office and phone numbers), with `&` standing for +/// the entry's name capitalised, a BSD convention. `None` without an entry, with a full name that +/// has nothing any cleaning could keep (empty, blanks, control characters), or with a *name* that +/// isn't UTF-8: the office and phone fields behind the first comma are never read, so a Latin-1 in +/// one of them keeps nothing. +#[cfg(any(test, all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))] +fn full_name(passwd: &[u8], uid: &str) -> Option { + // As `getpwuid` reads the file: a line whose first character that is neither a space nor a tab is + // `#` is a comment in the file, not an account, so it is skipped rather than matched. A + // commented-out `#ada:x:1000:...` would otherwise answer for uid 1000 and outrank the live + // `ada:x:1000:...` line below it, indented just as much, since the uid is still its third field. + let is_comment = |line: &[u8]| matches!(line.iter().find(|b| !matches!(**b, b' ' | b'\t')), Some(&b'#')); + let entries: Vec> = + passwd.split(|&b| b == b'\n').filter(|line| !is_comment(line)).map(|line| line.split(|&b| b == b':').collect()).collect(); + // Our own entry, and only ours. The entry named by the logon name is not a candidate: an + // account from a directory service has no line in this file under its uid or its name, so a + // match by name can only ever land on somebody else's local entry - and a full name is + // somebody's, so guessing wrong signs their work. The uid is matched whole, not as a prefix, so + // `100` never takes `1000`'s entry, and the first line with our uid is the one, as `getpwuid`. + let entry = entries.iter().find(|fields| fields.get(2) == Some(&uid.as_bytes()))?; + let account = std::str::from_utf8(entry.first()?).ok()?; + // Only the part of GECOS before the first comma has to be UTF-8. The office and phone fields + // behind it are never read, and a Latin-1 in one of them must not cost the person their name. + let gecos = entry.get(4)?; + let name = match gecos.iter().position(|&b| b == b',') { + Some(comma) => &gecos[..comma], + None => gecos, + }; + let name = std::str::from_utf8(name).ok()?; + let name = if name.contains('&') { name.replace('&', &capitalised(account)) } else { name.to_owned() }; + // A full name with nothing in it that a cleaning could keep - blanks, control characters - is no + // name at all: `None` lets the logon name have its turn, rather than one stray control character + // in the GECOS field leaving the person with the placeholder. The name itself is handed on as it + // stands, each app cleaning a name the same way it cleans one typed in. + let nothing_left = name.chars().filter(|c| !c.is_control()).collect::().trim().is_empty(); + (!nothing_left).then(|| name.trim().to_owned()) +} + +/// The macOS account's full name, from the system's own Directory Services lookup (`id -F`, which +/// prints the login name when the account has no real name), bounded by [`ask_with_timeout`] so the +/// window never waits on it; `None` when it fails. +#[cfg(target_os = "macos")] +fn directory_services_full_name() -> Option { + ask_with_timeout("id -F", lookup_id_dash_f) +} + +/// Wait for `child` until `deadline`; `None` if it has not answered by then, in which case it is +/// stopped and waited for, so a lookup that never finishes leaves no process behind for the next +/// start to add to. `what` names it in the log. Split out from the `id -F` lookup because a test +/// cannot make Directory Services unresponsive, but it can hand a wait like this a child that never +/// ends, which is what `a_child_that_never_answers_is_stopped_at_its_deadline` does. +#[cfg(any(target_os = "macos", all(test, unix)))] +fn wait_with_deadline(mut child: std::process::Child, deadline: std::time::Instant, what: &str) -> Option { + loop { + match child.try_wait() { + Ok(Some(status)) => return Some(status), + Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(10)), + Ok(None) => { + log::debug!("user name: {what} gave no answer within {LOOKUP_TIMEOUT:?}"); + let _ = child.kill(); + let _ = child.wait(); + return None; + } + Err(e) => { + log::debug!("user name: {what}: {e}"); + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + } +} + +/// The system's own `id -F`, run as `/usr/bin/id`: a GNU coreutils `id` earlier in `PATH`, easy to +/// have on a Mac with coreutils installed, has no `-F` and would only print an error. Stopped and +/// waited for if it outlives [`LOOKUP_TIMEOUT`]: a directory service that never answers would +/// otherwise leave an `id` process waiting on every start. The name it prints is far below what a +/// pipe holds, so reading its output after it finished cannot block. +#[cfg(target_os = "macos")] +fn lookup_id_dash_f() -> Option { + use std::io::Read; + use std::process::{Command, Stdio}; + let mut child = match Command::new("/usr/bin/id").arg("-F").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() { + Ok(child) => child, + Err(e) => { + log::debug!("user name: id -F: {e}"); + return None; + } + }; + let (out, err) = (child.stdout.take(), child.stderr.take()); + let status = wait_with_deadline(child, std::time::Instant::now() + LOOKUP_TIMEOUT, "id -F")?; + let mut text = String::new(); + if status.success() { + if let Some(mut pipe) = out { + let _ = pipe.read_to_string(&mut text); + } + } else { + if let Some(mut pipe) = err { + let _ = pipe.read_to_string(&mut text); + } + log::debug!("user name: id -F: {}", text.trim()); + return None; + } + Some(text.trim().to_owned()).filter(|n| !n.is_empty()) +} + +/// `word` with its first letter upper case (`ada` → `Ada`). +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +fn capitalised(word: &str) -> String { + let mut chars = word.chars(); + chars.next().map(|first| first.to_uppercase().chain(chars).collect()).unwrap_or_default() +} + +#[cfg(test)] +#[path = "user_name_tests.rs"] +mod tests; diff --git a/apps/figcraft/src/user_name_tests.rs b/apps/figcraft/src/user_name_tests.rs new file mode 100644 index 000000000..18ae4d9a1 --- /dev/null +++ b/apps/figcraft/src/user_name_tests.rs @@ -0,0 +1,140 @@ +//! The shapes [`crate::user_name`] accepts and rejects: the GECOS forms of a `/etc/passwd` entry, +//! the logon-name variables, and the names the Windows Runtime returns. The file is a synthetic +//! one; no real account or personal name is in it. + +use std::ffi::OsString; + +use super::*; + +/// The deadline half of the macOS lookup, which is otherwise untestable: no test can make Directory +/// Services unresponsive, so the child here is a `sleep` and the waiting code is the same. The wait +/// must end at its deadline with the child stopped and reaped, not run to the child's own end. +#[cfg(unix)] +#[test] +fn a_child_that_never_answers_is_stopped_at_its_deadline() { + use std::process::Stdio; + // `sleep` itself, not a shell standing in front of it: the process the check below looks for + // has to be the one the wait is meant to stop. + let Ok(child) = std::process::Command::new("sleep").arg("30").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else { + return; // no `sleep` to time out on: the waiting code is not what changed + }; + let started = std::time::Instant::now(); + let pid = child.id(); + let deadline = started + std::time::Duration::from_millis(200); + assert!(wait_with_deadline(child, deadline, "sleep").is_none(), "the deadline ends the wait, not the child"); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "and it ends it at the deadline, not after the sleep: {:?}", started.elapsed()); + // Stopped *and* waited for: a child that was only killed would still be a process, and + // `kill -0` finds zombies. So nothing is left for the next start to pile up behind. + let still_there = std::process::Command::new("sh").arg("-c").arg(format!("kill -0 {pid}")).status().is_ok_and(|status| status.success()); + assert!(!still_there, "the child is reaped, not left running or waiting"); +} + +const PASSWD: &[u8] = b"# local accounts\n\ + #ada:x:1000:1000:Older Ada,commented out:/home/not-ada:/bin/sh\n\ + \t#ada2:x:1000:1000:Older Ada,indented comment:/home/not-ada2:/bin/sh\n\ + root:x:0:0:root:/root:/bin/bash\n\ + ada:x:1000:1000:Ada Lovelace,Room 1,+44 20,,:/home/ada:/bin/zsh\n\ + anna:x:1001:1001:& Smith:/home/anna:/bin/sh\r\n\ + bob:x:1002:1002::/home/bob:/bin/sh\n\ + carl:x:1003:1003: ,office:/home/carl:/bin/sh\n\ + dee:x:1004:1004:Dee \xe9:/home/dee:/bin/sh\n\ + ren:x:1008:1008:Rene Dupont,Office \xe9:/home/ren:/bin/sh\n\ + eve:x:1005\n\ + zoe:x:1006:1006:Zo\xc3\xab Kowalska:/home/zoe:/bin/sh\n\ + zoe:x:1007:1007:Someone Else:/home/zoe2:/bin/sh\n\ + gus:x:1009:1009:\x07\x02:/home/gus:/bin/sh\n\ + +ldapuser::::::"; + +#[test] +fn the_passwd_full_name_is_the_gecos_name_without_office_and_phones() { + assert_eq!(full_name(PASSWD, "0").as_deref(), Some("root")); + // The commented-out line above with the same uid is not an account, and is skipped as + // `getpwuid` skips it; the real entry below is the one. + assert_eq!(full_name(PASSWD, "1000").as_deref(), Some("Ada Lovelace")); + // `&` is the entry's own name, capitalised; a Windows line ending is no part of the name. + assert_eq!(full_name(PASSWD, "1001").as_deref(), Some("Anna Smith")); + // The first line with our uid is the one, as `getpwuid` reads it. + assert_eq!(full_name(PASSWD, "1006").as_deref(), Some("Zoë Kowalska")); + assert_eq!(full_name(PASSWD, "1007").as_deref(), Some("Someone Else")); + // A Latin-1 in the office field behind the name costs nothing: only the name half is read. + assert_eq!(full_name(PASSWD, "1008").as_deref(), Some("Rene Dupont")); +} + +#[test] +fn no_usable_passwd_name_falls_back_to_the_logon_name() { + for (uid, why) in [ + ("1002", "an empty GECOS field"), + ("1003", "a full name of blanks"), + ("1004", "a full name that isn't UTF-8 (Latin-1)"), + ("1005", "a cut-off entry"), + ("1009", "a full name of control characters only"), + ("4242", "no line for our uid"), + ("", "the empty uid field of a NIS `+` line"), + ("100", "a prefix of another uid, not a whole match"), + ("ada", "a logon name is no uid, and the line named by it is somebody else's"), + ] { + assert_eq!(full_name(PASSWD, uid), None, "{why} ({uid:?})"); + } + assert_eq!(full_name(b"", "1000"), None, "an empty file"); + assert_eq!(full_name(b"ada:x:1000:1000:Ada Lovelace", "1000").as_deref(), Some("Ada Lovelace"), "no shell or home"); +} + +#[test] +fn the_logon_name_skips_blank_and_non_unicode_variables() { + let env = + |vars: &'static [(&'static str, &'static str)]| move |name: &str| vars.iter().find(|(k, _)| *k == name).map(|(_, v)| OsString::from(*v)); + let first = LOGON_VARS.first().copied().unwrap_or_default(); + assert_eq!(logon_name(env(&[])), None); + assert_eq!(logon_name(|name| (name == first).then(|| OsString::from(" ada \t"))).as_deref(), Some("ada")); + assert_eq!(logon_name(|name| (name == first).then(|| OsString::from(" \t "))), None); + #[cfg(not(target_os = "windows"))] + { + assert_eq!(logon_name(env(&[("USER", "ada"), ("LOGNAME", "root")])).as_deref(), Some("ada"), "USER first"); + assert_eq!(logon_name(env(&[("USER", " "), ("LOGNAME", "ada")])).as_deref(), Some("ada")); + use std::os::unix::ffi::OsStringExt; + let bad = |name: &str| match name { + "USER" => Some(OsString::from_vec(b"caf\xe9".to_vec())), + "LOGNAME" => Some(OsString::from("ada")), + _ => None, + }; + assert_eq!(logon_name(bad).as_deref(), Some("ada"), "a name that isn't UTF-8 is skipped"); + } +} + +#[test] +fn a_first_and_last_name_join_into_one() { + assert_eq!(joined("Ada", "Lovelace").as_deref(), Some("Ada Lovelace")); + assert_eq!(joined(" Zoë ", "\tKowalska ").as_deref(), Some("Zoë Kowalska")); + // Either alone is the name; with neither the display name is tried. + assert_eq!(joined("Ada", "").as_deref(), Some("Ada")); + assert_eq!(joined(" ", "Lovelace").as_deref(), Some("Lovelace")); + assert_eq!(joined("", ""), None); + assert_eq!(joined(" \t", " "), None); +} + +#[test] +fn the_first_and_last_name_win_over_the_display_name() { + let asked = std::cell::Cell::new(false); + let display = |name: &'static str| { + let asked = &asked; + move || { + asked.set(true); + name.to_owned() + } + }; + assert_eq!(chosen("Ada", "Lovelace", display("Contoso Admin")).as_deref(), Some("Ada Lovelace")); + assert!(!asked.get(), "the display name is asked only without a first or last name"); + assert_eq!(chosen("", "Lovelace", display("Contoso Admin")).as_deref(), Some("Lovelace")); + // Without either (a domain account may have only a display name), the display name. + assert_eq!(chosen(" ", "", display(" Ada Lovelace ")).as_deref(), Some("Ada Lovelace")); + assert!(asked.get()); + assert_eq!(chosen("", "", display(" \t")), None, "no name at all: the logon name follows"); +} + +#[test] +fn capitalised_upper_cases_the_first_letter_only() { + assert_eq!(capitalised("ada"), "Ada"); + assert_eq!(capitalised("éva"), "Éva"); + assert_eq!(capitalised("ß"), "SS"); + assert_eq!(capitalised(""), ""); +} diff --git a/contributors/people.toml b/contributors/people.toml index 2510f4a97..5dd3c0602 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -152,3 +152,6 @@ sync_github_name = true real_name = "Bryton Cooper" display_name = "Bryton Cooper" sync_github_name = true + +[people.johanneswilm] +real_name = "Johannes Wilm" diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 14558fe2c..d412c14eb 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -466,7 +466,12 @@ resuming with its offline edits, and leaving the session going back to snapshot coordinates on whatever page you look at and nothing is outlined. - Colours and names: the host hands out the first free colour of an eight-colour palette and "Guest N" to people without a name (Preferences ▸ Your name, `pref.userName`; also in the Share - popover and the Join dialog). Changing it while in a session renames you there at once (a + popover and the Join dialog; a desktop start arrives named unless you have set one, because it + takes the system account's name into that preference). Clearing it goes back to "Guest N" as + before, with one exception worth knowing: clearing is not a lasting choice - the next desktop + start fills the name from the account again, so it stays cleared only for as long as that run + lasts, or until a name of your own is set, which the start-up does not touch. Changing it while + in a session renames you there at once (a `name` signal, sent again after a reconnect, whose hello has the old name); clearing it keeps the session's name until you join again. After a newcomer's `Welcome` the host sends it its own `PeerJoined`, which is how it learns its name and colour. diff --git a/docs/mcp.md b/docs/mcp.md index 018ee2bde..89c7ee031 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1618,9 +1618,11 @@ and read state are its own, it can edit and delete only its own messages, and it `"agent": true` in `comment.list` (the app shows an **Agent** label by the name); the user's name in Preferences is unchanged. It is set once per connection, so no command needs `author`; an `author` param still wins. In the app, comments act as the name from Preferences (`pref.userName {name}`, -default "You"); only a message's author can edit or delete it. `@Name` in a message mentions -someone (`comment.people` lists the names used in the file: everyone who wrote or reacted, and -every name a message @mentions, once each in any case; and, as `you`, who is acting). +default "You"); only a message's author can edit or delete it. A first desktop start takes the +operating system account's name into that preference instead of "You"; the CLI, this server and a +`--control` run keep the default, so what an agent signs is the same on every machine. `@Name` in a +message mentions someone (`comment.people` lists the names used in the file: everyone who wrote or +reacted, and every name a message @mentions, once each in any case; and, as `you`, who is acting). Read state is kept per name: a new message is unread for everyone but its author; `comment.markRead {id? | link?, read?}` marks one thread (or, without `id`, all of them) read or From f7c033e466a73247738ce4bc74e8bcc80cd0c54f Mon Sep 17 00:00:00 2001 From: Johannes Wilm Date: Wed, 18 Nov 2026 21:09:04 +0100 Subject: [PATCH 02/13] Comments: keep You-authored threads owned after renaming --- apps/figcraft/src/main.rs | 33 ++++++++++ crates/doc/src/comments.rs | 33 ++++++++-- crates/engine/src/cmd/comment.rs | 77 ++++++++++++++-------- crates/engine/src/comments_polish_tests.rs | 39 ++++++++++- crates/ui-egui/src/canvas/comments.rs | 39 +++++++---- 5 files changed, 176 insertions(+), 45 deletions(-) diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index 2d850ec27..958a82b76 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -917,6 +917,39 @@ mod system_name_tests { s.execute("comment.delete", &json!({"id": c})).unwrap(); } + #[test] + fn comments_saved_as_you_stay_mine_after_the_system_name_arrives() { + // The upgrade regression: a file written under the old default keeps its authors on disk, + // and the renamed person keeps edit, delete, Mine and read state for those threads. + let dir = std::env::temp_dir().join(format!("figcraft-system-name-upgrade-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("comments.figcraft").to_string_lossy().into_owned(); + + let mut before = Session::new(); + let c = before.execute("comment.add", &json!({"x": 0, "y": 0, "text": "Old note"})).unwrap()["id"].as_u64().unwrap(); + before.execute("comment.reply", &json!({"id": c, "text": "Old reply"})).unwrap(); + before.execute("file.saveAs", &json!({"path": path})).unwrap(); + + let mut s = Session::new(); + use_system_user_name(&mut s, true, || Some("Ada Lovelace".into())); + assert_eq!(s.prefs.user_name, "Ada Lovelace"); + s.execute("file.open", &json!({"path": path})).unwrap(); + let saved = s.doc().unwrap().comment(c).unwrap().clone(); + assert_eq!(saved.first.author, DEFAULT, "opening the file does not rewrite its author"); + assert_eq!(saved.replies[0].author, DEFAULT, "nor its replies"); + assert!(!saved.is_unread_as("Ada Lovelace", Some(DEFAULT)), "read under You stays read"); + + let mine = s.execute("comment.list", &json!({"page": "all", "filter": "mine"})).unwrap(); + assert!(mine["comments"].as_array().unwrap().iter().any(|comment| comment["id"] == c), "the old thread is Mine"); + assert!(s.execute("comment.edit", &json!({"id": c, "text": "Not yours", "author": "Sam"})).is_err()); + s.execute("comment.edit", &json!({"id": c, "text": "Updated"})).unwrap(); + s.execute("comment.edit", &json!({"id": c, "reply": 0, "text": "Updated reply"})).unwrap(); + s.execute("comment.delete", &json!({"id": c, "reply": 0})).unwrap(); + s.execute("comment.delete", &json!({"id": c})).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn only_a_run_with_a_settings_folder_and_no_agent_asks() { assert!(asks_for_user_name(true, false), "a desktop run with somewhere to keep the name"); diff --git a/crates/doc/src/comments.rs b/crates/doc/src/comments.rs index 4e43b84d7..ca3989710 100644 --- a/crates/doc/src/comments.rs +++ b/crates/doc/src/comments.rs @@ -148,21 +148,44 @@ impl Comment { /// `user` wrote in the thread or is @mentioned in it. pub fn involves(&self, user: &str) -> bool { - self.messages().any(|m| m.author == user || !mention_ranges(&m.text, &[user]).is_empty()) + self.involves_as(user, None) + } + + /// [`Self::involves`], with `legacy_user` counting as `user` too. An old default author can be + /// claimed this way after the local person's real name replaces the placeholder, without + /// rewriting the messages in the file. + pub fn involves_as(&self, user: &str, legacy_user: Option<&str>) -> bool { + self.messages() + .any(|m| m.author == user || legacy_user.is_some_and(|legacy| m.author == legacy) || !mention_ranges(&m.text, &[user]).is_empty()) } /// The thread has something `user` hasn't read. pub fn is_unread(&self, user: &str) -> bool { - self.read_by.as_ref().is_some_and(|r| !r.iter().any(|u| u == user)) + self.is_unread_as(user, None) + } + + /// [`Self::is_unread`], with `legacy_user` counting as `user` too: a thread read under the old + /// default name stays read when that person is renamed. + pub fn is_unread_as(&self, user: &str, legacy_user: Option<&str>) -> bool { + self.read_by.as_ref().is_some_and(|r| !r.iter().any(|u| u == user || legacy_user.is_some_and(|legacy| u == legacy))) } /// Mark the thread read or unread for `user`. True when it changed. pub fn set_read(&mut self, user: &str, read: bool) -> bool { - if read != self.is_unread(user) { + self.set_read_as(user, read, None) + } + + /// [`Self::set_read`], with `legacy_user` counting as `user` too. Marking the renamed person + /// unread drops the old default name from the readers; marking them read needs no write when + /// the old default name already recorded that they had read it. + pub fn set_read_as(&mut self, user: &str, read: bool, legacy_user: Option<&str>) -> bool { + if read != self.is_unread_as(user, legacy_user) { return false; } if read { - if let Some(r) = self.read_by.as_mut() { + if let Some(r) = self.read_by.as_mut() + && !r.iter().any(|u| u == user) + { r.push(user.to_string()); } return true; @@ -172,7 +195,7 @@ impl Comment { self.read_by = Some(self.participants().into_iter().map(String::from).collect()); } if let Some(r) = self.read_by.as_mut() { - r.retain(|u| u != user); + r.retain(|u| u != user && !legacy_user.is_some_and(|legacy| u == legacy)); } true } diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 87c9cfe9d..0ed5cf609 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -3,7 +3,8 @@ //! Messages are addressed by `reply` (an index into the replies; omitted: the thread's first //! message). `author` is who is acting (default: the AI agent the command runs for, else the name //! from Preferences, `pref.userName`): only a message's author edits or deletes it, and only the -//! thread's author deletes the thread. +//! thread's author deletes the thread. A message signed with the old default `You` remains the +//! local person's after their real name arrives, without rewriting the file's author string. use std::fmt::Write as _; @@ -99,13 +100,13 @@ impl Filter { Self::ALL.into_iter().find(|f| f.id().eq_ignore_ascii_case(s.trim())) } - pub fn keeps(self, c: &Comment, user: &str) -> bool { + pub fn keeps(self, c: &Comment, user: &str, legacy_user: Option<&str>) -> bool { match self { Filter::All => true, Filter::Open => !c.resolved, Filter::Resolved => c.resolved, - Filter::Mine => c.involves(user), - Filter::Unread => c.is_unread(user), + Filter::Mine => c.involves_as(user, legacy_user), + Filter::Unread => c.is_unread_as(user, legacy_user), } } } @@ -161,15 +162,16 @@ impl Default for Query<'_> { } } -/// The comments `q` asks for, as `user` sees them, in order. -pub fn query<'a>(doc: &'a Document, q: &Query, user: &str) -> Vec<&'a Comment> { +/// The comments `q` asks for, as `user` sees them, in order. `legacy_user` is an old placeholder +/// name (the default author) that still counts as `user` after a real name replaces it. +pub fn query<'a>(doc: &'a Document, q: &Query, user: &str, legacy_user: Option<&str>) -> Vec<&'a Comment> { let needle = q.text.trim().to_lowercase(); let mut out: Vec<&Comment> = doc .comments .iter() .filter(|c| doc.pages.contains(&c.page)) .filter(|c| q.page.is_none_or(|p| c.page == p)) - .filter(|c| q.filter.keeps(c, user)) + .filter(|c| q.filter.keeps(c, user, legacy_user)) .filter(|c| q.frame.is_none_or(|f| frame_of(doc, c) == Some(f))) .filter(|c| needle.is_empty() || matches_text(doc, c, &needle)) .collect(); @@ -290,6 +292,19 @@ fn author(s: &Session, p: &Value) -> String { string(p, "author").map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).unwrap_or_else(|| acting_name(s)) } +/// The old default author, when it still identifies `who` in this session: `who` is the local +/// person (not an AI agent acting for them) whose real name has replaced `You`. Other people and +/// agents get no claim on placeholder-authored messages. +pub fn legacy_default(s: &Session, who: &str) -> Option<&'static str> { + (s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR) +} + +/// Whether `m` is `who`'s message in this session, including a placeholder-authored message the +/// local person wrote before their real name arrived. +pub fn is_own(s: &Session, m: &Message, who: &str) -> bool { + m.author == who || legacy_default(s, who).is_some_and(|default| m.author == default) +} + /// A new message by `who`, marked as an agent's when the command runs for one. fn new_message(s: &Session, who: String, text: String) -> Message { Message { agent: s.agent.is_some(), ..Message::new(who, text, now_secs()) } @@ -304,8 +319,8 @@ fn text(cmd: &str, p: &Value) -> crate::Result { } /// Refuse to change someone else's message. -fn own(cmd: &str, m: &Message, who: &str, what: &str) -> crate::Result<()> { - if m.author == who { +fn own(cmd: &str, m: &Message, who: &str, legacy_user: Option<&str>, what: &str) -> crate::Result<()> { + if m.author == who || legacy_user.is_some_and(|legacy| m.author == legacy) { return Ok(()); } Err(bad(cmd, format!("only {} can {what} (acting as {who}; pass `author` to act as someone else)", m.author))) @@ -371,7 +386,10 @@ fn listed<'s>(cmd: &str, s: &'s Session, p: &Value, who: &str, people: &[&str]) let (page, filter, sort, text) = list_params(cmd, s, p)?; let want = mentions_param(cmd, p)?; let q = Query { page, frame: id(p, "frame"), filter, sort, text: &text }; - Ok(query(s.doc()?, &q, who).into_iter().filter(|c| want.as_deref().is_none_or(|w| thread_mentions(c, people, w))).collect()) + Ok(query(s.doc()?, &q, who, legacy_default(s, who)) + .into_iter() + .filter(|c| want.as_deref().is_none_or(|w| thread_mentions(c, people, w))) + .collect()) } /// Add the names `text` @mentions to `named` as `{name, known, you}`, each once. @@ -423,7 +441,7 @@ fn message_json(m: &Message, people: &[&str], user: &str) -> Value { /// JSON view of a comment as `user` sees it: its page position, frame, read state and link, the /// first message's fields, and the replies; mentions resolve against `people` (`mentionable`). -pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str]) -> Value { +pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str], legacy_user: Option<&str>) -> Value { let (x, y) = c.position(doc); let frame = frame_of(doc, c); let mut v = message_json(&c.first, people, user); @@ -431,7 +449,7 @@ pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str]) -> "id": c.id, "page": c.page, "pageName": doc.node(c.page).map(|n| n.name.as_str()), "x": x, "y": y, "anchor": c.anchor, "frame": frame, "frameName": frame.and_then(|f| doc.node(f)).map(|n| n.name.as_str()), - "resolved": c.resolved, "unread": c.is_unread(user), "link": link(c.id), + "resolved": c.resolved, "unread": c.is_unread_as(user, legacy_user), "link": link(c.id), "replies": c.replies.iter().map(|m| message_json(m, people, user)).collect::>(), }); if let (Some(m), Value::Object(e)) = (v.as_object_mut(), extra) { @@ -442,7 +460,7 @@ pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str]) -> /// Bounded metadata for `comment.prompt`'s `comments` list. Full messages and replies stay in /// `comment.list`; a prompt over thousands of threads must not repeat all of them here. -fn comment_brief_json(doc: &Document, c: &Comment, user: &str, people: &[&str]) -> Value { +fn comment_brief_json(doc: &Document, c: &Comment, user: &str, people: &[&str], legacy_user: Option<&str>) -> Value { let (x, y) = c.position(doc); let frame = frame_of(doc, c); // The names the whole thread @mentions, as `comment.list` reports them per message. @@ -464,7 +482,7 @@ fn comment_brief_json(doc: &Document, c: &Comment, user: &str, people: &[&str]) "pageName": doc.node(c.page).map(|n| clip_chars(&n.name, 80)), "x": x, "y": y, "anchor": c.anchor, "frame": frame, "frameName": frame.and_then(|f| doc.node(f)).map(|n| clip_chars(&n.name, 80)), - "resolved": c.resolved, "unread": c.is_unread(user), "link": link(c.id), + "resolved": c.resolved, "unread": c.is_unread_as(user, legacy_user), "link": link(c.id), "author": clip_chars(&c.first.author, 80), "agent": c.first.agent, "preview": clip_chars(&c.first.text, 160), "replies": c.replies.len(), "mentions": named, }) @@ -503,17 +521,18 @@ fn reveal(s: &mut Session, id: u64, how: &str) -> crate::Result<()> { /// Reveal a thread (`how`: fit, center or keep), mark it read for `who` and ask the UI to open it. fn open(s: &mut Session, id: u64, how: &str, who: &str) -> crate::Result { + let legacy = legacy_default(s, who); reveal(s, id, how)?; - if s.doc()?.comment(id).is_some_and(|c| c.is_unread(who)) + if s.doc()?.comment(id).is_some_and(|c| c.is_unread_as(who, legacy)) && let Some(c) = s.doc_mut()?.comment_mut(id) { - c.set_read(who, true); + c.set_read_as(who, true, legacy); } s.request_ui("comment.open", json!({"id": id})); let doc = s.doc()?; let c = doc.comment(id).ok_or_else(|| bad("comment.open", "no comment"))?; let people = doc.comment_people(); - Ok(comment_json(doc, c, who, &mentionable(&people, who))) + Ok(comment_json(doc, c, who, &mentionable(&people, who), legacy)) } /// A list's page (None: every page), filter, sort and search text from params. @@ -718,11 +737,12 @@ pub fn specs() -> Vec { let id = req_comment("comment.edit", s, p)?; let t = text("comment.edit", p)?; let who = author(s, p); + let legacy = legacy_default(s, &who); let (i, same) = { let c = s.doc()?.comment(id).ok_or_else(|| bad("comment.edit", "no comment"))?; let i = message_index("comment.edit", c, p)?; let m = c.message(i).ok_or_else(|| bad("comment.edit", "no message"))?; - own("comment.edit", m, &who, "edit this message")?; + own("comment.edit", m, &who, legacy, "edit this message")?; (i, m.text == t) }; // The same text is no edit (and no undo step). @@ -791,16 +811,17 @@ pub fn specs() -> Vec { |s, p| { let id = req_comment("comment.delete", s, p)?; let who = author(s, p); + let legacy = legacy_default(s, &who); let doc = s.doc_mut()?; let c = doc.comment_mut(id).ok_or_else(|| bad("comment.delete", "no comment"))?; match message_index("comment.delete", c, p)? { 0 => { - own("comment.delete", &c.first, &who, "delete this thread")?; + own("comment.delete", &c.first, &who, legacy, "delete this thread")?; doc.comments.retain(|c| c.id != id); } i => { let m = c.message(i).ok_or_else(|| bad("comment.delete", "no message"))?; - own("comment.delete", m, &who, "delete this reply")?; + own("comment.delete", m, &who, legacy, "delete this reply")?; c.replies.remove(i - 1); } } @@ -816,14 +837,15 @@ pub fn specs() -> Vec { let read = boolean(p, "read").unwrap_or(true); let who = author(s, p); let only = if get(p, "id").is_some() || get(p, "link").is_some() { Some(req_comment("comment.markRead", s, p)?) } else { None }; - let wants = |c: &Comment| only.is_none_or(|i| c.id == i) && c.is_unread(&who) == read; + let legacy = legacy_default(s, &who); + let wants = |c: &Comment| only.is_none_or(|i| c.id == i) && c.is_unread_as(&who, legacy) == read; // The document is left alone when nothing changes (no unsaved changes for nothing). if !s.doc()?.comments.iter().any(wants) { return Ok(json!({"changed": 0})); } let mut n = 0; for c in s.doc_mut()?.comments.iter_mut().filter(|c| only.is_none_or(|i| c.id == i)) { - n += usize::from(c.set_read(&who, read)); + n += usize::from(c.set_read_as(&who, read, legacy)); } Ok(json!({"changed": n})) } @@ -904,8 +926,10 @@ pub fn specs() -> Vec { let who = author(s, p); let people = doc.comment_people(); let people = mentionable(&people, &who); - let list: Vec = - listed("comment.list", s, p, &who, &people)?.into_iter().map(|c| comment_json(doc, c, &who, &people)).collect(); + let list: Vec = listed("comment.list", s, p, &who, &people)? + .into_iter() + .map(|c| comment_json(doc, c, &who, &people, legacy_default(s, &who))) + .collect(); Ok(json!({"comments": list})) } ), @@ -962,13 +986,14 @@ pub fn specs() -> Vec { out } else { let search = string(p, "query").unwrap_or_default(); - query(doc, &Query { page, frame: None, filter, sort, text: &search }, &who) + query(doc, &Query { page, frame: None, filter, sort, text: &search }, &who, legacy_default(s, &who)) }; let count = selected.len(); let (text, truncated) = prompt_text(doc, path.as_deref(), &selected); let people = doc.comment_people(); let people = mentionable(&people, &who); - let comments: Vec = selected.iter().take(PROMPT_MAX_THREADS).map(|c| comment_brief_json(doc, c, &who, &people)).collect(); + let comments: Vec = + selected.iter().take(PROMPT_MAX_THREADS).map(|c| comment_brief_json(doc, c, &who, &people, legacy_default(s, &who))).collect(); Ok(json!({"count": count, "truncated": truncated, "text": text, "comments": comments})) } ), diff --git a/crates/engine/src/comments_polish_tests.rs b/crates/engine/src/comments_polish_tests.rs index 9fb0bf736..a9c50b05b 100644 --- a/crates/engine/src/comments_polish_tests.rs +++ b/crates/engine/src/comments_polish_tests.rs @@ -90,16 +90,51 @@ fn only_authors_edit_and_delete_their_messages() { assert_eq!(comment(&s, c).replies[0].text, "Second!"); s.execute("comment.delete", &json!({"id": c, "reply": 0, "author": "Sam"})).unwrap(); assert!(comment(&s, c).replies.is_empty()); - // Your name from Preferences signs and owns your comments. + // Your name from Preferences signs and owns your comments, including ones the old default + // signed before the real name arrived. s.execute("pref.userName", &json!({"name": " Ada "})).unwrap(); let d = s.execute("comment.add", &json!({"x": 0, "y": 0, "text": "Mine"})).unwrap()["id"].as_u64().unwrap(); assert_eq!(comment(&s, d).first.author, "Ada"); - assert!(s.execute("comment.delete", &json!({"id": c})).is_err()); + s.execute("comment.delete", &json!({"id": c})).unwrap(); + assert!(s.doc().unwrap().comment(c).is_none()); s.execute("comment.delete", &json!({"id": d})).unwrap(); s.execute("pref.userName", &json!({"name": " "})).unwrap(); assert_eq!(s.prefs.user_name, "You"); } +#[test] +fn default_authored_comments_stay_mine_after_the_person_is_renamed() { + let mut s = Session::new(); + let c = add(&mut s, 0.0, 0.0, "First", "You"); + s.execute("comment.reply", &json!({"id": c, "text": "Mine too"})).unwrap(); + + // The desktop start-up hook fills in the real name; the saved message authors stay as they + // were, so ownership has to recognize the old placeholder. + s.execute("pref.userName", &json!({"name": "Ada"})).unwrap(); + let mine = list(&mut s, json!({"page": "all", "filter": "mine"})); + assert_eq!(mine, vec![c], "a legacy You thread is still Mine for the renamed person"); + assert!(!comment(&s, c).is_unread_as("Ada", Some("You")), "read under You stays read"); + + // Neither another named person nor an AI agent inherits the placeholder's messages. + assert!(s.execute("comment.edit", &json!({"id": c, "text": "No", "author": "Sam"})).is_err()); + s.agent = Some("Claude".into()); + assert!(s.execute("comment.edit", &json!({"id": c, "text": "No"})).is_err()); + s.agent = None; + + s.execute("comment.edit", &json!({"id": c, "text": "First, edited"})).unwrap(); + s.execute("comment.edit", &json!({"id": c, "reply": 0, "text": "Mine too, edited"})).unwrap(); + s.execute("comment.delete", &json!({"id": c, "reply": 0})).unwrap(); + + // Marking the renamed person unread does not resurrect the placeholder as a separate reader. + s.execute("comment.markRead", &json!({"id": c, "read": false})).unwrap(); + assert!(comment(&s, c).is_unread_as("Ada", Some("You"))); + s.execute("comment.markRead", &json!({"id": c})).unwrap(); + assert!(!comment(&s, c).is_unread_as("Ada", Some("You"))); + + s.execute("comment.delete", &json!({"id": c})).unwrap(); + assert!(s.doc().unwrap().comment(c).is_none()); +} + #[test] fn reactions_toggle_per_person() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/canvas/comments.rs b/crates/ui-egui/src/canvas/comments.rs index c0cfa8d6e..7f0bf75c0 100644 --- a/crates/ui-egui/src/canvas/comments.rs +++ b/crates/ui-egui/src/canvas/comments.rs @@ -232,8 +232,15 @@ struct Pin { } impl Pin { - fn of(c: &Comment, me: &str, at: Pos2) -> Self { - Pin { id: c.id, author: c.first.author.clone(), resolved: c.resolved, unread: c.is_unread(me), mine: c.first.author == me, at } + fn of(c: &Comment, me: &str, legacy_user: Option<&str>, at: Pos2) -> Self { + Pin { + id: c.id, + author: c.first.author.clone(), + resolved: c.resolved, + unread: c.is_unread_as(me, legacy_user), + mine: c.first.author == me || legacy_user.is_some_and(|legacy| c.first.author == legacy), + at, + } } } @@ -242,9 +249,10 @@ impl Pin { fn pins(app: &FigApp) -> Vec { let Ok(ds) = app.session.ds() else { return Vec::new() }; let me = me(app); + let legacy = cc::legacy_default(&app.session, &me); let cu = &app.ui.comments; let q = Query { page: Some(ds.page), filter: cu.filter, ..Query::default() }; - let mut list = cc::query(&ds.doc, &q, &me); + let mut list = cc::query(&ds.doc, &q, &me, legacy); list.reverse(); if let Some(c) = cu.open.and_then(|o| ds.doc.comment(o)).filter(|c| c.page == ds.page && !list.iter().any(|x| x.id == c.id)) { list.push(c); @@ -260,7 +268,7 @@ fn pins(app: &FigApp) -> Vec { app.to_screen(x, y) } }; - Pin::of(c, &me, at) + Pin::of(c, &me, legacy, at) }) .collect() } @@ -658,6 +666,8 @@ struct ThreadCtx<'a> { c: &'a Comment, me: &'a str, people: &'a [String], + /// The old default author that still counts as `me` after a real name arrives. + legacy_user: Option<&'a str>, } /// One message: author, time, its buttons on hover (react; edit and delete when it's yours), the @@ -686,7 +696,7 @@ fn message( let when = if m.edited > 0 { trf("{when} · edited", &[("when", &ago(m.created))]) } else { ago(m.created) }; ui.label(egui::RichText::new(when).font(regular(11.0)).color(t.text_tertiary)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if m.author == cx.me { + if m.author == cx.me || cx.legacy_user.is_some_and(|legacy| m.author == legacy) { let menu = Id::unique(("comment_msg_more_menu", id, i)); let more = hover_button( ui, @@ -909,14 +919,15 @@ pub fn thread(app: &mut FigApp, ctx: &egui::Context, id: u64, anchor: Pos2, boun }; let people = ds.doc.comment_people(); let me = me(app); - if c.is_unread(&me) && !previewing { + let legacy = cc::legacy_default(&app.session, &me); + if c.is_unread_as(&me, legacy) && !previewing { app.run("comment.markRead", json!({"id": id})); } let mut reply = std::mem::take(&mut app.ui.comments.reply); let mut editing = app.ui.comments.editing.take().filter(|e| e.0 == id && c.message(e.1).is_some()); let mut pick = std::mem::take(&mut app.ui.comments.mention); let mut act: Option = None; - let cx = ThreadCtx { c: &c, me: &me, people: &people }; + let cx = ThreadCtx { c: &c, me: &me, people: &people, legacy_user: legacy }; egui::Area::new(Id::unique("comment_thread")).order(egui::Order::Foreground).fixed_pos(popover_pos(anchor, bounds)).show(ctx, |ui| { popover_frame(&t).show(ui, |ui| { ui.set_width(POPOVER_W - 24.0); @@ -945,7 +956,9 @@ pub fn thread(app: &mut FigApp, ctx: &egui::Context, id: u64, anchor: Pos2, boun act = Some(Act::Run("comment.resolve", json!({"id": id, "resolved": !c.resolved}))); ui.close(); } - if c.first.author == me && crate::right::menu_item(ui, tr("Delete thread"), "") { + if (c.first.author == me || legacy.is_some_and(|default| c.first.author == default)) + && crate::right::menu_item(ui, tr("Delete thread"), "") + { act = Some(Act::Run("comment.delete", json!({"id": id}))); ui.close(); } @@ -1078,6 +1091,7 @@ pub fn panel(app: &mut FigApp, ui: &mut Ui) { let page = ds.page; let doc = ds.doc.clone(); let me = me(app); + let legacy = cc::legacy_default(&app.session, &me); ui.add_space(8.0); ui.horizontal(|ui| { ui.add_space(16.0); @@ -1136,7 +1150,7 @@ pub fn panel(app: &mut FigApp, ui: &mut Ui) { ui.add_space(8.0); let search = app.ui.comments.search.clone(); let q = Query { page: None, frame: None, filter: app.ui.comments.filter, sort: app.ui.comments.sort, text: &search }; - let list = cc::query(&doc, &q, &me); + let list = cc::query(&doc, &q, &me, legacy); if list.is_empty() { let (title, sub) = if doc.comments.iter().any(|c| doc.pages.contains(&c.page)) { (tr("No matching comments"), tr("Try another search or filter.")) @@ -1178,7 +1192,7 @@ pub fn panel(app: &mut FigApp, ui: &mut Ui) { } else if resp.hovered() { ui.painter().rect_filled(r, CornerRadius::ZERO, t.hover); } - let unread = c.is_unread(&me); + let unread = c.is_unread_as(&me, legacy); if unread { ui.painter().circle_filled(pos2(r.min.x + 8.0, r.min.y + 22.0), 3.5, ACCENT); } @@ -1230,16 +1244,17 @@ pub fn presenter(app: &mut FigApp, ctx: &egui::Context, frame: NodeId, place: cr let doc = ds.doc.clone(); let Some(fb) = doc.world_bounds(frame) else { return }; let me = me(app); + let legacy = cc::legacy_default(&app.session, &me); let open = app.ui.comments.open; // The frame as designed maps onto the frame as presented. let to_screen = |(x, y): (f64, f64)| place.pt(place.page_min.0 + x - fb.x0, place.page_min.1 + y - fb.y0); let q = Query { frame: Some(frame), filter: app.ui.comments.filter, ..Query::default() }; - let mut list = cc::query(&doc, &q, &me); + let mut list = cc::query(&doc, &q, &me, legacy); list.reverse(); if let Some(c) = open.and_then(|o| doc.comment(o)).filter(|c| cc::frame_of(&doc, c) == Some(frame) && !list.iter().any(|x| x.id == c.id)) { list.push(c); } - let pins: Vec = list.iter().map(|c| Pin::of(c, &me, to_screen(c.position(&doc)))).filter(|p| clip.contains(p.at)).collect(); + let pins: Vec = list.iter().map(|c| Pin::of(c, &me, legacy, to_screen(c.position(&doc)))).filter(|p| clip.contains(p.at)).collect(); let mut clicked = None; for p in &pins { let r = pin_rect(p.at); From bce8e3802b8be4ef1e546b858a1044a9cba84dbc Mon Sep 17 00:00:00 2001 From: Johannes Wilm Date: Thu, 19 Nov 2026 08:48:26 +0100 Subject: [PATCH 03/13] Preferences: no Windows session-user fallback in the account lookup FindAllAsync enumerates the session's users, and a sole session user is not established to be the account the process runs as, so when User::GetDefault errors the lookup now takes no name from it and the logon name follows instead. Same change as deckcraft#2034. --- apps/figcraft/src/user_name.rs | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/apps/figcraft/src/user_name.rs b/apps/figcraft/src/user_name.rs index c8c48e141..5b72ff134 100644 --- a/apps/figcraft/src/user_name.rs +++ b/apps/figcraft/src/user_name.rs @@ -119,21 +119,12 @@ fn ask_with_timeout(what: &str, ask: impl FnOnce() -> Option + Send + 's #[cfg(target_os = "windows")] fn account_name() -> windows::core::Result { use windows::System::{KnownUserProperties, User}; - // The account this process runs as. `GetDefault` names that one; `FindAllAsync` enumerates the - // session's users, so it is the fallback, and only when it answers with exactly one — a - // machine with two signed-in accounts (fast user switching) gets no name from us rather than a - // guess at which of them this is. - let user = match User::GetDefault() { - Ok(user) => user, - Err(e) => { - log::debug!("user name: no default account: {e}"); - let users = User::FindAllAsync()?.join()?; - if users.Size()? != 1 { - return Ok(String::new()); - } - users.GetAt(0)? - } - }; + // Only `GetDefault` names an account here: it names the account this process runs as. There is + // deliberately no fallback to `FindAllAsync`, which enumerates the session's users: a sole + // session user is not established to be the process's account (the review threads on this + // change), so when `GetDefault` errors the account has no name from us and the logon name + // follows, rather than a guess at whose name this is. + let user = User::GetDefault().inspect_err(|e| log::debug!("user name: no default account: {e}"))?; let first = user_property(&user, "first name", KnownUserProperties::FirstName); let last = user_property(&user, "last name", KnownUserProperties::LastName); Ok(chosen(&first, &last, || user_property(&user, "display name", KnownUserProperties::DisplayName)).unwrap_or_default()) From e6e1366cca91307cfe2d0da8621c4969be96e553 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 1 Dec 2026 19:38:11 +0700 Subject: [PATCH 04/13] Comments: one written_by check for You-authored ownership; lockfile after rebase The "author is me, or the old default while my real name stands in" test was written out in own() and three places in the comment UI, and the session-based is_own helper was never called. comment::written_by replaces both. Cargo.lock: rustix 1.1.6, the version main now carries; the roadmap rows count the tests the change adds (7 and 8). --- Cargo.lock | 2 +- ROADMAP.md | 4 ++-- crates/engine/src/cmd/comment.rs | 10 +++++----- crates/ui-egui/src/canvas/comments.rs | 8 +++----- 4 files changed, 11 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c6a793ef4..441b16bc2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2816,7 +2816,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "rfd", - "rustix 1.1.5", + "rustix 1.1.6", "serde_json", "wat", "webbrowser", diff --git a/ROADMAP.md b/ROADMAP.md index c7b26714b..566725c06 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -134,7 +134,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). ## Progress log -- **2026-11-11** · M9: a first desktop start signs work with the operating system account's name instead of the default "You". `apps/figcraft/src/user_name.rs` resolves it: on Windows the account's first and last name, else its display name (the Windows Runtime's `Windows.System.User`, a safe API); on Linux and the BSDs the full name in the account's `/etc/passwd` entry (its GECOS field, in the line whose uid field is the uid the kernel gives for this process, which no name can stand in for); on macOS `/usr/bin/id -F`; everywhere else, and as the fallback, the logon name (`USERNAME`/`USER`/`LOGNAME`). It fills Preferences ▸ Your name on any desktop run that has a settings folder and no name chosen yet, so a name set there wins and is never asked over; clearing it there puts the default back, and the next start fills the account's name again, because FigCraft has no empty name to keep (WordCraft #4368 does keep one). The browser build, `figcraft-cli`, the MCP server and a `--control` run never ask, so what an agent signs stays the same on every machine. The two lookups that go through the machine's directory services (Windows Runtime, `/usr/bin/id -F`) run on their own thread with a 2 s deadline, so a directory service that never answers cannot hold up opening the window. The name is cleaned by `pref.userName`, as one typed in Preferences is (trimmed, control characters out, 64 characters). Same change as wordcraft's PR #6286. Tests: `user_name_tests` (6), `system_name_tests` (7). Numbers unchanged. +- **2026-11-11** · M9: a first desktop start signs work with the operating system account's name instead of the default "You". `apps/figcraft/src/user_name.rs` resolves it: on Windows the account's first and last name, else its display name (the Windows Runtime's `Windows.System.User`, a safe API); on Linux and the BSDs the full name in the account's `/etc/passwd` entry (its GECOS field, in the line whose uid field is the uid the kernel gives for this process, which no name can stand in for); on macOS `/usr/bin/id -F`; everywhere else, and as the fallback, the logon name (`USERNAME`/`USER`/`LOGNAME`). It fills Preferences ▸ Your name on any desktop run that has a settings folder and no name chosen yet, so a name set there wins and is never asked over; clearing it there puts the default back, and the next start fills the account's name again, because FigCraft has no empty name to keep (WordCraft #4368 does keep one). The browser build, `figcraft-cli`, the MCP server and a `--control` run never ask, so what an agent signs stays the same on every machine. The two lookups that go through the machine's directory services (Windows Runtime, `/usr/bin/id -F`) run on their own thread with a 2 s deadline, so a directory service that never answers cannot hold up opening the window. The name is cleaned by `pref.userName`, as one typed in Preferences is (trimmed, control characters out, 64 characters). Same change as wordcraft's PR #6286. Tests: `user_name_tests` (7), `system_name_tests` (8). Numbers unchanged. - **2026-11-07** · M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. - **2026-11-05** · M2, #1823: Suggest auto layout is its own command. `layout.suggest` used to run `layout.add` and made one row of everything. It now splits a frame's layers into rows or columns by the gaps between them, wraps each band of several layers in a hugging frame without fill and repeats inside it, so the design gets as many auto layout frames as it needs and keeps its placement where the gaps are even (the frame keeps its size). Uneven gaps, bands that start at different offsets across the flow (lined up at the smallest) and layers that overlap along both axes are reported as `warnings`, and instances and layers inside them are refused. `layout.add` is unchanged. Tests in `layout_suggest_tests.rs`. Numbers unchanged. - **2026-11-05** · M3, #2002: the Local variables window selects several variables with a click, Shift+click (range) and Cmd/Ctrl+click (toggle), cleared by Escape or a click on the empty space; delete, move to a group and scope act on the selected local variables as one undo step (`command.batch`); inherited variables can be selected but are left out, since they change in their own collection, and the bulk menu needs two or more local variables selected (otherwise the row shows its own menu). Rename and value edits stay single-row. @@ -393,7 +393,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | 2026-11-16 | patch | M9, #2365: native and browser clients accept the complete legacy `Welcome` layout without its later reconnect secret, preserving explicit access and rejecting incomplete or trailing data. A host that supplies no secret is rejoined with the share link instead of an unauthenticated `Resume`. Numbers unchanged. | | 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), the exported frame itself hugs where it hugs in the design, a clip is written only on a frame fixed on both axes, and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). | | 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. | -| 2026-11-11 | patch | M9: a first desktop start takes the operating system account's name as the name from Preferences ▸ Your name, so comments and board work are signed with it instead of the default "You" (`apps/figcraft/src/user_name.rs`: Windows Runtime first and last name, else display name; `/etc/passwd` GECOS name on Linux and the BSDs; `id -F` on macOS; the logon name as the fallback). Asked whenever the name in the preferences is still the default and the run has a settings folder, never by the browser build, `figcraft-cli`, the MCP server or a `--control` run, and bounded by 2 s so a silent directory service cannot hold up the window. Tests: `user_name_tests` (6), `system_name_tests` (7). Numbers unchanged | +| 2026-11-11 | patch | M9: a first desktop start takes the operating system account's name as the name from Preferences ▸ Your name, so comments and board work are signed with it instead of the default "You" (`apps/figcraft/src/user_name.rs`: Windows Runtime first and last name, else display name; `/etc/passwd` GECOS name on Linux and the BSDs; `id -F` on macOS; the logon name as the fallback). Asked whenever the name in the preferences is still the default and the run has a settings folder, never by the browser build, `figcraft-cli`, the MCP server or a `--control` run, and bounded by 2 s so a silent directory service cannot hold up the window. Tests: `user_name_tests` (7), `system_name_tests` (8). Numbers unchanged | | 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged | | 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. | | 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. | diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 0ed5cf609..8fd842033 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -299,10 +299,10 @@ pub fn legacy_default(s: &Session, who: &str) -> Option<&'static str> { (s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR) } -/// Whether `m` is `who`'s message in this session, including a placeholder-authored message the -/// local person wrote before their real name arrived. -pub fn is_own(s: &Session, m: &Message, who: &str) -> bool { - m.author == who || legacy_default(s, who).is_some_and(|default| m.author == default) +/// Whether a message signed `author` is `who`'s, counting `legacy_user` ([`legacy_default`]) as +/// `who`: a placeholder-authored message the local person wrote before their real name arrived. +pub fn written_by(author: &str, who: &str, legacy_user: Option<&str>) -> bool { + author == who || legacy_user == Some(author) } /// A new message by `who`, marked as an agent's when the command runs for one. @@ -320,7 +320,7 @@ fn text(cmd: &str, p: &Value) -> crate::Result { /// Refuse to change someone else's message. fn own(cmd: &str, m: &Message, who: &str, legacy_user: Option<&str>, what: &str) -> crate::Result<()> { - if m.author == who || legacy_user.is_some_and(|legacy| m.author == legacy) { + if written_by(&m.author, who, legacy_user) { return Ok(()); } Err(bad(cmd, format!("only {} can {what} (acting as {who}; pass `author` to act as someone else)", m.author))) diff --git a/crates/ui-egui/src/canvas/comments.rs b/crates/ui-egui/src/canvas/comments.rs index 7f0bf75c0..151b47382 100644 --- a/crates/ui-egui/src/canvas/comments.rs +++ b/crates/ui-egui/src/canvas/comments.rs @@ -238,7 +238,7 @@ impl Pin { author: c.first.author.clone(), resolved: c.resolved, unread: c.is_unread_as(me, legacy_user), - mine: c.first.author == me || legacy_user.is_some_and(|legacy| c.first.author == legacy), + mine: cc::written_by(&c.first.author, me, legacy_user), at, } } @@ -696,7 +696,7 @@ fn message( let when = if m.edited > 0 { trf("{when} · edited", &[("when", &ago(m.created))]) } else { ago(m.created) }; ui.label(egui::RichText::new(when).font(regular(11.0)).color(t.text_tertiary)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if m.author == cx.me || cx.legacy_user.is_some_and(|legacy| m.author == legacy) { + if cc::written_by(&m.author, cx.me, cx.legacy_user) { let menu = Id::unique(("comment_msg_more_menu", id, i)); let more = hover_button( ui, @@ -956,9 +956,7 @@ pub fn thread(app: &mut FigApp, ctx: &egui::Context, id: u64, anchor: Pos2, boun act = Some(Act::Run("comment.resolve", json!({"id": id, "resolved": !c.resolved}))); ui.close(); } - if (c.first.author == me || legacy.is_some_and(|default| c.first.author == default)) - && crate::right::menu_item(ui, tr("Delete thread"), "") - { + if cc::written_by(&c.first.author, &me, legacy) && crate::right::menu_item(ui, tr("Delete thread"), "") { act = Some(Act::Run("comment.delete", json!({"id": id}))); ui.close(); } From e7cb62e92e082bbf01786da478222d63379eaf1d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 1 Dec 2026 19:54:31 +0700 Subject: [PATCH 05/13] Comments: a reaction left as You follows the rename comment.react and the reaction chips matched only the current name, so after the desktop start filled in a real name, toggling a reaction left under the old default added a second one instead of taking it back, and the chip showed it as somebody else's. Message::reacted_as / react_as count the legacy name as the person, like set_read_as already does. The "this name is me, or my old default" rule now lives once in the doc crate (figcraft_doc::is_user) and replaces the engine's written_by and the inline copies in involves_as, is_unread_as and set_read_as. Test: a_reaction_left_as_you_follows_the_rename. --- crates/doc/src/comments.rs | 34 +++++++++++++++++----- crates/engine/src/cmd/comment.rs | 13 +++------ crates/engine/src/comments_polish_tests.rs | 21 +++++++++++++ crates/ui-egui/src/canvas/comments.rs | 10 +++---- 4 files changed, 56 insertions(+), 22 deletions(-) diff --git a/crates/doc/src/comments.rs b/crates/doc/src/comments.rs index ca3989710..59c28111c 100644 --- a/crates/doc/src/comments.rs +++ b/crates/doc/src/comments.rs @@ -6,6 +6,13 @@ use serde::{Deserialize, Serialize}; use crate::{Document, NodeId}; +/// Whether `name` (a message's author, a reader, a reactor) is `user`, counting `legacy_user` as +/// `user` too: the old default name the local person wrote, read and reacted under before their +/// real name replaced it. +pub fn is_user(name: &str, user: &str, legacy_user: Option<&str>) -> bool { + name == user || legacy_user == Some(name) +} + /// An emoji reaction on a message and who left it. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Reaction { @@ -45,13 +52,25 @@ impl Message { /// `user` left the `emoji` reaction. pub fn reacted(&self, emoji: &str, user: &str) -> bool { - self.reactions.iter().any(|r| r.emoji == emoji && r.users.iter().any(|u| u == user)) + self.reacted_as(emoji, user, None) + } + + /// [`Self::reacted`], with `legacy_user` counting as `user` too ([`is_user`]). + pub fn reacted_as(&self, emoji: &str, user: &str, legacy_user: Option<&str>) -> bool { + self.reactions.iter().any(|r| r.emoji == emoji && r.users.iter().any(|u| is_user(u, user, legacy_user))) } /// Add `user`'s `emoji` reaction, or take it back (`on`: None toggles). True when it changed. pub fn react(&mut self, emoji: &str, user: &str, on: Option) -> bool { - let want = on.unwrap_or(!self.reacted(emoji, user)); - if want == self.reacted(emoji, user) { + self.react_as(emoji, user, on, None) + } + + /// [`Self::react`], with `legacy_user` counting as `user` too: a reaction left under the old + /// default name is the renamed person's, so taking it back removes it rather than adding theirs. + pub fn react_as(&mut self, emoji: &str, user: &str, on: Option, legacy_user: Option<&str>) -> bool { + let has = self.reacted_as(emoji, user, legacy_user); + let want = on.unwrap_or(!has); + if want == has { return false; } match self.reactions.iter().position(|r| r.emoji == emoji) { @@ -62,7 +81,7 @@ impl Message { } Some(i) => { if let Some(r) = self.reactions.get_mut(i) { - r.users.retain(|u| u != user); + r.users.retain(|u| !is_user(u, user, legacy_user)); if r.users.is_empty() { self.reactions.remove(i); } @@ -155,8 +174,7 @@ impl Comment { /// claimed this way after the local person's real name replaces the placeholder, without /// rewriting the messages in the file. pub fn involves_as(&self, user: &str, legacy_user: Option<&str>) -> bool { - self.messages() - .any(|m| m.author == user || legacy_user.is_some_and(|legacy| m.author == legacy) || !mention_ranges(&m.text, &[user]).is_empty()) + self.messages().any(|m| is_user(&m.author, user, legacy_user) || !mention_ranges(&m.text, &[user]).is_empty()) } /// The thread has something `user` hasn't read. @@ -167,7 +185,7 @@ impl Comment { /// [`Self::is_unread`], with `legacy_user` counting as `user` too: a thread read under the old /// default name stays read when that person is renamed. pub fn is_unread_as(&self, user: &str, legacy_user: Option<&str>) -> bool { - self.read_by.as_ref().is_some_and(|r| !r.iter().any(|u| u == user || legacy_user.is_some_and(|legacy| u == legacy))) + self.read_by.as_ref().is_some_and(|r| !r.iter().any(|u| is_user(u, user, legacy_user))) } /// Mark the thread read or unread for `user`. True when it changed. @@ -195,7 +213,7 @@ impl Comment { self.read_by = Some(self.participants().into_iter().map(String::from).collect()); } if let Some(r) = self.read_by.as_mut() { - r.retain(|u| u != user && !legacy_user.is_some_and(|legacy| u == legacy)); + r.retain(|u| !is_user(u, user, legacy_user)); } true } diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 8fd842033..0c0ea6f00 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -299,12 +299,6 @@ pub fn legacy_default(s: &Session, who: &str) -> Option<&'static str> { (s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR) } -/// Whether a message signed `author` is `who`'s, counting `legacy_user` ([`legacy_default`]) as -/// `who`: a placeholder-authored message the local person wrote before their real name arrived. -pub fn written_by(author: &str, who: &str, legacy_user: Option<&str>) -> bool { - author == who || legacy_user == Some(author) -} - /// A new message by `who`, marked as an agent's when the command runs for one. fn new_message(s: &Session, who: String, text: String) -> Message { Message { agent: s.agent.is_some(), ..Message::new(who, text, now_secs()) } @@ -320,7 +314,7 @@ fn text(cmd: &str, p: &Value) -> crate::Result { /// Refuse to change someone else's message. fn own(cmd: &str, m: &Message, who: &str, legacy_user: Option<&str>, what: &str) -> crate::Result<()> { - if written_by(&m.author, who, legacy_user) { + if figcraft_doc::is_user(&m.author, who, legacy_user) { return Ok(()); } Err(bad(cmd, format!("only {} can {what} (acting as {who}; pass `author` to act as someone else)", m.author))) @@ -764,15 +758,16 @@ pub fn specs() -> Vec { return Err(bad("comment.react", "`emoji` must be one emoji")); } let who = author(s, p); + let legacy = legacy_default(s, &who); let c = s.doc()?.comment(id).ok_or_else(|| bad("comment.react", "no comment"))?; let i = message_index("comment.react", c, p)?; - let has = c.message(i).is_some_and(|m| m.reacted(&emoji, &who)); + let has = c.message(i).is_some_and(|m| m.reacted_as(&emoji, &who, legacy)); let on = boolean(p, "on").unwrap_or(!has); // Already so: no edit (and no undo step). if on != has && let Some(m) = s.doc_mut()?.comment_mut(id).and_then(|c| c.message_mut(i)) { - m.react(&emoji, &who, Some(on)); + m.react_as(&emoji, &who, Some(on), legacy); } Ok(json!({"on": on})) } diff --git a/crates/engine/src/comments_polish_tests.rs b/crates/engine/src/comments_polish_tests.rs index a9c50b05b..f0385629c 100644 --- a/crates/engine/src/comments_polish_tests.rs +++ b/crates/engine/src/comments_polish_tests.rs @@ -135,6 +135,27 @@ fn default_authored_comments_stay_mine_after_the_person_is_renamed() { assert!(s.doc().unwrap().comment(c).is_none()); } +#[test] +fn a_reaction_left_as_you_follows_the_rename() { + let mut s = Session::new(); + let c = add(&mut s, 0.0, 0.0, "First", "You"); + s.execute("comment.react", &json!({"id": c, "emoji": "👍"})).unwrap(); + s.execute("comment.react", &json!({"id": c, "emoji": "👍", "author": "Sam"})).unwrap(); + s.execute("pref.userName", &json!({"name": "Ada"})).unwrap(); + let users = |s: &Session| comment(s, c).first.reactions.iter().flat_map(|r| r.users.clone()).collect::>(); + + // Turning it on again is no change: the person already reacted, under the old name. + assert_eq!(s.execute("comment.react", &json!({"id": c, "emoji": "👍", "on": true})).unwrap()["on"], true); + assert_eq!(users(&s), ["You", "Sam"], "no second reaction from the new name"); + // A toggle takes theirs back, leaving everyone else's. + assert_eq!(s.execute("comment.react", &json!({"id": c, "emoji": "👍"})).unwrap()["on"], false); + assert_eq!(users(&s), ["Sam"]); + // Another named person has no claim on the old default's reaction. + s.execute("comment.react", &json!({"id": c, "emoji": "🎉", "author": "You"})).unwrap(); + s.execute("comment.react", &json!({"id": c, "emoji": "🎉", "author": "Sam"})).unwrap(); + assert!(comment(&s, c).first.reacted("🎉", "You"), "Sam's toggle adds Sam's, not removes You's"); +} + #[test] fn reactions_toggle_per_person() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/canvas/comments.rs b/crates/ui-egui/src/canvas/comments.rs index 151b47382..9aa8f25c3 100644 --- a/crates/ui-egui/src/canvas/comments.rs +++ b/crates/ui-egui/src/canvas/comments.rs @@ -238,7 +238,7 @@ impl Pin { author: c.first.author.clone(), resolved: c.resolved, unread: c.is_unread_as(me, legacy_user), - mine: cc::written_by(&c.first.author, me, legacy_user), + mine: figcraft_doc::is_user(&c.first.author, me, legacy_user), at, } } @@ -696,7 +696,7 @@ fn message( let when = if m.edited > 0 { trf("{when} · edited", &[("when", &ago(m.created))]) } else { ago(m.created) }; ui.label(egui::RichText::new(when).font(regular(11.0)).color(t.text_tertiary)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if cc::written_by(&m.author, cx.me, cx.legacy_user) { + if figcraft_doc::is_user(&m.author, cx.me, cx.legacy_user) { let menu = Id::unique(("comment_msg_more_menu", id, i)); let more = hover_button( ui, @@ -727,7 +727,7 @@ fn message( crate::right::menu_popup(&react).id(menu).show(|ui| { ui.horizontal(|ui| { for e in REACTIONS { - let on = m.reacted(e, cx.me); + let on = m.reacted_as(e, cx.me, cx.legacy_user); let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click()); if on || resp.hovered() { ui.painter().rect_filled(r, CornerRadius::same(6), if on { t.selected_row } else { t.hover }); @@ -773,7 +773,7 @@ fn message( ui.add_space(indent); ui.spacing_mut().item_spacing = vec2(4.0, 4.0); for r in &m.reactions { - let on = r.users.iter().any(|u| u == cx.me); + let on = r.users.iter().any(|u| figcraft_doc::is_user(u, cx.me, cx.legacy_user)); // The emoji a size up from its count. let mut job = LayoutJob::default(); job.append( @@ -956,7 +956,7 @@ pub fn thread(app: &mut FigApp, ctx: &egui::Context, id: u64, anchor: Pos2, boun act = Some(Act::Run("comment.resolve", json!({"id": id, "resolved": !c.resolved}))); ui.close(); } - if cc::written_by(&c.first.author, &me, legacy) && crate::right::menu_item(ui, tr("Delete thread"), "") { + if figcraft_doc::is_user(&c.first.author, &me, legacy) && crate::right::menu_item(ui, tr("Delete thread"), "") { act = Some(Act::Run("comment.delete", json!({"id": id}))); ui.close(); } From 6e222454a584d7ca3ad5afb52883a1e9280810b9 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 1 Dec 2026 19:56:32 +0700 Subject: [PATCH 06/13] Comments: say why the You alias grants no new access --- crates/engine/src/cmd/comment.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 0c0ea6f00..5c5b6b943 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -295,6 +295,11 @@ fn author(s: &Session, p: &Value) -> String { /// The old default author, when it still identifies `who` in this session: `who` is the local /// person (not an AI agent acting for them) whose real name has replaced `You`. Other people and /// agents get no claim on placeholder-authored messages. +/// +/// A file can't say which `You` wrote a message: every person signed so before names came from the +/// account. This grants nothing new: clearing Preferences ▸ Your name makes anyone `You` again, and +/// `author` lets any caller act as any name, so authorship is attribution, not access control. +/// Without the alias, a renamed person would lose their own old messages and reactions. pub fn legacy_default(s: &Session, who: &str) -> Option<&'static str> { (s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR) } From 12a2fe5432fe94ed06f1f67cac3a30909f30210b Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 1 Dec 2026 20:29:13 +0700 Subject: [PATCH 07/13] docs: a --control run keeps a saved name; it only skips the account lookup --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 89c7ee031..86333a7aa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1620,7 +1620,8 @@ Preferences is unchanged. It is set once per connection, so no command needs `au param still wins. In the app, comments act as the name from Preferences (`pref.userName {name}`, default "You"); only a message's author can edit or delete it. A first desktop start takes the operating system account's name into that preference instead of "You"; the CLI, this server and a -`--control` run keep the default, so what an agent signs is the same on every machine. `@Name` in a +`--control` run never ask the account (a `--control` run keeps a name already saved in Preferences), +so what an agent signs is the same on every machine. `@Name` in a message mentions someone (`comment.people` lists the names used in the file: everyone who wrote or reacted, and every name a message @mentions, once each in any case; and, as `you`, who is acting). From 147dc2511cb98d67446d699df34ad69f6e4798c0 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 1 Dec 2026 20:56:52 +0700 Subject: [PATCH 08/13] Comments: work out the You alias once per list and prompt, not per thread --- crates/engine/src/cmd/comment.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 5c5b6b943..cb7816a62 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -926,10 +926,9 @@ pub fn specs() -> Vec { let who = author(s, p); let people = doc.comment_people(); let people = mentionable(&people, &who); - let list: Vec = listed("comment.list", s, p, &who, &people)? - .into_iter() - .map(|c| comment_json(doc, c, &who, &people, legacy_default(s, &who))) - .collect(); + let legacy = legacy_default(s, &who); + let list: Vec = + listed("comment.list", s, p, &who, &people)?.into_iter().map(|c| comment_json(doc, c, &who, &people, legacy)).collect(); Ok(json!({"comments": list})) } ), @@ -978,6 +977,7 @@ pub fn specs() -> Vec { Some(_) => return Err(bad("comment.prompt", "`ids` must be an array of comment ids")), }; let who = acting_name(s); + let legacy = legacy_default(s, &who); let selected: Vec<&Comment> = if let Some(ids) = ids { let mut out = Vec::with_capacity(ids.len()); for id in ids { @@ -986,14 +986,14 @@ pub fn specs() -> Vec { out } else { let search = string(p, "query").unwrap_or_default(); - query(doc, &Query { page, frame: None, filter, sort, text: &search }, &who, legacy_default(s, &who)) + query(doc, &Query { page, frame: None, filter, sort, text: &search }, &who, legacy) }; let count = selected.len(); let (text, truncated) = prompt_text(doc, path.as_deref(), &selected); let people = doc.comment_people(); let people = mentionable(&people, &who); let comments: Vec = - selected.iter().take(PROMPT_MAX_THREADS).map(|c| comment_brief_json(doc, c, &who, &people, legacy_default(s, &who))).collect(); + selected.iter().take(PROMPT_MAX_THREADS).map(|c| comment_brief_json(doc, c, &who, &people, legacy)).collect(); Ok(json!({"count": count, "truncated": truncated, "text": text, "comments": comments})) } ), From aa203f023df89a81b04a172b479904004aa91996 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Tue, 1 Dec 2026 21:17:51 +0700 Subject: [PATCH 09/13] Comments: a thread that @mentions You stays Mine after the rename --- crates/doc/src/comments.rs | 9 +++++---- crates/engine/src/comments_polish_tests.rs | 9 +++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/comments.rs b/crates/doc/src/comments.rs index 59c28111c..6808e0aa7 100644 --- a/crates/doc/src/comments.rs +++ b/crates/doc/src/comments.rs @@ -170,11 +170,12 @@ impl Comment { self.involves_as(user, None) } - /// [`Self::involves`], with `legacy_user` counting as `user` too. An old default author can be - /// claimed this way after the local person's real name replaces the placeholder, without - /// rewriting the messages in the file. + /// [`Self::involves`], with `legacy_user` counting as `user` too, as an author and as an + /// @mention. An old default author can be claimed this way after the local person's real name + /// replaces the placeholder, without rewriting the messages in the file. pub fn involves_as(&self, user: &str, legacy_user: Option<&str>) -> bool { - self.messages().any(|m| is_user(&m.author, user, legacy_user) || !mention_ranges(&m.text, &[user]).is_empty()) + let names: Vec<&str> = std::iter::once(user).chain(legacy_user).collect(); + self.messages().any(|m| is_user(&m.author, user, legacy_user) || !mention_ranges(&m.text, &names).is_empty()) } /// The thread has something `user` hasn't read. diff --git a/crates/engine/src/comments_polish_tests.rs b/crates/engine/src/comments_polish_tests.rs index f0385629c..0ae9e4789 100644 --- a/crates/engine/src/comments_polish_tests.rs +++ b/crates/engine/src/comments_polish_tests.rs @@ -156,6 +156,15 @@ fn a_reaction_left_as_you_follows_the_rename() { assert!(comment(&s, c).first.reacted("🎉", "You"), "Sam's toggle adds Sam's, not removes You's"); } +#[test] +fn a_thread_mentioning_you_stays_mine_after_the_rename() { + let mut s = Session::new(); + let c = add(&mut s, 0.0, 0.0, "Can @You check this?", "Sam"); + s.execute("pref.userName", &json!({"name": "Ada"})).unwrap(); + assert_eq!(list(&mut s, json!({"page": "all", "filter": "mine"})), [c], "@You still names the renamed person"); + assert!(list(&mut s, json!({"page": "all", "filter": "mine", "author": "Lee"})).is_empty(), "nobody else is @You"); +} + #[test] fn reactions_toggle_per_person() { let mut s = Session::new(); From 9413d575095f56426d1b1525df1f277c60937772 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 4 Dec 2026 09:03:18 +0700 Subject: [PATCH 10/13] Comments: only a profile that signed as You owns You messages; @You reports you after the rename --- apps/figcraft/src/main.rs | 4 +++ crates/engine/src/cmd/comment.rs | 29 ++++++++++++---------- crates/engine/src/cmd/view.rs | 2 ++ crates/engine/src/comments_polish_tests.rs | 29 ++++++++++++++++++++++ crates/engine/src/prefs.rs | 6 +++++ docs/mcp.md | 4 ++- 6 files changed, 60 insertions(+), 14 deletions(-) diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index 907b0247e..033e80cde 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -426,6 +426,10 @@ fn main() -> eframe::Result { // an agent started it. Nothing has been commented or drawn yet, so the name is in place before // anything can be signed. use_system_user_name(&mut session, asks_for_user_name(svc.has_settings(), port.is_some()), user_name::system); + if svc.prefs.is_none() { + // A first start never signed anything as "You", so no "You" message is this profile's. + session.prefs.was_default_name = false; + } figcraft_engine::keymap::set_custom(&session.prefs.shortcuts); let first_run = svc.prefs.is_none() && args.join.is_none(); // Initialise the interface language before opening files, as startup can now show an import diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index cb7816a62..5981d8967 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -293,15 +293,16 @@ fn author(s: &Session, p: &Value) -> String { } /// The old default author, when it still identifies `who` in this session: `who` is the local -/// person (not an AI agent acting for them) whose real name has replaced `You`. Other people and +/// person (not an AI agent acting for them) whose profile signed as `You` until a real name +/// replaced it (`Prefs::was_default_name`). A profile that always had a name, other people and /// agents get no claim on placeholder-authored messages. /// /// A file can't say which `You` wrote a message: every person signed so before names came from the -/// account. This grants nothing new: clearing Preferences ▸ Your name makes anyone `You` again, and -/// `author` lets any caller act as any name, so authorship is attribution, not access control. -/// Without the alias, a renamed person would lose their own old messages and reactions. +/// account. The renamed person keeps exactly what they had as `You`, no more: `author` lets any +/// caller act as any name, so authorship is attribution, not access control. Without the alias, a +/// renamed person would lose their own old messages and reactions. pub fn legacy_default(s: &Session, who: &str) -> Option<&'static str> { - (s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR) + (s.prefs.was_default_name && s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR) } /// A new message by `who`, marked as an agent's when the command runs for one. @@ -391,13 +392,15 @@ fn listed<'s>(cmd: &str, s: &'s Session, p: &Value, who: &str, people: &[&str]) .collect()) } -/// Add the names `text` @mentions to `named` as `{name, known, you}`, each once. -fn push_mentions(named: &mut Vec, text: &str, people: &[&str], user: &str) { +/// Add the names `text` @mentions to `named` as `{name, known, you}`, each once; `you` counts +/// `legacy_user` ([`legacy_default`]) as `user` too. +fn push_mentions(named: &mut Vec, text: &str, people: &[&str], user: &str, legacy_user: Option<&str>) { // `known` and `you` follow from the name, so the name alone tells a repeat. let mut seen: std::collections::BTreeSet = named.iter().filter_map(|v| v.get("name")?.as_str().map(str::to_string)).collect(); for (name, known) in mentioned(text, people) { if seen.insert(name.to_string()) { - named.push(json!({"name": name, "known": known, "you": known && name.eq_ignore_ascii_case(user)})); + let you = [Some(user), legacy_user].into_iter().flatten().any(|u| name.eq_ignore_ascii_case(u)); + named.push(json!({"name": name, "known": known, "you": known && you})); } } } @@ -428,9 +431,9 @@ fn people_and_mentioned(doc: &Document, you: &str) -> Vec { /// A message as JSON, with the names it @mentions: `{name, known, you}` each, resolved against /// `people` (`mentionable`); `known: false` is a name nobody in the file has. -fn message_json(m: &Message, people: &[&str], user: &str) -> Value { +fn message_json(m: &Message, people: &[&str], user: &str, legacy_user: Option<&str>) -> Value { let mut named: Vec = Vec::new(); - push_mentions(&mut named, &m.text, people, user); + push_mentions(&mut named, &m.text, people, user, legacy_user); json!({ "author": m.author, "agent": m.agent, "text": m.text, "created": m.created, "edited": m.edited, "reactions": m.reactions.iter().map(|r| json!({"emoji": r.emoji, "users": r.users})).collect::>(), @@ -443,13 +446,13 @@ fn message_json(m: &Message, people: &[&str], user: &str) -> Value { pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str], legacy_user: Option<&str>) -> Value { let (x, y) = c.position(doc); let frame = frame_of(doc, c); - let mut v = message_json(&c.first, people, user); + let mut v = message_json(&c.first, people, user, legacy_user); let extra = json!({ "id": c.id, "page": c.page, "pageName": doc.node(c.page).map(|n| n.name.as_str()), "x": x, "y": y, "anchor": c.anchor, "frame": frame, "frameName": frame.and_then(|f| doc.node(f)).map(|n| n.name.as_str()), "resolved": c.resolved, "unread": c.is_unread_as(user, legacy_user), "link": link(c.id), - "replies": c.replies.iter().map(|m| message_json(m, people, user)).collect::>(), + "replies": c.replies.iter().map(|m| message_json(m, people, user, legacy_user)).collect::>(), }); if let (Some(m), Value::Object(e)) = (v.as_object_mut(), extra) { m.extend(e); @@ -465,7 +468,7 @@ fn comment_brief_json(doc: &Document, c: &Comment, user: &str, people: &[&str], // The names the whole thread @mentions, as `comment.list` reports them per message. let mut named = Vec::new(); for m in c.messages() { - push_mentions(&mut named, &m.text, people, user); + push_mentions(&mut named, &m.text, people, user, legacy_user); if named.len() >= PROMPT_MAX_MENTIONS { break; } diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 9c18c5da6..1b43fd6ee 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -572,7 +572,9 @@ pub fn specs() -> Vec { |s, p| { let name = req_string("pref.userName", p, "name")?; let name: String = name.trim().chars().filter(|c| !c.is_control()).take(crate::live::MAX_NAME).collect(); + let was_default = super::comment::user_name(s) == super::comment::DEFAULT_AUTHOR; s.prefs.user_name = if name.is_empty() { super::comment::DEFAULT_AUTHOR.into() } else { name }; + s.prefs.was_default_name |= was_default && s.prefs.user_name != super::comment::DEFAULT_AUTHOR; s.live_rename(); Ok(json!({"name": s.prefs.user_name})) } diff --git a/crates/engine/src/comments_polish_tests.rs b/crates/engine/src/comments_polish_tests.rs index 0ae9e4789..ddba58688 100644 --- a/crates/engine/src/comments_polish_tests.rs +++ b/crates/engine/src/comments_polish_tests.rs @@ -165,6 +165,35 @@ fn a_thread_mentioning_you_stays_mine_after_the_rename() { assert!(list(&mut s, json!({"page": "all", "filter": "mine", "author": "Lee"})).is_empty(), "nobody else is @You"); } +#[test] +fn an_at_you_mention_reports_the_renamed_person_as_you() { + let mut s = Session::new(); + let c = add(&mut s, 0.0, 0.0, "Can @You check this?", "You"); + s.execute("pref.userName", &json!({"name": "Ada"})).unwrap(); + let listed = s.execute("comment.list", &json!({"page": "all"})).unwrap(); + assert_eq!(listed["comments"][0]["mentions"][0]["you"], true, "comment.list: @You is the renamed person"); + let prompt = s.execute("comment.prompt", &json!({"ids": [c]})).unwrap(); + assert_eq!(prompt["comments"][0]["mentions"][0]["you"], true, "comment.prompt: the same"); + let other = s.execute("comment.list", &json!({"page": "all", "author": "Lee"})).unwrap(); + assert_eq!(other["comments"][0]["mentions"][0]["you"], false, "nobody else is @You"); +} + +#[test] +fn a_profile_that_always_had_a_name_has_no_claim_on_you_messages() { + // Opening a shared file whose comments were signed with the default: someone who never signed + // as "You" in this profile cannot edit, delete or count them as theirs. + let mut s = Session::new(); + let c = add(&mut s, 0.0, 0.0, "Can @You check this?", "You"); + s.prefs.user_name = "Grace".into(); + assert!(!s.prefs.was_default_name); + assert!(list(&mut s, json!({"page": "all", "filter": "mine"})).is_empty(), "not Mine"); + assert!(s.execute("comment.edit", &json!({"id": c, "text": "No"})).is_err()); + assert!(s.execute("comment.delete", &json!({"id": c})).is_err()); + // A later rename keeps it that way: the profile still never was the default. + s.execute("pref.userName", &json!({"name": "Grace Hopper"})).unwrap(); + assert!(s.execute("comment.edit", &json!({"id": c, "text": "No"})).is_err()); +} + #[test] fn reactions_toggle_per_person() { let mut s = Session::new(); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 61c55e965..5ef2511be 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -59,6 +59,11 @@ pub struct Prefs { pub language: String, /// The name comments are signed with (and whose comments count as yours). pub user_name: String, + /// This profile signed as the default name ("You") before a real name replaced it, so messages, + /// reads and reactions under the default are its own (`cmd::comment::legacy_default`). Off for a + /// profile that never was the default, so a shared file's "You" messages aren't someone else's to + /// edit. + pub was_default_name: bool, /// Reduce motion: the interface's own animations are off (the system's setting turns them off /// too). Prototype transitions still play. pub reduce_motion: bool, @@ -203,6 +208,7 @@ impl Default for Prefs { pages_height: None, language: "system".into(), user_name: cmd::comment::DEFAULT_AUTHOR.into(), + was_default_name: false, reduce_motion: false, nav_bar_auto_hide: false, ui_scale: 1.0, diff --git a/docs/mcp.md b/docs/mcp.md index a602e6f9d..a11399e54 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1702,7 +1702,9 @@ param still wins. In the app, comments act as the name from Preferences (`pref.u default "You"); only a message's author can edit or delete it. A first desktop start takes the operating system account's name into that preference instead of "You"; the CLI, this server and a `--control` run never ask the account (a `--control` run keeps a name already saved in Preferences), -so what an agent signs is the same on every machine. `@Name` in a +so what an agent signs is the same on every machine. Messages, reads, reactions and `@You` mentions from before a profile +took a real name stay that person's; a profile that always had a name, and an agent, get no claim +on a "You" message. `@Name` in a message mentions someone (`comment.people` lists the names used in the file: everyone who wrote or reacted, and every name a message @mentions, once each in any case; and, as `you`, who is acting). From 468553ef56c47e86b58e1a9033beeb5b65ccc915 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 4 Dec 2026 09:21:39 +0700 Subject: [PATCH 11/13] Comments: the You alias only keeps old threads in Mine; changes go by the signed name --- apps/figcraft/src/main.rs | 14 ++-- crates/doc/src/comments.rs | 55 ++++------------ crates/engine/src/cmd/comment.rs | 51 +++++++-------- crates/engine/src/comments_polish_tests.rs | 74 +++++++--------------- crates/ui-egui/src/canvas/comments.rs | 19 +++--- docs/mcp.md | 7 +- 6 files changed, 78 insertions(+), 142 deletions(-) diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index 033e80cde..92eeca711 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -985,8 +985,9 @@ mod system_name_tests { #[test] fn comments_saved_as_you_stay_mine_after_the_system_name_arrives() { - // The upgrade regression: a file written under the old default keeps its authors on disk, - // and the renamed person keeps edit, delete, Mine and read state for those threads. + // The upgrade regression: a file written under the old default keeps its authors on disk, and + // its threads stay in the renamed person's Mine. Nothing more: a file can't say which "You" + // wrote a message, so changing one still takes the name it was signed with. let dir = std::env::temp_dir().join(format!("figcraft-system-name-upgrade-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); @@ -1004,15 +1005,12 @@ mod system_name_tests { let saved = s.doc().unwrap().comment(c).unwrap().clone(); assert_eq!(saved.first.author, DEFAULT, "opening the file does not rewrite its author"); assert_eq!(saved.replies[0].author, DEFAULT, "nor its replies"); - assert!(!saved.is_unread_as("Ada Lovelace", Some(DEFAULT)), "read under You stays read"); let mine = s.execute("comment.list", &json!({"page": "all", "filter": "mine"})).unwrap(); assert!(mine["comments"].as_array().unwrap().iter().any(|comment| comment["id"] == c), "the old thread is Mine"); - assert!(s.execute("comment.edit", &json!({"id": c, "text": "Not yours", "author": "Sam"})).is_err()); - s.execute("comment.edit", &json!({"id": c, "text": "Updated"})).unwrap(); - s.execute("comment.edit", &json!({"id": c, "reply": 0, "text": "Updated reply"})).unwrap(); - s.execute("comment.delete", &json!({"id": c, "reply": 0})).unwrap(); - s.execute("comment.delete", &json!({"id": c})).unwrap(); + assert!(s.execute("comment.edit", &json!({"id": c, "text": "Updated"})).is_err()); + assert!(s.execute("comment.delete", &json!({"id": c})).is_err()); + s.execute("comment.edit", &json!({"id": c, "text": "Updated", "author": DEFAULT})).unwrap(); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/doc/src/comments.rs b/crates/doc/src/comments.rs index 6808e0aa7..9c6d43522 100644 --- a/crates/doc/src/comments.rs +++ b/crates/doc/src/comments.rs @@ -6,9 +6,10 @@ use serde::{Deserialize, Serialize}; use crate::{Document, NodeId}; -/// Whether `name` (a message's author, a reader, a reactor) is `user`, counting `legacy_user` as -/// `user` too: the old default name the local person wrote, read and reacted under before their -/// real name replaced it. +/// Whether `name` (a message's author or an @mentioned name) is `user`, counting `legacy_user` as +/// `user` too: the old default name the local person may have written under before their real name +/// replaced it. For views only (Mine): a file can't say which "You" wrote a message, so the alias +/// never grants a change. pub fn is_user(name: &str, user: &str, legacy_user: Option<&str>) -> bool { name == user || legacy_user == Some(name) } @@ -52,25 +53,13 @@ impl Message { /// `user` left the `emoji` reaction. pub fn reacted(&self, emoji: &str, user: &str) -> bool { - self.reacted_as(emoji, user, None) - } - - /// [`Self::reacted`], with `legacy_user` counting as `user` too ([`is_user`]). - pub fn reacted_as(&self, emoji: &str, user: &str, legacy_user: Option<&str>) -> bool { - self.reactions.iter().any(|r| r.emoji == emoji && r.users.iter().any(|u| is_user(u, user, legacy_user))) + self.reactions.iter().any(|r| r.emoji == emoji && r.users.iter().any(|u| u == user)) } /// Add `user`'s `emoji` reaction, or take it back (`on`: None toggles). True when it changed. pub fn react(&mut self, emoji: &str, user: &str, on: Option) -> bool { - self.react_as(emoji, user, on, None) - } - - /// [`Self::react`], with `legacy_user` counting as `user` too: a reaction left under the old - /// default name is the renamed person's, so taking it back removes it rather than adding theirs. - pub fn react_as(&mut self, emoji: &str, user: &str, on: Option, legacy_user: Option<&str>) -> bool { - let has = self.reacted_as(emoji, user, legacy_user); - let want = on.unwrap_or(!has); - if want == has { + let want = on.unwrap_or(!self.reacted(emoji, user)); + if want == self.reacted(emoji, user) { return false; } match self.reactions.iter().position(|r| r.emoji == emoji) { @@ -81,7 +70,7 @@ impl Message { } Some(i) => { if let Some(r) = self.reactions.get_mut(i) { - r.users.retain(|u| !is_user(u, user, legacy_user)); + r.users.retain(|u| u != user); if r.users.is_empty() { self.reactions.remove(i); } @@ -170,9 +159,8 @@ impl Comment { self.involves_as(user, None) } - /// [`Self::involves`], with `legacy_user` counting as `user` too, as an author and as an - /// @mention. An old default author can be claimed this way after the local person's real name - /// replaces the placeholder, without rewriting the messages in the file. + /// [`Self::involves`], with `legacy_user` counting as `user` too ([`is_user`]), as an author and + /// as an @mention. pub fn involves_as(&self, user: &str, legacy_user: Option<&str>) -> bool { let names: Vec<&str> = std::iter::once(user).chain(legacy_user).collect(); self.messages().any(|m| is_user(&m.author, user, legacy_user) || !mention_ranges(&m.text, &names).is_empty()) @@ -180,31 +168,16 @@ impl Comment { /// The thread has something `user` hasn't read. pub fn is_unread(&self, user: &str) -> bool { - self.is_unread_as(user, None) - } - - /// [`Self::is_unread`], with `legacy_user` counting as `user` too: a thread read under the old - /// default name stays read when that person is renamed. - pub fn is_unread_as(&self, user: &str, legacy_user: Option<&str>) -> bool { - self.read_by.as_ref().is_some_and(|r| !r.iter().any(|u| is_user(u, user, legacy_user))) + self.read_by.as_ref().is_some_and(|r| !r.iter().any(|u| u == user)) } /// Mark the thread read or unread for `user`. True when it changed. pub fn set_read(&mut self, user: &str, read: bool) -> bool { - self.set_read_as(user, read, None) - } - - /// [`Self::set_read`], with `legacy_user` counting as `user` too. Marking the renamed person - /// unread drops the old default name from the readers; marking them read needs no write when - /// the old default name already recorded that they had read it. - pub fn set_read_as(&mut self, user: &str, read: bool, legacy_user: Option<&str>) -> bool { - if read != self.is_unread_as(user, legacy_user) { + if read != self.is_unread(user) { return false; } if read { - if let Some(r) = self.read_by.as_mut() - && !r.iter().any(|u| u == user) - { + if let Some(r) = self.read_by.as_mut() { r.push(user.to_string()); } return true; @@ -214,7 +187,7 @@ impl Comment { self.read_by = Some(self.participants().into_iter().map(String::from).collect()); } if let Some(r) = self.read_by.as_mut() { - r.retain(|u| !is_user(u, user, legacy_user)); + r.retain(|u| u != user); } true } diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 5981d8967..1f8bf548b 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -3,8 +3,9 @@ //! Messages are addressed by `reply` (an index into the replies; omitted: the thread's first //! message). `author` is who is acting (default: the AI agent the command runs for, else the name //! from Preferences, `pref.userName`): only a message's author edits or deletes it, and only the -//! thread's author deletes the thread. A message signed with the old default `You` remains the -//! local person's after their real name arrives, without rewriting the file's author string. +//! thread's author deletes the thread. A thread signed or @mentioning the old default `You` still +//! shows as Mine after the local person's real name arrives; editing or deleting it takes the name +//! it was signed with, since a file can't say which `You` wrote it. use std::fmt::Write as _; @@ -106,7 +107,7 @@ impl Filter { Filter::Open => !c.resolved, Filter::Resolved => c.resolved, Filter::Mine => c.involves_as(user, legacy_user), - Filter::Unread => c.is_unread_as(user, legacy_user), + Filter::Unread => c.is_unread(user), } } } @@ -292,15 +293,13 @@ fn author(s: &Session, p: &Value) -> String { string(p, "author").map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).unwrap_or_else(|| acting_name(s)) } -/// The old default author, when it still identifies `who` in this session: `who` is the local -/// person (not an AI agent acting for them) whose profile signed as `You` until a real name -/// replaced it (`Prefs::was_default_name`). A profile that always had a name, other people and -/// agents get no claim on placeholder-authored messages. +/// The old default author, when it may still name `who` in this session: `who` is the local person +/// (not an AI agent acting for them) whose profile signed as `You` until a real name replaced it +/// (`Prefs::was_default_name`). A profile that always had a name, other people and agents get none. /// -/// A file can't say which `You` wrote a message: every person signed so before names came from the -/// account. The renamed person keeps exactly what they had as `You`, no more: `author` lets any -/// caller act as any name, so authorship is attribution, not access control. Without the alias, a -/// renamed person would lose their own old messages and reactions. +/// Views only: threads signed or @mentioning `You` stay in Mine, and `@You` reports `you`. A file +/// can't say which `You` wrote a message, so the alias never lets anyone edit, delete, react or +/// mark read under it; those act under the name they are given. pub fn legacy_default(s: &Session, who: &str) -> Option<&'static str> { (s.prefs.was_default_name && s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR) } @@ -319,8 +318,8 @@ fn text(cmd: &str, p: &Value) -> crate::Result { } /// Refuse to change someone else's message. -fn own(cmd: &str, m: &Message, who: &str, legacy_user: Option<&str>, what: &str) -> crate::Result<()> { - if figcraft_doc::is_user(&m.author, who, legacy_user) { +fn own(cmd: &str, m: &Message, who: &str, what: &str) -> crate::Result<()> { + if m.author == who { return Ok(()); } Err(bad(cmd, format!("only {} can {what} (acting as {who}; pass `author` to act as someone else)", m.author))) @@ -451,7 +450,7 @@ pub fn comment_json(doc: &Document, c: &Comment, user: &str, people: &[&str], le "id": c.id, "page": c.page, "pageName": doc.node(c.page).map(|n| n.name.as_str()), "x": x, "y": y, "anchor": c.anchor, "frame": frame, "frameName": frame.and_then(|f| doc.node(f)).map(|n| n.name.as_str()), - "resolved": c.resolved, "unread": c.is_unread_as(user, legacy_user), "link": link(c.id), + "resolved": c.resolved, "unread": c.is_unread(user), "link": link(c.id), "replies": c.replies.iter().map(|m| message_json(m, people, user, legacy_user)).collect::>(), }); if let (Some(m), Value::Object(e)) = (v.as_object_mut(), extra) { @@ -484,7 +483,7 @@ fn comment_brief_json(doc: &Document, c: &Comment, user: &str, people: &[&str], "pageName": doc.node(c.page).map(|n| clip_chars(&n.name, 80)), "x": x, "y": y, "anchor": c.anchor, "frame": frame, "frameName": frame.and_then(|f| doc.node(f)).map(|n| clip_chars(&n.name, 80)), - "resolved": c.resolved, "unread": c.is_unread_as(user, legacy_user), "link": link(c.id), + "resolved": c.resolved, "unread": c.is_unread(user), "link": link(c.id), "author": clip_chars(&c.first.author, 80), "agent": c.first.agent, "preview": clip_chars(&c.first.text, 160), "replies": c.replies.len(), "mentions": named, }) @@ -525,10 +524,10 @@ fn reveal(s: &mut Session, id: u64, how: &str) -> crate::Result<()> { fn open(s: &mut Session, id: u64, how: &str, who: &str) -> crate::Result { let legacy = legacy_default(s, who); reveal(s, id, how)?; - if s.doc()?.comment(id).is_some_and(|c| c.is_unread_as(who, legacy)) + if s.doc()?.comment(id).is_some_and(|c| c.is_unread(who)) && let Some(c) = s.doc_mut()?.comment_mut(id) { - c.set_read_as(who, true, legacy); + c.set_read(who, true); } s.request_ui("comment.open", json!({"id": id})); let doc = s.doc()?; @@ -739,12 +738,11 @@ pub fn specs() -> Vec { let id = req_comment("comment.edit", s, p)?; let t = text("comment.edit", p)?; let who = author(s, p); - let legacy = legacy_default(s, &who); let (i, same) = { let c = s.doc()?.comment(id).ok_or_else(|| bad("comment.edit", "no comment"))?; let i = message_index("comment.edit", c, p)?; let m = c.message(i).ok_or_else(|| bad("comment.edit", "no message"))?; - own("comment.edit", m, &who, legacy, "edit this message")?; + own("comment.edit", m, &who, "edit this message")?; (i, m.text == t) }; // The same text is no edit (and no undo step). @@ -766,16 +764,15 @@ pub fn specs() -> Vec { return Err(bad("comment.react", "`emoji` must be one emoji")); } let who = author(s, p); - let legacy = legacy_default(s, &who); let c = s.doc()?.comment(id).ok_or_else(|| bad("comment.react", "no comment"))?; let i = message_index("comment.react", c, p)?; - let has = c.message(i).is_some_and(|m| m.reacted_as(&emoji, &who, legacy)); + let has = c.message(i).is_some_and(|m| m.reacted(&emoji, &who)); let on = boolean(p, "on").unwrap_or(!has); // Already so: no edit (and no undo step). if on != has && let Some(m) = s.doc_mut()?.comment_mut(id).and_then(|c| c.message_mut(i)) { - m.react_as(&emoji, &who, Some(on), legacy); + m.react(&emoji, &who, Some(on)); } Ok(json!({"on": on})) } @@ -814,17 +811,16 @@ pub fn specs() -> Vec { |s, p| { let id = req_comment("comment.delete", s, p)?; let who = author(s, p); - let legacy = legacy_default(s, &who); let doc = s.doc_mut()?; let c = doc.comment_mut(id).ok_or_else(|| bad("comment.delete", "no comment"))?; match message_index("comment.delete", c, p)? { 0 => { - own("comment.delete", &c.first, &who, legacy, "delete this thread")?; + own("comment.delete", &c.first, &who, "delete this thread")?; doc.comments.retain(|c| c.id != id); } i => { let m = c.message(i).ok_or_else(|| bad("comment.delete", "no message"))?; - own("comment.delete", m, &who, legacy, "delete this reply")?; + own("comment.delete", m, &who, "delete this reply")?; c.replies.remove(i - 1); } } @@ -840,15 +836,14 @@ pub fn specs() -> Vec { let read = boolean(p, "read").unwrap_or(true); let who = author(s, p); let only = if get(p, "id").is_some() || get(p, "link").is_some() { Some(req_comment("comment.markRead", s, p)?) } else { None }; - let legacy = legacy_default(s, &who); - let wants = |c: &Comment| only.is_none_or(|i| c.id == i) && c.is_unread_as(&who, legacy) == read; + let wants = |c: &Comment| only.is_none_or(|i| c.id == i) && c.is_unread(&who) == read; // The document is left alone when nothing changes (no unsaved changes for nothing). if !s.doc()?.comments.iter().any(wants) { return Ok(json!({"changed": 0})); } let mut n = 0; for c in s.doc_mut()?.comments.iter_mut().filter(|c| only.is_none_or(|i| c.id == i)) { - n += usize::from(c.set_read_as(&who, read, legacy)); + n += usize::from(c.set_read(&who, read)); } Ok(json!({"changed": n})) } diff --git a/crates/engine/src/comments_polish_tests.rs b/crates/engine/src/comments_polish_tests.rs index ddba58688..1d0080f35 100644 --- a/crates/engine/src/comments_polish_tests.rs +++ b/crates/engine/src/comments_polish_tests.rs @@ -90,70 +90,42 @@ fn only_authors_edit_and_delete_their_messages() { assert_eq!(comment(&s, c).replies[0].text, "Second!"); s.execute("comment.delete", &json!({"id": c, "reply": 0, "author": "Sam"})).unwrap(); assert!(comment(&s, c).replies.is_empty()); - // Your name from Preferences signs and owns your comments, including ones the old default - // signed before the real name arrived. + // Your name from Preferences signs and owns your comments. s.execute("pref.userName", &json!({"name": " Ada "})).unwrap(); let d = s.execute("comment.add", &json!({"x": 0, "y": 0, "text": "Mine"})).unwrap()["id"].as_u64().unwrap(); assert_eq!(comment(&s, d).first.author, "Ada"); - s.execute("comment.delete", &json!({"id": c})).unwrap(); - assert!(s.doc().unwrap().comment(c).is_none()); + assert!(s.execute("comment.delete", &json!({"id": c})).is_err()); s.execute("comment.delete", &json!({"id": d})).unwrap(); s.execute("pref.userName", &json!({"name": " "})).unwrap(); assert_eq!(s.prefs.user_name, "You"); } #[test] -fn default_authored_comments_stay_mine_after_the_person_is_renamed() { - let mut s = Session::new(); - let c = add(&mut s, 0.0, 0.0, "First", "You"); - s.execute("comment.reply", &json!({"id": c, "text": "Mine too"})).unwrap(); - - // The desktop start-up hook fills in the real name; the saved message authors stay as they - // were, so ownership has to recognize the old placeholder. - s.execute("pref.userName", &json!({"name": "Ada"})).unwrap(); - let mine = list(&mut s, json!({"page": "all", "filter": "mine"})); - assert_eq!(mine, vec![c], "a legacy You thread is still Mine for the renamed person"); - assert!(!comment(&s, c).is_unread_as("Ada", Some("You")), "read under You stays read"); - - // Neither another named person nor an AI agent inherits the placeholder's messages. - assert!(s.execute("comment.edit", &json!({"id": c, "text": "No", "author": "Sam"})).is_err()); - s.agent = Some("Claude".into()); - assert!(s.execute("comment.edit", &json!({"id": c, "text": "No"})).is_err()); - s.agent = None; - - s.execute("comment.edit", &json!({"id": c, "text": "First, edited"})).unwrap(); - s.execute("comment.edit", &json!({"id": c, "reply": 0, "text": "Mine too, edited"})).unwrap(); - s.execute("comment.delete", &json!({"id": c, "reply": 0})).unwrap(); - - // Marking the renamed person unread does not resurrect the placeholder as a separate reader. - s.execute("comment.markRead", &json!({"id": c, "read": false})).unwrap(); - assert!(comment(&s, c).is_unread_as("Ada", Some("You"))); - s.execute("comment.markRead", &json!({"id": c})).unwrap(); - assert!(!comment(&s, c).is_unread_as("Ada", Some("You"))); - - s.execute("comment.delete", &json!({"id": c})).unwrap(); - assert!(s.doc().unwrap().comment(c).is_none()); -} - -#[test] -fn a_reaction_left_as_you_follows_the_rename() { +fn a_renamed_person_sees_you_threads_as_mine_but_changes_nothing_under_you() { + // A shared file's "You" messages may be anyone's: the file can't say which "You" wrote them. + // Renaming from the default (the normal `pref.userName` path) keeps them in Mine, and nothing + // more: edits, deletes, reactions and read marks act under the real name only. let mut s = Session::new(); let c = add(&mut s, 0.0, 0.0, "First", "You"); + s.execute("comment.reply", &json!({"id": c, "text": "A reply"})).unwrap(); s.execute("comment.react", &json!({"id": c, "emoji": "👍"})).unwrap(); - s.execute("comment.react", &json!({"id": c, "emoji": "👍", "author": "Sam"})).unwrap(); s.execute("pref.userName", &json!({"name": "Ada"})).unwrap(); - let users = |s: &Session| comment(s, c).first.reactions.iter().flat_map(|r| r.users.clone()).collect::>(); + assert!(s.prefs.was_default_name); + assert_eq!(list(&mut s, json!({"page": "all", "filter": "mine"})), vec![c], "still Mine"); - // Turning it on again is no change: the person already reacted, under the old name. - assert_eq!(s.execute("comment.react", &json!({"id": c, "emoji": "👍", "on": true})).unwrap()["on"], true); - assert_eq!(users(&s), ["You", "Sam"], "no second reaction from the new name"); - // A toggle takes theirs back, leaving everyone else's. - assert_eq!(s.execute("comment.react", &json!({"id": c, "emoji": "👍"})).unwrap()["on"], false); - assert_eq!(users(&s), ["Sam"]); - // Another named person has no claim on the old default's reaction. - s.execute("comment.react", &json!({"id": c, "emoji": "🎉", "author": "You"})).unwrap(); - s.execute("comment.react", &json!({"id": c, "emoji": "🎉", "author": "Sam"})).unwrap(); - assert!(comment(&s, c).first.reacted("🎉", "You"), "Sam's toggle adds Sam's, not removes You's"); + assert!(s.execute("comment.edit", &json!({"id": c, "text": "No"})).is_err()); + assert!(s.execute("comment.edit", &json!({"id": c, "reply": 0, "text": "No"})).is_err()); + assert!(s.execute("comment.delete", &json!({"id": c, "reply": 0})).is_err()); + assert!(s.execute("comment.delete", &json!({"id": c})).is_err()); + assert_eq!(comment(&s, c).first.text, "First"); + + // A toggle adds Ada's reaction and leaves the one signed "You". + assert_eq!(s.execute("comment.react", &json!({"id": c, "emoji": "👍"})).unwrap()["on"], true); + assert_eq!(comment(&s, c).first.reactions[0].users, ["You", "Ada"]); + // Marking unread for Ada leaves the "You" reader alone. + s.execute("comment.markRead", &json!({"id": c})).unwrap(); + s.execute("comment.markRead", &json!({"id": c, "read": false})).unwrap(); + assert!(!comment(&s, c).is_unread("You")); } #[test] @@ -181,7 +153,7 @@ fn an_at_you_mention_reports_the_renamed_person_as_you() { #[test] fn a_profile_that_always_had_a_name_has_no_claim_on_you_messages() { // Opening a shared file whose comments were signed with the default: someone who never signed - // as "You" in this profile cannot edit, delete or count them as theirs. + // as "You" in this profile doesn't see them as theirs (nor edits or deletes them). let mut s = Session::new(); let c = add(&mut s, 0.0, 0.0, "Can @You check this?", "You"); s.prefs.user_name = "Grace".into(); diff --git a/crates/ui-egui/src/canvas/comments.rs b/crates/ui-egui/src/canvas/comments.rs index 9aa8f25c3..527de58d0 100644 --- a/crates/ui-egui/src/canvas/comments.rs +++ b/crates/ui-egui/src/canvas/comments.rs @@ -237,7 +237,7 @@ impl Pin { id: c.id, author: c.first.author.clone(), resolved: c.resolved, - unread: c.is_unread_as(me, legacy_user), + unread: c.is_unread(me), mine: figcraft_doc::is_user(&c.first.author, me, legacy_user), at, } @@ -666,8 +666,6 @@ struct ThreadCtx<'a> { c: &'a Comment, me: &'a str, people: &'a [String], - /// The old default author that still counts as `me` after a real name arrives. - legacy_user: Option<&'a str>, } /// One message: author, time, its buttons on hover (react; edit and delete when it's yours), the @@ -696,7 +694,7 @@ fn message( let when = if m.edited > 0 { trf("{when} · edited", &[("when", &ago(m.created))]) } else { ago(m.created) }; ui.label(egui::RichText::new(when).font(regular(11.0)).color(t.text_tertiary)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if figcraft_doc::is_user(&m.author, cx.me, cx.legacy_user) { + if m.author == cx.me { let menu = Id::unique(("comment_msg_more_menu", id, i)); let more = hover_button( ui, @@ -727,7 +725,7 @@ fn message( crate::right::menu_popup(&react).id(menu).show(|ui| { ui.horizontal(|ui| { for e in REACTIONS { - let on = m.reacted_as(e, cx.me, cx.legacy_user); + let on = m.reacted(e, cx.me); let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click()); if on || resp.hovered() { ui.painter().rect_filled(r, CornerRadius::same(6), if on { t.selected_row } else { t.hover }); @@ -773,7 +771,7 @@ fn message( ui.add_space(indent); ui.spacing_mut().item_spacing = vec2(4.0, 4.0); for r in &m.reactions { - let on = r.users.iter().any(|u| figcraft_doc::is_user(u, cx.me, cx.legacy_user)); + let on = r.users.iter().any(|u| u == cx.me); // The emoji a size up from its count. let mut job = LayoutJob::default(); job.append( @@ -919,15 +917,14 @@ pub fn thread(app: &mut FigApp, ctx: &egui::Context, id: u64, anchor: Pos2, boun }; let people = ds.doc.comment_people(); let me = me(app); - let legacy = cc::legacy_default(&app.session, &me); - if c.is_unread_as(&me, legacy) && !previewing { + if c.is_unread(&me) && !previewing { app.run("comment.markRead", json!({"id": id})); } let mut reply = std::mem::take(&mut app.ui.comments.reply); let mut editing = app.ui.comments.editing.take().filter(|e| e.0 == id && c.message(e.1).is_some()); let mut pick = std::mem::take(&mut app.ui.comments.mention); let mut act: Option = None; - let cx = ThreadCtx { c: &c, me: &me, people: &people, legacy_user: legacy }; + let cx = ThreadCtx { c: &c, me: &me, people: &people }; egui::Area::new(Id::unique("comment_thread")).order(egui::Order::Foreground).fixed_pos(popover_pos(anchor, bounds)).show(ctx, |ui| { popover_frame(&t).show(ui, |ui| { ui.set_width(POPOVER_W - 24.0); @@ -956,7 +953,7 @@ pub fn thread(app: &mut FigApp, ctx: &egui::Context, id: u64, anchor: Pos2, boun act = Some(Act::Run("comment.resolve", json!({"id": id, "resolved": !c.resolved}))); ui.close(); } - if figcraft_doc::is_user(&c.first.author, &me, legacy) && crate::right::menu_item(ui, tr("Delete thread"), "") { + if c.first.author == me && crate::right::menu_item(ui, tr("Delete thread"), "") { act = Some(Act::Run("comment.delete", json!({"id": id}))); ui.close(); } @@ -1190,7 +1187,7 @@ pub fn panel(app: &mut FigApp, ui: &mut Ui) { } else if resp.hovered() { ui.painter().rect_filled(r, CornerRadius::ZERO, t.hover); } - let unread = c.is_unread_as(&me, legacy); + let unread = c.is_unread(&me); if unread { ui.painter().circle_filled(pos2(r.min.x + 8.0, r.min.y + 22.0), 3.5, ACCENT); } diff --git a/docs/mcp.md b/docs/mcp.md index a11399e54..299727ac9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1702,9 +1702,10 @@ param still wins. In the app, comments act as the name from Preferences (`pref.u default "You"); only a message's author can edit or delete it. A first desktop start takes the operating system account's name into that preference instead of "You"; the CLI, this server and a `--control` run never ask the account (a `--control` run keeps a name already saved in Preferences), -so what an agent signs is the same on every machine. Messages, reads, reactions and `@You` mentions from before a profile -took a real name stay that person's; a profile that always had a name, and an agent, get no claim -on a "You" message. `@Name` in a +so what an agent signs is the same on every machine. Threads signed or `@You`-mentioned from before a profile took a real +name stay in that person's Mine filter (and `@You` reports `you`); a file can't say which "You" +wrote a message, so editing, deleting, reacting and read marks still go by the name a message was +signed with. `@Name` in a message mentions someone (`comment.people` lists the names used in the file: everyone who wrote or reacted, and every name a message @mentions, once each in any case; and, as `you`, who is acting). From 37ce1f24ab59c1ccba5b01002d3723a9c57b6e47 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 4 Dec 2026 11:12:23 +0700 Subject: [PATCH 12/13] Comments: say that the You alias lets old pins drag, which comment.move never restricted --- crates/engine/src/cmd/comment.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/comment.rs b/crates/engine/src/cmd/comment.rs index 1f8bf548b..f75b8b3c8 100644 --- a/crates/engine/src/cmd/comment.rs +++ b/crates/engine/src/cmd/comment.rs @@ -297,9 +297,10 @@ fn author(s: &Session, p: &Value) -> String { /// (not an AI agent acting for them) whose profile signed as `You` until a real name replaced it /// (`Prefs::was_default_name`). A profile that always had a name, other people and agents get none. /// -/// Views only: threads signed or @mentioning `You` stay in Mine, and `@You` reports `you`. A file -/// can't say which `You` wrote a message, so the alias never lets anyone edit, delete, react or -/// mark read under it; those act under the name they are given. +/// Views only: threads signed or @mentioning `You` stay in Mine (so their pins drag like the +/// person's own, which grants nothing: `comment.move` checks no author), and `@You` reports `you`. +/// A file can't say which `You` wrote a message, so the alias never lets anyone edit, delete, react +/// or mark read under it; those act under the name they are given. pub fn legacy_default(s: &Session, who: &str) -> Option<&'static str> { (s.prefs.was_default_name && s.agent.is_none() && who == user_name(s) && who != DEFAULT_AUTHOR).then_some(DEFAULT_AUTHOR) } From 728c2cb940d6c9c318775b09eec2b9c0069e12f8 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Fri, 4 Dec 2026 11:23:09 +0700 Subject: [PATCH 13/13] Your name: read id -F's answer while it runs, capped, so a long one can't stall it --- apps/figcraft/src/user_name.rs | 56 ++++++++++++++++++---------- apps/figcraft/src/user_name_tests.rs | 18 +++++++++ 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/apps/figcraft/src/user_name.rs b/apps/figcraft/src/user_name.rs index 5b72ff134..e23002ac0 100644 --- a/apps/figcraft/src/user_name.rs +++ b/apps/figcraft/src/user_name.rs @@ -255,37 +255,53 @@ fn wait_with_deadline(mut child: std::process::Child, deadline: std::time::Insta } } +/// The most of a lookup's output read: a name is far shorter, so an answer this long is not one. +#[cfg(any(target_os = "macos", all(test, unix)))] +const MAX_ANSWER_BYTES: u64 = 4096; + /// The system's own `id -F`, run as `/usr/bin/id`: a GNU coreutils `id` earlier in `PATH`, easy to -/// have on a Mac with coreutils installed, has no `-F` and would only print an error. Stopped and -/// waited for if it outlives [`LOOKUP_TIMEOUT`]: a directory service that never answers would -/// otherwise leave an `id` process waiting on every start. The name it prints is far below what a -/// pipe holds, so reading its output after it finished cannot block. +/// have on a Mac with coreutils installed, has no `-F` and would only print an error. #[cfg(target_os = "macos")] fn lookup_id_dash_f() -> Option { + let mut command = std::process::Command::new("/usr/bin/id"); + command.arg("-F"); + answer_of(command, "id -F") +} + +/// What `command` prints, trimmed, when it succeeds within [`LOOKUP_TIMEOUT`] with a non-empty +/// answer of at most [`MAX_ANSWER_BYTES`]; `None` otherwise (`what` names it in the log). Its +/// output is read while it runs, not after: a child whose answer fills the pipe would otherwise +/// stall writing it until the deadline. The read stops at the cap and closes the pipe, so a child +/// that keeps writing is ended by the broken pipe; one that never answers is stopped at the +/// deadline ([`wait_with_deadline`]), which closes the pipe and ends the read too. +#[cfg(any(target_os = "macos", all(test, unix)))] +fn answer_of(mut command: std::process::Command, what: &str) -> Option { use std::io::Read; - use std::process::{Command, Stdio}; - let mut child = match Command::new("/usr/bin/id").arg("-F").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() { + use std::process::Stdio; + let mut child = match command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn() { Ok(child) => child, Err(e) => { - log::debug!("user name: id -F: {e}"); + log::debug!("user name: {what}: {e}"); return None; } }; - let (out, err) = (child.stdout.take(), child.stderr.take()); - let status = wait_with_deadline(child, std::time::Instant::now() + LOOKUP_TIMEOUT, "id -F")?; - let mut text = String::new(); - if status.success() { - if let Some(mut pipe) = out { - let _ = pipe.read_to_string(&mut text); - } - } else { - if let Some(mut pipe) = err { - let _ = pipe.read_to_string(&mut text); - } - log::debug!("user name: id -F: {}", text.trim()); + let deadline = std::time::Instant::now() + LOOKUP_TIMEOUT; + let out = child.stdout.take()?; + let reader = std::thread::spawn(move || { + let mut answer = Vec::new(); + out.take(MAX_ANSWER_BYTES + 1).read_to_end(&mut answer).map(|_| answer) + }); + let status = wait_with_deadline(child, deadline, what)?; + let Ok(Ok(answer)) = reader.join() else { return None }; + if !status.success() { + log::debug!("user name: {what} failed: {status}"); return None; } - Some(text.trim().to_owned()).filter(|n| !n.is_empty()) + if answer.len() as u64 > MAX_ANSWER_BYTES { + log::debug!("user name: {what} answered with more than {MAX_ANSWER_BYTES} bytes"); + return None; + } + Some(String::from_utf8(answer).ok()?.trim().to_owned()).filter(|n| !n.is_empty()) } /// `word` with its first letter upper case (`ada` → `Ada`). diff --git a/apps/figcraft/src/user_name_tests.rs b/apps/figcraft/src/user_name_tests.rs index 18ae4d9a1..e680831f8 100644 --- a/apps/figcraft/src/user_name_tests.rs +++ b/apps/figcraft/src/user_name_tests.rs @@ -29,6 +29,24 @@ fn a_child_that_never_answers_is_stopped_at_its_deadline() { assert!(!still_there, "the child is reaped, not left running or waiting"); } +/// The output half of the macOS lookup: an answer is read while the child runs, so one too long +/// for a pipe neither stalls the child until the deadline nor passes for a name, while an ordinary +/// one is the name. +#[cfg(unix)] +#[test] +fn an_oversized_answer_is_no_name_and_does_not_wait_for_the_deadline() { + let command = |program: &str, args: &[&str]| { + let mut command = std::process::Command::new(program); + command.args(args); + command + }; + assert_eq!(answer_of(command("echo", &[" Ada Lovelace "]), "echo").as_deref(), Some("Ada Lovelace")); + // Endless output: more than the read takes and far more than a pipe holds. + let started = std::time::Instant::now(); + assert_eq!(answer_of(command("yes", &["Ada Lovelace"]), "yes"), None, "an answer past the cap is not a name"); + assert!(started.elapsed() < LOOKUP_TIMEOUT, "the capped read ends the child before the deadline: {:?}", started.elapsed()); +} + const PASSWD: &[u8] = b"# local accounts\n\ #ada:x:1000:1000:Older Ada,commented out:/home/not-ada:/bin/sh\n\ \t#ada2:x:1000:1000:Older Ada,indented comment:/home/not-ada2:/bin/sh\n\