M4-22: Files, images and voice messages on the desktop¶
Status: ready | Depends on: M4-20, M3-05 | Milestone: M4
Goal¶
After this ticket the desktop app sends, shows, downloads and plays files: attaching by the attachment button, drag and drop and paste creates one upload entry per file in the outbox before the message (12 3: session with size, SHA-256 and declared type, parts with Content-Digest, completion, resumption from the confirmed parts after an abort), with progress and the states of 12 2 ("being checked", "Upload failed", "blocked"); messages show attachments with name, size and state, images as thumbnails loaded only from the server (downloadThumbnail, SEC-OUT-2), opening and saving through downloadFile with the Repr-Digest check, and media players through short-lived file tickets; voice messages are recorded as AAC-LC in .m4a (package record, client.voice.bitrate, at most voice_max_duration_ms from InstanceLimits), sent as kind = voice, played at speed 1, 1.5 and 2, and show the transcript when file.updated reports it, with "Transcribe" where the server allows it; the local file cache keeps bytes with the metadata rows of local_store and is cleaned with the database; and the session column gets the "Files" section. 409 file_not_ready is shown as "being checked" and retried on file.updated. Why: files are part of the conversation with agents (screenshots, logs, voice), and every byte a client shows must come from the server's checked copy, never from a URL an agent wrote (T-AI-06).
Read first¶
docs/PLAN.md: section 3; section 10 (Red team: T-AI-06; rows M4-15, M4-20, M4-22, M4-34).docs/spec/01-product.md: 3.4 "Files and voice", 5.1 D1 (session column "Files"), 6.6, 8 (labels of attachments and players), 14.docs/spec/12-files.md: 1, 2 "States of a file", 3 "Upload flow" (3.1, 3.2, 3.4, 3.6, 3.7;presignedmode 3.3 only to know the client followsmode), 6.2 (names), 7.1 and 7.3 (images and thumbnails), 8 "Voice messages", 9 "Download" (9.1 to 9.3, tickets,Repr-Digest), 10 "Attaching and agent invocation", 15, 18 (configuration values the client meets).docs/spec/15-client-architecture.md: 6.1 (files,message_attachments,file_cache), 6.3 (cleanup), 7.5 (uploads before messages), 13 "Voice recording", 14 "File upload".docs/spec/04-sync-protocol.md: 2.2 rule 5 (redactedfile.updated), 13.2.docs/spec/19-security.md: SEC-OUT-2, SEC-T13;docs/security/threat-model.mdT-AI-06.docs/api/openapi.yaml:createUpload(UploadCreate,UploadSession),uploadPart,completeUpload,getUpload,abortUpload,getFile,downloadFile,downloadThumbnail,createFileTicket,getTranscript,requestTranscription,deleteFile,getInstance(InstanceLimits); problem codesfile_not_ready,file_blocked,payload_too_large,unsupported_media_type,file_not_attachable,voice_format_unsupported,voice_too_long,transcription_unavailable.docs/DECISIONS.md: D-W-100, D-W-114, D-W-115; section 10.- Briefs:
docs/briefs/M4-20-thread-view.md(composer, history, session column),docs/briefs/M4-15-sync-outbox.md(dependency rule, executors),docs/briefs/M4-12-local-store.md(file_cache,FileCacheDao, cleanup),docs/briefs/M4-14-sync-catch-up.md(FileCacheEraser),docs/briefs/M4-07-core-components.md(DsMarkdownattachment resolver),docs/briefs/M4-17-fake-server.md(handler registry); for the server sidedocs/briefs/M3-03-upload-sessions.md,docs/briefs/M3-05-file-download.md,docs/briefs/M3-06-image-metadata-thumbnails.md,docs/briefs/M3-09-voice-transcript.md.
This ticket touches no API operation, no table of chapter 03, no action, no event and no configuration key.
Fixed requirements that apply¶
Owner's fixed build rules (apply verbatim):
- No MVP. New from scratch and directly in the final state; stages are only the order.
- Strictly modular: clear module and service boundaries, dependencies only through defined interfaces, no cross access.
- Documentation in code: every public module, class, function and interface with a docstring/doc comment (purpose, parameters, return value, errors, example where useful); comments explain the why, not the what. API documentation is generated from code (OpenAPI from the routes, dartdoc, Python API docs in MkDocs).
- Documentation in the repo: README per module/service, ADR for every architecture decision, CHANGELOG per release, keep the documentation site current. A change without matching documentation is not done.
- Quality gates (SonarQube, linters, type checking, security scanners, test coverage) block the merge.
Rules for every brief:
- Test first: write the failing test, run it and keep the red output for the report, then make it green, then clean up.
- No en dash and no em dash in any file you write; the
text-rulespre-commit hook rejects them, and the ARB test of M4-06 rejects them in interface texts. Use a hyphen or rephrase. - White label: examples and test data use
example.comand the people Alex, Sam and Robin; no company, host or personal names, no paths under a home directory. Interface texts come frompackages/l10n, never as literals in widgets. - Limits only through named keys or the server:
file_max_upload_bytes,message_max_attachmentsandvoice_max_duration_msfromInstanceLimits(D-W-115),client.voice.bitratefromAppConfig, part size and count from the upload session; no literal in code. - Specification first: 15 7.5 and 15 14 say a message waits until its files are
complete, while 12 3.4 allows attaching once the upload session is completed and holds the agent invocation until the files are final (12 10). This ticket follows 12 3.4 (Design note 2) and aligns 15 7.5 and 15 14 in the same change.
Product requirements implemented here:
- Every file is its own outbox entry before the message that attaches it; the client checks size against
file_max_upload_bytesand the count againstmessage_max_attachmentsbefore sending (15 14, 04 13.2). - Upload as 12 3: session with name, size, SHA-256 and declared type (
Idempotency-Key), parts withContent-Digest, resume from the partsgetUploadconfirms after an abort, completion; a message attaches the file after completion (12 3.4). - States shown as 12 2 names them: "being checked", "Upload failed", "blocked";
409 file_not_readywaits forfile.updated(06 5). - Previews only from server files: thumbnails through
downloadThumbnail, never from a URL in the content; the local preview before sending shows the local file (15 14, SEC-OUT-2). - Downloads through the server only; the client checks
Repr-Digest; media playback through file tickets (12 9). - Voice: AAC-LC in MP4 (
.m4a), mono,client.voice.bitrate, at mostvoice_max_duration_ms; microphone permission at the first use; playback at 1, 1.5 and 2; the transcript appears whenfile.updatedreports it (15 13, 12 8). - The file cache lives with the encrypted database's metadata and is deleted on removal, revocation and cleanup (15 6.3, 04 8.3).
Scope¶
Create in apps/client/lib/:
files/upload_executor.dart(outbox executorupload, Design note 1),files/upload_planner.dart(hashing in a background isolate, part plan from the session),files/attach_controller.dart(button, drag and drop, paste),files/attachment_tile.dartandfiles/attachment_mapping.dart(states of 12 2 to the view),files/image_preview.dart(thumbnails from the server, full view),files/download_service.dart(download withRepr-Digest, save dialog, open),files/file_cache.dart(bytes on disk under the instance's cache folder, theFileCacheEraserof M4-14),files/ticket_player.dart(audio and video through tickets).voice/recorder.dart(portVoiceRecorderwith therecordimplementation, Design note 4),voice/voice_button.dart,voice/voice_player.dart(speeds),voice/transcript_view.dart.session_column/files_section.dart.- The resolver for internal file references of
DsMarkdown(M4-07 Design note 2) on the files of the message. - Fake server handlers through the registry of M4-17 for the upload, download, ticket, transcript and file operations of Read first, with the states of 12 2 and the faults
abort after part n,file_not_ready,blocked. - Tests under
test/files/andtest/voice/, goldens undertest/goldens/files/, integration tests underintegration_test/(Tests). - macOS:
NSMicrophoneUsageDescriptioninInfo.plistand the audio input entitlement; Windows: nothing beyond the package. - ARB keys for every new text in
packages/l10n.
Change:
apps/client/pubspec.yaml(record,cryptofor SHA-256,file_selectorordesktop_droponly ifmake licensesandmake osvstay green,just_audioor the player the license gate allows, Design note 4),apps/client/README.md(files and voice).docs/spec/15-client-architecture.md7.5 and 14 (attach after the session is completed, 12 3.4).docs/DECISIONS.mdsection 10: rowsD-M4-22-<n>; rootCHANGELOG.mdunder[Unreleased].
Out of scope¶
- Images as JPEG from a photo library (mobile, M5); share sheet and Share Target (M5, later on Windows).
- Video posters and transcoding (12 8.3 "later").
- File text extraction and search (M3-15, M4-23).
- Files from agents arrive like any attachment; nothing agent-specific here.
Boundaries¶
- Work in a dedicated git worktree on the branch
feat/M4-22-files-desktop; one writer per worktree. - Conventional Commits with the package or component as scope (for example
feat(client): ...,feat(sync-engine): ...,build(gates): ...,docs(spec): ...) and a DCO sign-off on every commit (git commit -s); squash into meaningful commits before the merge (docs/quality/push-discipline.md). - Never push to
main, never tag and never create remote repositories; the only remote steps are the branch push and the pull request ofAGENTS.md. Never publish a Dart package (publish_to: nonein everypubspec.yaml). - Do not modify files outside the scope above, except the CHANGELOG, README and
docs/DECISIONS.mdentries named in this brief. - Follow the host rules supplied by the launcher (ports, machine rules).
- Tests bind only
127.0.0.1with port 0 and make no network call; fakes replace the server unless a section below names a container. Temporary directories only viamktemp -d(DartDirectory.systemTemp.createTemp, pytesttmp_path), removed at the end. Stop only processes you started, by PID. - Never read or print secrets. No network calls except package downloads for pinned tools and pub packages and what the gates of
make checkdo themselves. - The Flutter SDK at the version pinned in the root
pubspec.yamlmust be onPATH(and Go and Docker where a section names them); without them the gates fail by design (R-QA-02), and the ticket stops withVerdict: BLOCKED <tool> missinginstead of skipping. - Never lower a threshold, disable a gate, delete a test, raise
repo.max_file_kbor extendquality/licenses/allowed.txt; never exclude hand-written code from a lint, format, coverage or doc gate. - The product name appears only at the places of 02 "Code layout" ("Places that carry the product name"); the app shows
branding.product_namefrom the instance, never a literal. - No permission logic in the client (15 1 principle 1): controls follow server responses, snapshots and events, never an own derivation from grants.
- If the core contract (chapters 00, 03, 04, 05) or
docs/api/lacks something this ticket needs, stop withVerdict: BLOCKED <reason>instead of building a deviation (P-11). - This brief was written before milestone M1 closed (D-W-100, extended to M4 by D-W-114). Where the merged code of an earlier ticket names a package, type, function, file, provider or make target differently from this brief, follow the code and list each difference in the report; where it behaves differently from the specification, stop with
Verdict: BLOCKED <reason>.
Design notes¶
-
Upload executor.
uploadentries carry the local path, name, size and the SHA-256 computed in a background isolate when the entry is created (streamed, never the whole file in memory). Steps:createUploadwithIdempotency-Key= entry ID (retries return the same session); formode = directsend the parts thatgetUploaddoes not list as confirmed, at most two in parallel, each withContent-Digest, reading only that part from disk;presigned: PUT to the given URLs the same way; thencompleteUpload. The entry is confirmed whencompleteUploadreturned200(12 3.4), which releases the dependent message; the file row's states then followfile.updated. Progress per entry (bytes confirmed / size) is exposed for the tile.409 conflictwithreasonpart_conflictor a session infailed,abortedorexpiredfail the entry with the reason; "Send again" creates a new upload. Ruling for docs/DECISIONS.md: attach after completion, and the parallelism. -
Attaching and the message. The composer shows chips for the files being uploaded; sending creates the message entry with
depends_onon every upload entry andattachment_file_idsfilled from the sessions when they exist (the message executor reads the file IDs from its confirmed dependencies). Over the limits: the composer refuses with the reason before creating entries. -
Display and download. Attachment tiles by the states of 12 2; images with a thumbnail from
downloadThumbnail(cached in the file cache, variant per size); clicking opens the full image fromdownloadFile. A file that answers409 file_not_readyshows "being checked" and reloads onfile.updated;file_blockedshows "blocked". Downloads stream to the cache or the chosen path and compareRepr-Digestwith the received bytes; a mismatch deletes the bytes and shows an error. Audio and video usecreateFileTicketand pass the ticket URL to the player; a ticket URL is never logged and never stored. Redacted files (deleted) show the tombstone fields only. -
Voice.
VoiceRecorderport:start(),stop() -> RecordedFile,cancel(), amplitude stream; the implementation usesrecordwith AAC-LC, mono,client.voice.bitrate, into a temporary file; it stops atvoice_max_duration_ms. Permission is asked at the first use; a denied permission shows how to allow it in the system settings. Sending: upload entry plus a message withkind = voiceand exactly one attachment. Player with speed 1, 1.5 and 2 through a ticket. Transcript: shown fromfile.updated(transcript_status); "Transcribe" callsrequestTranscriptionand showstranscription_unavailableas a short text. Tests use a fake recorder; the real microphone is checked by hand once and named in the report. Choose the player package by the license gate; record the choice. -
Cache. Bytes under
<application support>/<instance id>/files/<file id>/<variant>, rows infile_cachewithlast_accessed_at; the cleaner of M4-12 returns paths thatfile_cache.dartdeletes;targetsRemovedand the wipe delete them (M4-14, M4-18). -
Rulings for docs/DECISIONS.md (
D-M4-22-<n>): attach after completion and parallel parts (note 1); hashing in an isolate and streaming (note 1); ticket handling (note 3); the player and picker packages (note 4); the cache layout (note 5).
Tests (write them first)¶
Widget and unit tests (fake API through the handlers, fake recorder, fake clock):
test/files/upload_executor_test.dart: session, parts with digests, completion; an abort after part 2 resumes with the partsgetUploaddid not confirm;part_conflictfails the entry; the message waits for its uploads and attaches their file IDs; over-limit files are refused before any entry.test/files/states_test.dart: tiles for every view of 12 2;file_not_readyshows "being checked" and reloads onfile.updated;file_blockedshows "blocked".test/files/preview_only_from_server_test.dart(SEC-OUT-2): a message whose Markdown contains an image URL and an attachment shows the thumbnail of the attachment fromdownloadThumbnailand loads nothing else (anHttpOverridesfails on any other request).test/files/download_test.dart:Repr-Digestmatch and mismatch; ticket URLs never logged.test/voice/voice_test.dart: recording stops at the limit; the message haskind = voiceand one attachment; speeds; transcript appears onfile.updated;transcription_unavailabletext.test/goldens/files/*: attachment tiles in every state, image preview, voice player with transcript; light and dark, two densities, text scaling 1 and 2,deanden.
Integration tests (integration_test/, against FakeServer):
upload_outbox_test.dart: attach two files and send offline; on reconnect the uploads run before the message; the message appears with both attachments;file_not_readyuntil the fake reportsclean.voice_test.dart: a voice message with the fake recorder is sent and played back, and its transcript appears.
Commands that must pass, from the repository root:
cd apps/client && flutter analyze --fatal-infos && flutter test --coverage- on macOS and on Windows:
make apps-platform; elsewhere it prints its SKIP line make codegen-check,make arch,make lint,make fmt-check,make coverage,make licenses,make osvmake check
Acceptance criteria¶
- Integration tests for upload in the outbox,
file_not_readyand previews only from server files (SEC-OUT-2) are green. - Uploads follow 12 3 with resumption; downloads check
Repr-Digest; media plays through tickets. - Voice messages record AAC-LC within the limit, play at three speeds and show the transcript.
- The file cache is cleaned with the database and on removal and revocation; 15 7.5 and 14 follow 12 3.4.
-
make licensesandmake osvgreen with the chosen packages; rulings recorded. -
make checkis green.
Definition of done¶
- Code and tests as specified; doc comment on every public symbol (purpose, parameters, return value, errors, example where useful); comments explain why and cite 12 or 15.
apps/client/README.md(English) as in Scope.- 15 7.5 and 14 updated; rulings of Design note 6 in
docs/DECISIONS.mdsection 10. - Root
CHANGELOG.mdentry under 'Unreleased'. - An ADR only if you take an architecture decision beyond this brief (MADR 4 as in
docs/adr/0000-template-madr-4.md, headings and text in English, next free number,make adr-index). make checkgreen.- An independent code review over the diff, then the red team gate (
docs/quality/red-team-gate.md, verdictJAorNEIN); onNEINfix with a test per finding and have the delta checked again. Record both verdicts. - Land the change as
AGENTS.md("How work lands onmain") describes: a pull request from this branch, squash-merged only when review, red team andmake check,ci-okand the review threads are green; thengit worktree remove.
Report¶
Write to {{REPORT_PATH}}:
- First line exactly
Verdict: DONEorVerdict: BLOCKED <reason>. - Commits (SHA and subject), changed files with line counts, test results with counts (the red run before the change and the green run after), the summary of
make check. - Review and red team verdicts and the findings fixed.
- Where the integration tests ran, the packages chosen for recording, playback and file picking with their licenses, and whether the real microphone was checked by hand on macOS and Windows.
- What is not proven (for example a platform test that ran only in CI, or a check done by hand).
- Follow-ups that could not be done in this scope, each with its reason, every difference to the names of this brief (D-W-100, D-W-114), and spec gaps found.
Then write {{DONE_PATH}} with exit=0 sha=<sha> or exit=1 <reason>.