mirror of
https://github.com/bulwarkmail/webmail.git
synced 2026-11-25 08:07:31 +00:00
Merge branch 'feat/desktop-offline' into feat/do-native-dialogs
# Conflicts: # components/email/email-composer.tsx
This commit is contained in:
@@ -22,6 +22,16 @@ const source = (file: string) => readFileSync(path.join(ROOT, file), 'utf8');
|
||||
const classesOf = (el: Element) => el.getAttribute('class')!.split(/\s+/).filter((c) => c !== 'bk').sort();
|
||||
|
||||
describe('plugin UI kit components', () => {
|
||||
it('starts a long LinkButton\'s lines at its icon, as a paragraph, not centred as a button would', () => {
|
||||
// The AI assistant's examples in its panel ("Decline the invitation politely and suggest next month instead").
|
||||
render(<kit.LinkButton icon="arrow-right">Decline the invitation politely and suggest next month instead</kit.LinkButton>);
|
||||
const link = screen.getByRole('button');
|
||||
expect(link.className).toMatch(/(^|\s)text-start(\s|$)/);
|
||||
// The icon stays beside the first line rather than the middle of the text.
|
||||
expect(link.className).toMatch(/(^|\s)items-start(\s|$)/);
|
||||
expect(link.querySelector('svg')!.getAttribute('class')).toContain('mt-');
|
||||
});
|
||||
|
||||
it('renders the app\'s own Button and Input', () => {
|
||||
render(<>
|
||||
<kit.Button variant="secondary" size="sm">Cancel</kit.Button>
|
||||
|
||||
@@ -32,7 +32,7 @@ describe('the schema', () => {
|
||||
'PluginsMode', 'PluginAllowlist', 'OfflineEnabled', 'AppLockRequired', 'AppLockTimeoutMinutes', 'TelemetryAllowed',
|
||||
'CrashReportsAllowed', 'QuickComposeShortcut', 'AuthServerAllowlist', 'AuthNegotiateDelegateAllowlist',
|
||||
'AutoSelectCertificateForUrls', 'KeystoreEnabled', 'KeystoreAllowedOrigins', 'BrowserSignIn', 'WipeOfflineData',
|
||||
'OpenWithEnabled', 'DeveloperToolsAvailability',
|
||||
'OpenWithEnabled', 'DeveloperToolsAvailability', 'RecentFilesInAttach',
|
||||
]);
|
||||
for (const key of POLICY_KEYS) {
|
||||
const { title, description } = POLICY_SCHEMA[key];
|
||||
@@ -56,6 +56,13 @@ describe('developer tools and Open with', () => {
|
||||
expect(resolvePolicies(layers({ forcedMachine: { OpenWithEnabled: 0 } })).OpenWithEnabled).toMatchObject({ value: false, locked: true });
|
||||
expect(resolvePolicies(layers({ forcedMachine: { OpenWithEnabled: 'maybe' } })).OpenWithEnabled).toMatchObject({ value: false, locked: true });
|
||||
});
|
||||
|
||||
it('hide recent files in the Attach menu only by force, and a value nobody can read hides them', () => {
|
||||
expect(resolvePolicies(layers({})).RecentFilesInAttach).toMatchObject({ value: true, locked: false });
|
||||
expect(resolvePolicies(layers({ recommendedMachine: { RecentFilesInAttach: 0 } })).RecentFilesInAttach).toMatchObject({ value: true, locked: false });
|
||||
expect(resolvePolicies(layers({ forcedUser: { RecentFilesInAttach: 0 } })).RecentFilesInAttach).toMatchObject({ value: false, locked: true });
|
||||
expect(resolvePolicies(layers({ forcedMachine: { RecentFilesInAttach: 'yes please' } })).RecentFilesInAttach).toMatchObject({ value: false, locked: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('precedence', () => {
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { DEFAULT_POLICY_SNAPSHOT, type PolicySnapshot } from '../policy-schema';
|
||||
import type { BulwarkDesktopBridge, DesktopRecentFilesBridge } from '../types';
|
||||
import { createElement } from 'react';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { listRecentFiles, readRecentFile, recentFilesOffered, recentWhen, shortFolder, useRecentFilesOffered } from '../recent-files';
|
||||
|
||||
describe('shortFolder', () => {
|
||||
it('keeps the drive or share and the folders nearest the file, and drops the middle', () => {
|
||||
expect(shortFolder('C:\\Users\\me\\Documents')).toBe('C:\\Users\\me\\Documents');
|
||||
expect(shortFolder('C:\\Users\\me\\AppData\\Local\\Temp\\bw-shots-gnIFSO\\Documents\\Reports'))
|
||||
.toBe('C:\\…\\Temp\\bw-shots-gnIFSO\\Documents\\Reports');
|
||||
expect(shortFolder('\\\\fileserver\\departments\\Finance\\Controlling\\2026\\Quarterly\\Board'))
|
||||
.toBe('\\\\fileserver\\departments\\…\\Quarterly\\Board');
|
||||
expect(shortFolder('/home/me/projects/customer-a/2026/contracts/signed/final')).toBe('/…/customer-a/2026/contracts/signed/final');
|
||||
// One long name: nothing to drop, the line's ellipsis does the rest.
|
||||
const long = `C:\\${'x'.repeat(60)}`;
|
||||
expect(shortFolder(long)).toBe(long);
|
||||
});
|
||||
});
|
||||
|
||||
function setBridge(recentFiles?: Partial<DesktopRecentFilesBridge>, policy: Partial<PolicySnapshot> = {}) {
|
||||
const snapshot = { ...DEFAULT_POLICY_SNAPSHOT, ...policy };
|
||||
window.bulwarkDesktop = {
|
||||
version: 1,
|
||||
platform: 'win32',
|
||||
policy: { get: () => snapshot, onChange: () => () => {} },
|
||||
...(recentFiles ? { recentFiles: recentFiles as DesktopRecentFilesBridge } : {}),
|
||||
} as BulwarkDesktopBridge;
|
||||
}
|
||||
|
||||
const off = { RecentFilesInAttach: { value: false, source: 'forced-machine', locked: true } } as Partial<PolicySnapshot>;
|
||||
|
||||
afterEach(() => {
|
||||
window.bulwarkDesktop = undefined;
|
||||
});
|
||||
|
||||
describe('whether the Attach menu lists recent files', () => {
|
||||
it('not in a browser, not under a shell without the list, not when the policy says no', () => {
|
||||
expect(recentFilesOffered()).toBe(false);
|
||||
setBridge();
|
||||
expect(recentFilesOffered()).toBe(false);
|
||||
setBridge({ list: vi.fn(), attach: vi.fn() });
|
||||
expect(recentFilesOffered()).toBe(true);
|
||||
setBridge({ list: vi.fn(), attach: vi.fn() }, off);
|
||||
expect(recentFilesOffered()).toBe(false);
|
||||
});
|
||||
|
||||
it("says no in the server's render, so the page's first render matches it", () => {
|
||||
setBridge({ list: vi.fn(), attach: vi.fn() });
|
||||
const Probe = () => createElement('span', null, useRecentFilesOffered() ? 'menu' : 'button');
|
||||
expect(renderToString(createElement(Probe))).toBe('<span>button</span>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listRecentFiles', () => {
|
||||
it('gives the files, and nothing when main says no or fails', async () => {
|
||||
const file = { id: 'a', name: 'a.pdf', folder: 'C:\\Docs', path: 'C:\\Docs\\a.pdf', usedAt: 1 };
|
||||
setBridge({ list: vi.fn(async () => ({ ok: true as const, files: [file] })) });
|
||||
expect(await listRecentFiles()).toEqual([file]);
|
||||
setBridge({ list: vi.fn(async () => ({ ok: false as const, reason: 'gesture' as const })) });
|
||||
expect(await listRecentFiles()).toEqual([]);
|
||||
setBridge({ list: vi.fn(async () => { throw new Error('gone'); }) });
|
||||
expect(await listRecentFiles()).toEqual([]);
|
||||
window.bulwarkDesktop = undefined;
|
||||
expect(await listRecentFiles()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readRecentFile', () => {
|
||||
it('turns the bytes into a File with the name main gave', async () => {
|
||||
const attach = vi.fn(async () => ({ ok: true as const, file: { name: 'Report.docx', data: new TextEncoder().encode('hello') } }));
|
||||
setBridge({ attach });
|
||||
const result = await readRecentFile('id-1');
|
||||
expect(attach).toHaveBeenCalledWith('id-1');
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.file.name).toBe('Report.docx');
|
||||
expect(await result.file.text()).toBe('hello');
|
||||
});
|
||||
|
||||
it('says what the user can act on, and keeps quiet about a lock or a policy', async () => {
|
||||
const answer = (reason: string) => {
|
||||
setBridge({ attach: vi.fn(async () => ({ ok: false, reason }) as never) });
|
||||
return readRecentFile('x');
|
||||
};
|
||||
expect(await answer('missing')).toEqual({ ok: false, reason: 'missing' });
|
||||
expect(await answer('too-large')).toEqual({ ok: false, reason: 'too-large' });
|
||||
expect(await answer('unknown')).toEqual({ ok: false, reason: 'failed' });
|
||||
expect(await answer('gesture')).toEqual({ ok: false, reason: 'failed' });
|
||||
expect(await answer('locked')).toEqual({ ok: false, reason: 'quiet' });
|
||||
expect(await answer('policy')).toEqual({ ok: false, reason: 'quiet' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('recentWhen', () => {
|
||||
const now = new Date(2026, 10, 4, 15, 0).getTime();
|
||||
it('counts minutes and hours today, calendar days this week, then weeks and months', () => {
|
||||
expect(recentWhen(now - 20_000, now, 'en')).toBe('now');
|
||||
expect(recentWhen(now - 5 * 60_000, now, 'en')).toBe('5 minutes ago');
|
||||
expect(recentWhen(now - 3 * 60 * 60_000, now, 'en')).toBe('3 hours ago');
|
||||
// Last night at 23:00, 16 hours ago: yesterday.
|
||||
expect(recentWhen(new Date(2026, 10, 3, 23, 0).getTime(), now, 'en')).toBe('yesterday');
|
||||
expect(recentWhen(new Date(2026, 10, 1, 9, 0).getTime(), now, 'en')).toBe('3 days ago');
|
||||
expect(recentWhen(now - 15 * 24 * 60 * 60_000, now, 'en')).toBe('2 weeks ago');
|
||||
expect(recentWhen(now - 70 * 24 * 60 * 60_000, now, 'en')).toBe('2 months ago');
|
||||
expect(recentWhen(now - 3 * 60 * 60_000, now, 'de')).toBe('vor 3 Stunden');
|
||||
});
|
||||
});
|
||||
@@ -82,6 +82,7 @@ export interface PolicyValues {
|
||||
WipeOfflineData: string | null;
|
||||
OpenWithEnabled: boolean;
|
||||
DeveloperToolsAvailability: number | null;
|
||||
RecentFilesInAttach: boolean;
|
||||
}
|
||||
|
||||
export type PolicyKey = keyof PolicyValues;
|
||||
@@ -466,6 +467,19 @@ export const POLICY_SCHEMA: Record<PolicyKey, PolicyDefinition> = {
|
||||
de: 'Dieselben Werte wie die gleichnamige Richtlinie von Chrome. 2: Die Entwicklertools sind aus und die Einstellung ist gesperrt. 0 oder 1 oder nicht konfiguriert: Benutzer können sie nach einer Warnung in den Einstellungen einschalten. Mit den Entwicklertools kann jeder an der Tastatur alles lesen, was die App enthält, auch E-Mails und Passwörter im Speicher.',
|
||||
},
|
||||
},
|
||||
RecentFilesInAttach: {
|
||||
category: 'privacy',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
onInvalid: false,
|
||||
forcedOnly: true,
|
||||
sample: true,
|
||||
title: { en: 'Show recent files in the Attach menu', de: 'Zuletzt verwendete Dateien im Menü „Anfügen“ anzeigen' },
|
||||
description: {
|
||||
en: 'When enabled or not configured, the Attach button in a new message lists the files the user opened recently, as the operating system records them, so one click attaches one. The list is read when the menu opens and stays on the device. When disabled, the list is gone and the app refuses to read it. Attaching through the file dialog is not affected.',
|
||||
de: 'Wenn aktiviert oder nicht konfiguriert, listet die Schaltfläche „Anfügen“ in einer neuen Nachricht die Dateien auf, die der Benutzer zuletzt geöffnet hat, so wie das Betriebssystem sie erfasst. Ein Klick fügt eine davon an. Die Liste wird beim Öffnen des Menüs gelesen und bleibt auf dem Gerät. Wenn deaktiviert, fehlt die Liste und die App lehnt es ab, sie zu lesen. Das Anfügen über den Dateidialog ist nicht betroffen.',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const POLICY_KEYS = Object.keys(POLICY_SCHEMA) as PolicyKey[];
|
||||
@@ -916,6 +930,7 @@ const PAGE_POLICY_KEYS: readonly PolicyKey[] = [
|
||||
'AppLockRequired',
|
||||
'AppLockTimeoutMinutes',
|
||||
'CrashReportsAllowed',
|
||||
'RecentFilesInAttach',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -965,6 +980,7 @@ export const POLICY_CONSUMERS: Record<PolicyKey, PolicyConsumer> = {
|
||||
BrowserSignIn: { repo: 'shell', file: 'src/main/features/browser-sign-in.ts' },
|
||||
OpenWithEnabled: { repo: 'shell', file: 'src/main/features/os-default-app.ts' },
|
||||
DeveloperToolsAvailability: { repo: 'shell', file: 'src/main/features/dev-tools.ts' },
|
||||
RecentFilesInAttach: { repo: 'shell', file: 'src/main/features/os-recent.ts' },
|
||||
};
|
||||
|
||||
/** The part the embedded server enforces. Sent to it by message. */
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Recent files in the composer's Attach menu, in the desktop app only. The shell reads the
|
||||
* OS's list when the menu opens and hands over what the menu shows; attaching sends back an
|
||||
* id, and the bytes come back as a File for the composer's own checks, as a file from the
|
||||
* file dialog does. In a browser there's no bridge, and nothing here offers anything.
|
||||
*/
|
||||
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { getDesktopBridge } from './bridge';
|
||||
import { getDesktopPolicy, onDesktopPolicyChange } from './policy';
|
||||
import type { PolicySnapshot } from './policy-schema';
|
||||
import type { DesktopRecentFile } from './types';
|
||||
|
||||
/** The shell's limit for one file, the same as for a file from "Open with" (HANDOFF_MAX_BYTES). */
|
||||
export const RECENT_FILE_MAX_BYTES = 100 * 1024 * 1024;
|
||||
|
||||
/** The shell has the list and the RecentFilesInAttach policy doesn't hide it. */
|
||||
export function recentFilesOffered(policy: PolicySnapshot = getDesktopPolicy()): boolean {
|
||||
return !!getDesktopBridge()?.recentFiles && policy.RecentFilesInAttach?.value !== false;
|
||||
}
|
||||
|
||||
/** recentFilesOffered, live. False in the server's render, so the first render in the page matches it. */
|
||||
export function useRecentFilesOffered(): boolean {
|
||||
return useSyncExternalStore(onDesktopPolicyChange, () => recentFilesOffered(), () => false);
|
||||
}
|
||||
|
||||
/** Straight from the click that opened the menu: main wants one. Empty when there's nothing to show. */
|
||||
export async function listRecentFiles(): Promise<DesktopRecentFile[]> {
|
||||
const bridge = getDesktopBridge()?.recentFiles;
|
||||
if (!bridge) return [];
|
||||
try {
|
||||
const result = await bridge.list();
|
||||
return result.ok ? result.files : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export type RecentFileAttach =
|
||||
| { ok: true; file: File }
|
||||
| { ok: false; reason: 'missing' | 'too-large' | 'failed' | 'quiet' };
|
||||
|
||||
/** Straight from the click on the row. `quiet`: nothing worth telling the user (locked, or switched off). */
|
||||
export async function readRecentFile(id: string): Promise<RecentFileAttach> {
|
||||
const bridge = getDesktopBridge()?.recentFiles;
|
||||
if (!bridge) return { ok: false, reason: 'quiet' };
|
||||
try {
|
||||
const result = await bridge.attach(id);
|
||||
if (result.ok) return { ok: true, file: new File([new Uint8Array(result.file.data)], result.file.name) };
|
||||
if (result.reason === 'missing' || result.reason === 'too-large') return { ok: false, reason: result.reason };
|
||||
// Locked or switched off since the menu opened: the page shows that itself.
|
||||
if (result.reason === 'locked' || result.reason === 'policy') return { ok: false, reason: 'quiet' };
|
||||
// An id from a list a newer one replaced, or a click main didn't see: worth another try.
|
||||
return { ok: false, reason: 'failed' };
|
||||
} catch {
|
||||
return { ok: false, reason: 'failed' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A long folder as its start and its end, which tell it apart: the drive or the share, then
|
||||
* the folders nearest the file. The middle goes, where a path's end would under an ellipsis.
|
||||
*/
|
||||
export function shortFolder(folder: string, max = 44): string {
|
||||
if (folder.length <= max) return folder;
|
||||
const sep = folder.includes('\\') ? '\\' : '/';
|
||||
const parts = folder.split(sep);
|
||||
// \\server\share, or C:, or the empty start of /home.
|
||||
const rootCount = folder.startsWith('\\\\') ? 4 : 1;
|
||||
if (parts.length <= rootCount + 1) return folder;
|
||||
const root = parts.slice(0, rootCount).join(sep);
|
||||
let tail = parts.slice(rootCount);
|
||||
while (tail.length > 1 && `${root}${sep}…${sep}${tail.join(sep)}`.length > max) tail = tail.slice(1);
|
||||
return `${root}${sep}…${sep}${tail.join(sep)}`;
|
||||
}
|
||||
|
||||
const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
|
||||
['year', 365 * 24 * 60 * 60_000],
|
||||
['month', 30 * 24 * 60 * 60_000],
|
||||
['week', 7 * 24 * 60 * 60_000],
|
||||
['day', 24 * 60 * 60_000],
|
||||
['hour', 60 * 60_000],
|
||||
['minute', 60_000],
|
||||
];
|
||||
|
||||
/** "5 minutes ago", "yesterday", "3 weeks ago", in the UI's language. Under a minute: "now". */
|
||||
export function recentWhen(usedAt: number, now: number, locale: string): string {
|
||||
const format = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
|
||||
const ago = Math.max(0, now - usedAt);
|
||||
// Whole days by the calendar, so something from last night is "yesterday", not "10 hours ago".
|
||||
if (ago >= 12 * 60 * 60_000 && ago < 7 * 24 * 60 * 60_000) {
|
||||
const day = (time: number) => {
|
||||
const date = new Date(time);
|
||||
return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / (24 * 60 * 60_000);
|
||||
};
|
||||
const days = day(now) - day(usedAt);
|
||||
if (days >= 1) return format.format(-days, 'day');
|
||||
}
|
||||
for (const [unit, size] of UNITS) {
|
||||
if (ago >= size) return format.format(-Math.floor(ago / size), unit);
|
||||
}
|
||||
return format.format(0, 'second');
|
||||
}
|
||||
@@ -810,6 +810,39 @@ export interface DesktopDevToolsBridge {
|
||||
onChange: (listener: (state: DesktopDevToolsState) => void) => () => void;
|
||||
}
|
||||
|
||||
/** One of the user's recently used files, as the Attach menu shows it. Nothing more of it reaches the page. */
|
||||
export interface DesktopRecentFile {
|
||||
/** Opaque. `attach` takes it, from the window that listed it, until that window lists again. */
|
||||
id: string;
|
||||
name: string;
|
||||
/** The folder it's in, for display. */
|
||||
folder: string;
|
||||
/** The whole path, for a tooltip. */
|
||||
path: string;
|
||||
/** When it was last used, in milliseconds since 1970. */
|
||||
usedAt: number;
|
||||
/** A small icon as a data: URL, when the OS gave one in time. */
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
/** `gesture`: no click or key press just now. `policy`: RecentFilesInAttach is off. */
|
||||
export type DesktopRecentFilesResult =
|
||||
| { ok: true; files: DesktopRecentFile[] }
|
||||
| { ok: false; reason: 'policy' | 'locked' | 'gesture' };
|
||||
|
||||
export type DesktopRecentFileAttachResult =
|
||||
| { ok: true; file: DesktopOsFile }
|
||||
| { ok: false; reason: 'policy' | 'locked' | 'gesture' | 'unknown' | 'missing' | 'too-large' | 'failed' };
|
||||
|
||||
/**
|
||||
* The files the OS says were used last, for the composer's Attach menu. Main wants a click
|
||||
* or key press of its own for each call, reads only a file it just listed, and never logs.
|
||||
*/
|
||||
export interface DesktopRecentFilesBridge {
|
||||
list: () => Promise<DesktopRecentFilesResult>;
|
||||
attach: (id: string) => Promise<DesktopRecentFileAttachResult>;
|
||||
}
|
||||
|
||||
/** An attachment copied to a private folder and open in its default program. */
|
||||
export interface DesktopEditSession {
|
||||
id: string;
|
||||
@@ -932,6 +965,8 @@ export interface BulwarkDesktopBridge {
|
||||
edit?: DesktopEditBridge;
|
||||
/** Absent on older shells. */
|
||||
devTools?: DesktopDevToolsBridge;
|
||||
/** Absent on older shells. */
|
||||
recentFiles?: DesktopRecentFilesBridge;
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -103,11 +103,15 @@ export const Button = React.forwardRef<HTMLButtonElement, KitButtonProps>(functi
|
||||
);
|
||||
});
|
||||
|
||||
/** A text link styled like the app's inline links ("Add condition"). */
|
||||
/**
|
||||
* A text link styled like the app's inline links ("Add condition"). A long one
|
||||
* wraps like a paragraph: lines start at the icon's side (a button centres its
|
||||
* text otherwise), with the icon beside the first line.
|
||||
*/
|
||||
export function LinkButton({ icon, children, className, ...rest }: React.ButtonHTMLAttributes<HTMLButtonElement> & { icon?: string }) {
|
||||
return (
|
||||
<button type="button" className={cn('bk inline-flex items-center gap-1 text-sm text-primary hover:underline disabled:opacity-50 disabled:pointer-events-none', className)} {...rest}>
|
||||
{icon && <Icon name={icon} size="sm" />}
|
||||
<button type="button" className={cn('bk inline-flex items-start gap-1 text-start text-sm text-primary hover:underline disabled:opacity-50 disabled:pointer-events-none', className)} {...rest}>
|
||||
{icon && <Icon name={icon} size="sm" className="mt-[0.1875rem]" />}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user