File zone share: controller built once per mount, one notification on success, tests for the surviving mutations
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m48s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Void 2026-11-12 13:15:47 +00:00
commit cf99096d3c
4 changed files with 108 additions and 46 deletions

View file

@ -6,7 +6,11 @@ import type { ClientConfig } from '../../hooks/useClientConfig';
import { ShareState } from './shareController';
import { ShareSetView, shareEnabled, useShareEnabled } from './ShareSet';
const text = (html: string) => html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
const text = (html: string) =>
html
.replace(/<[^>]*>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
const noop = () => undefined;
const file = (name: string) => ({ name, type: 'audio/ogg' } as File);
@ -45,11 +49,16 @@ describe('the share panel, drawn', () => {
});
it('sending: progress replaces Send and Cancel, and the title is locked', () => {
const html = view({ files: [file('a'), file('b'), file('c')], phase: { kind: 'sending', done: 2 } });
const html = view({
files: [file('a'), file('b'), file('c')],
phase: { kind: 'sending', done: 2 },
});
expect(text(html)).toContain('Sending 2 of 3…');
expect(text(html)).not.toContain('Send 3 files');
expect(text(html)).not.toContain('Cancel');
expect(html).toMatch(/aria-label="Album title"[^>]*disabled|disabled[^>]*aria-label="Album title"/);
expect(html).toMatch(
/aria-label="Album title"[^>]*disabled|disabled[^>]*aria-label="Album title"/
);
});
it('the encrypted note shows above the kept pick', () => {

View file

@ -1,4 +1,4 @@
import React, { useMemo, useRef, useSyncExternalStore } from 'react';
import React, { useRef, useState, useSyncExternalStore } from 'react';
import { Text } from 'folds';
import { useQueryClient } from '@tanstack/react-query';
import { Room } from 'matrix-js-sdk';
@ -104,42 +104,46 @@ export function ShareSet({ room }: { room: Room }) {
const mx = useMatrixClient();
const queryClient = useQueryClient();
const input = useRef<HTMLInputElement>(null);
const controller: ShareController<File> = useMemo(
() =>
createShareController<File>({
roomId: room.roomId,
isEncrypted: () => room.hasEncryptionStateEvent(),
onSent: () => queryClient.invalidateQueries({ queryKey: ['albums', room.roomId] }),
run: (files, title, onFile) =>
sendShareSet(
{
send: async (content) => (await mx.sendMessage(room.roomId, content as any)).event_id,
contentOf: async (f) => {
const file = safeFile(f.file);
const mxc = await new Promise<string>((resolve, reject) => {
uploadContent(mx, file, { onSuccess: resolve, onError: reject });
});
const content = await getMsgContent(
mx,
{
file,
originalFile: f.file,
metadata: { markedAsSpoiler: false },
encInfo: undefined,
},
mxc
);
const sha256 = await hashForSend(f.file);
if (sha256) content.info = { ...content.info, [FILE_HASH_KEY]: sha256 };
return content;
},
onFile,
// Built once per mount (AlbumView keys the panel by room): the pick lives in the controller, so a
// rerender with a new client or Room object must not build another. Live values go through `live`.
const live = useRef({ mx, room, queryClient });
live.current = { mx, room, queryClient };
const [controller]: [ShareController<File>, unknown] = useState(() =>
createShareController<File>({
roomId: room.roomId,
isEncrypted: () => live.current.room.hasEncryptionStateEvent(),
onSent: () =>
live.current.queryClient.invalidateQueries({ queryKey: ['albums', room.roomId] }),
run: (files, title, onFile) =>
sendShareSet(
{
send: async (content) =>
(await live.current.mx.sendMessage(room.roomId, content as any)).event_id,
contentOf: async (f) => {
const file = safeFile(f.file);
const mxc = await new Promise<string>((resolve, reject) => {
uploadContent(live.current.mx, file, { onSuccess: resolve, onError: reject });
});
const content = await getMsgContent(
live.current.mx,
{
file,
originalFile: f.file,
metadata: { markedAsSpoiler: false },
encInfo: undefined,
},
mxc
);
const sha256 = await hashForSend(f.file);
if (sha256) content.info = { ...content.info, [FILE_HASH_KEY]: sha256 };
return content;
},
title,
files.map((file) => ({ name: file.name, mimeType: file.type, file }))
),
}),
[mx, room, queryClient]
onFile,
},
title,
files.map((file) => ({ name: file.name, mimeType: file.type, file }))
),
})
);
const state = useSyncExternalStore(controller.subscribe, controller.getState);
return (

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { ENCRYPTED_NOTE, Picked, ShareDeps, createShareController } from './shareController';
import { Picked, ShareDeps, createShareController } from './shareController';
import { ShareResult } from './shareSet';
const file = (name: string): Picked => ({ name, type: 'audio/ogg' });
@ -190,13 +190,58 @@ describe('progress and results', () => {
});
});
describe('what a send leaves behind', () => {
it('keeps the title when some files failed, so the retry has the same name', async () => {
const { c, h } = make();
c.pick([file('a'), file('b')]);
c.setTitle('Take 4');
const p = c.send();
h.release({ albumId: '$r', sent: 1, failed: ['b'], failedAt: [1] });
await p;
expect(c.getState().title).toBe('Take 4');
});
it('tells the room list only after the send settled, and not when it threw', async () => {
const { c, h, sentTo } = make();
c.pick([file('a')]);
const p = c.send();
expect(sentTo).toEqual([]);
h.release(ok(1));
await p;
expect(sentTo).toEqual(['!zone:x']);
const bad = make();
bad.c.pick([file('a')]);
const q = bad.c.send();
bad.h.fail(new Error('boom'));
await q;
expect(bad.sentTo).toEqual([]);
});
it('a success lands in one notification: the pick is never empty while still sending', async () => {
const { c, h } = make();
c.pick([file('a')]);
const p = c.send();
const seen: string[] = [];
c.subscribe(() => {
const st = c.getState();
seen.push(`${st.files.length}:${st.phase.kind}`);
});
h.release(ok(1));
await p;
expect(seen).toEqual(['0:done']);
});
});
describe('an encrypted room', () => {
it('says so, sends nothing and keeps the pick', async () => {
const { c, h } = make({ isEncrypted: () => true });
c.pick([file('a')]);
await c.send();
expect(ENCRYPTED_NOTE).toBe('Not shared: this room is encrypted.');
expect(c.getState().phase).toEqual({ kind: 'done', text: ENCRYPTED_NOTE });
expect(c.getState().phase).toEqual({
kind: 'done',
text: 'Not shared: this room is encrypted.',
});
expect(c.getState().files).toHaveLength(1);
expect(h.calls).toHaveLength(0);
});
@ -208,6 +253,9 @@ describe('an encrypted room', () => {
encrypted = true;
await c.send();
expect(h.calls).toHaveLength(0);
expect(c.getState().phase).toMatchObject({ kind: 'done', text: ENCRYPTED_NOTE });
expect(c.getState().phase).toMatchObject({
kind: 'done',
text: 'Not shared: this room is encrypted.',
});
});
});

View file

@ -58,9 +58,10 @@ export const createShareController = <F extends Picked>(deps: ShareDeps<F>) => {
});
deps.onSent?.();
const left = remainingAfter(files, res);
if (left.length === 0) clear();
else set({ files: left });
set({ phase: { kind: 'done', text: resultNote(res) } });
const phase: SharePhase = { kind: 'done', text: resultNote(res) };
// One notification: no state is ever drawn with the pick emptied and the send still running.
if (left.length === 0) set({ files: [], title: '', epoch: state.epoch + 1, phase });
else set({ files: left, phase });
} catch (e: any) {
set({ phase: { kind: 'done', text: `Could not share: ${e?.message ?? 'send failed'}` } });
} finally {