From 5d49f982549d45db265ca75fd5c884c8943457f9 Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Wed, 21 Oct 2026 17:41:37 +0330 Subject: [PATCH 01/11] Feat: Migration - export message history for the 2.0 upgrade. --- src-tauri/src/lib.rs | 4 +- src-tauri/src/migration_export.rs | 63 +++++++- ui/src/lib/historyExport.ts | 230 ++++++++++++++++++++++++++++++ ui/src/lib/historyMeasure.ts | 227 +++++++++++++++++++++++++++++ ui/src/lib/migrationExport.ts | 60 +++++--- ui/src/routes/+layout.svelte | 33 +++++ 6 files changed, 597 insertions(+), 20 deletions(-) create mode 100644 ui/src/lib/historyExport.ts create mode 100644 ui/src/lib/historyMeasure.ts diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d05db758..d7a87797 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -14,7 +14,9 @@ pub fn run() { migration_export::write_migration_export, migration_export::read_migration_export, migration_export::set_pending_enable, - migration_export::get_pending_enable + migration_export::get_pending_enable, + migration_export::write_history_export, + migration_export::read_history_export ]) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_opener::init()) diff --git a/src-tauri/src/migration_export.rs b/src-tauri/src/migration_export.rs index 2d2aa48d..bcca5a25 100644 --- a/src-tauri/src/migration_export.rs +++ b/src-tauri/src/migration_export.rs @@ -14,7 +14,7 @@ use std::fs; use std::io::ErrorKind; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use crate::config::APP_ID; @@ -78,6 +78,13 @@ fn export_path(agent: Option<&str>) -> Result { #[tauri::command] pub fn write_migration_export(contents: String, agent: Option) -> Result { let path = export_path(agent.as_deref())?; + write_atomically(&path, contents.as_bytes())?; + Ok(path.display().to_string()) +} + +/// Write `bytes` to `path` through a temporary file and a rename, so a crash +/// or a full disk leaves the previous file intact instead of truncating it. +fn write_atomically(path: &Path, bytes: &[u8]) -> Result<(), String> { let dir = path .parent() .ok_or_else(|| "Export path has no parent directory".to_string())?; @@ -89,14 +96,64 @@ pub fn write_migration_export(contents: String, agent: Option) -> Result fs::create_dir_all(dir).map_err(|e| format!("Could not create {}: {e}", dir.display()))?; let tmp_path = dir.join(format!("{file_name}.tmp")); - fs::write(&tmp_path, contents.as_bytes()) + fs::write(&tmp_path, bytes) .map_err(|e| format!("Could not write {}: {e}", tmp_path.display()))?; - fs::rename(&tmp_path, &path) + fs::rename(&tmp_path, path) .map_err(|e| format!("Could not replace {}: {e}", path.display()))?; + Ok(()) +} + +/// Directory holding one message-history file per conversation, beside the +/// main export. Shares the export's dev and per-agent scoping. +fn history_dir(agent: Option<&str>) -> Result { + let export = export_path(agent)?; + let dir = export + .parent() + .ok_or_else(|| "Export path has no parent directory".to_string())?; + let name = match (tauri::is_dev(), agent) { + (true, Some(agent)) => format!("history-{}", agent_fragment(agent)), + _ => "history".to_string(), + }; + Ok(dir.join(name)) +} + +/// The history file for a conversation, named after its network seed. +/// +/// The seed comes from the frontend, so anything that is not a plain UUID-like +/// name is refused rather than allowed to form a path. +fn history_path(seed: &str, agent: Option<&str>) -> Result { + let valid = !seed.is_empty() + && seed.len() <= 128 + && seed.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + if !valid { + return Err(format!("Refusing unexpected network seed {seed:?} as a file name")); + } + Ok(history_dir(agent)?.join(format!("{seed}.json"))) +} +/// Write the message history of one conversation, replacing the previous one. +#[tauri::command] +pub fn write_history_export( + seed: String, + contents: String, + agent: Option, +) -> Result { + let path = history_path(&seed, agent.as_deref())?; + write_atomically(&path, contents.as_bytes())?; Ok(path.display().to_string()) } +/// Read the exported history of one conversation, or `None` if there is none. +#[tauri::command] +pub fn read_history_export(seed: String, agent: Option) -> Result, String> { + let path = history_path(&seed, agent.as_deref())?; + match fs::read_to_string(&path) { + Ok(contents) => Ok(Some(contents)), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("Could not read {}: {e}", path.display())), + } +} + fn pending_enable_path(agent: Option<&str>) -> Result { let export = export_path(agent)?; let dir = export diff --git a/ui/src/lib/historyExport.ts b/ui/src/lib/historyExport.ts new file mode 100644 index 00000000..ccc16369 --- /dev/null +++ b/ui/src/lib/historyExport.ts @@ -0,0 +1,230 @@ +import { invoke } from "@tauri-apps/api/core"; +import { get } from "svelte/store"; +import { encodeHashToBase64, type AgentPubKeyB64, type CellId, type Record } from "@holochain/client"; +import { BUCKET_RANGE_MS } from "$config"; +import type { ConversationExtended, MessageFile, MessageRecord, MessageType } from "$lib/types"; +import type { RelayClient } from "$store/RelayClient"; +import type { ConversationStore } from "$store/ConversationStore"; +import { encodeCellIdToBase64 } from "$lib/utils"; +import { withArchivedCellEnabled } from "$lib/migrationExport"; + +/** + * Export every conversation's message history for the next major release. + * + * A 2.x release cannot read this release's conductor database, so old messages + * only survive the upgrade if they are copied out first. One file per + * conversation, `export/history/.json`, beside the main export. + * 2.x matches it to the rebuilt conversation by that seed. + * + * Read from this device only — never the network — so it is fast and cannot + * stall: the measured cost on a real account was 527 messages in a few + * seconds. The whole history is re-read on each run, which keeps the logic + * simple and makes edits and deletions show up without any bookkeeping. + */ + +/** Bump when the file shape changes in a way an importer has to notice. */ +export const HISTORY_EXPORT_VERSION = 1; + +const TAG = "[history-export]"; +const BUCKET_CHUNK = 30; + +export interface ExportedImage { + name: string; + size: number; + type: string; + lastModified: number; + /** `storage_entry_hash` of the file in the file_storage zome. */ + hash: string; +} + +export interface ExportedMessage { + /** Original action hash: stable across edits, so an importer can deduplicate. */ + id: string; + author: AgentPubKeyB64; + /** When the message was first sent, in microseconds (Holochain timestamps). */ + timestamp: number; + /** When it was last edited, if it was; the content is the edited version. */ + editedAt?: number; + type: MessageType; + content: string; + images: ExportedImage[]; +} + +export interface HistoryExport { + version: number; + networkSeed: string; + /** The 1.x conversation this came from. */ + cellIdB64: string; + exportedAt: number; + messages: ExportedMessage[]; +} + +function exportImage(image: MessageFile): ExportedImage { + return { + name: image.name, + size: image.size, + type: image.file_type, + lastModified: image.last_modified, + hash: encodeHashToBase64(image.storage_entry_hash), + }; +} + +/** Timestamp of the original send, for a message that has been edited. */ +async function originalTimestamp( + relayClient: RelayClient, + cellId: CellId, + record: MessageRecord, +): Promise { + const original: Record | undefined = await relayClient.client.callZome({ + cell_id: cellId, + zome_name: "relay", + fn_name: "get_original_message", + payload: record.original_action, + }); + return original?.signed_action.hashed.content.timestamp ?? record.signed_action.hashed.content.timestamp; +} + +async function readHistory( + relayClient: RelayClient, + conversation: ConversationExtended, +): Promise { + const cellId = conversation.cellInfo.cell_id; + const lastBucket = Math.max( + 0, + Math.round((Date.now() - conversation.dnaProperties.created) / BUCKET_RANGE_MS), + ); + + const messages: ExportedMessage[] = []; + for (let first = 0; first <= lastBucket; first += BUCKET_CHUNK) { + const buckets: number[] = []; + for (let b = first; b <= Math.min(lastBucket, first + BUCKET_CHUNK - 1); b++) buckets.push(b); + + const records = await relayClient.getMessagesForBuckets(cellId, buckets); + for (const record of records) { + if (!record.message) continue; + const latest = record.signed_action.hashed; + const edited = + encodeHashToBase64(latest.hash) !== encodeHashToBase64(record.original_action); + + messages.push({ + id: encodeHashToBase64(record.original_action), + author: encodeHashToBase64(latest.content.author), + timestamp: edited + ? await originalTimestamp(relayClient, cellId, record) + : latest.content.timestamp, + editedAt: edited ? latest.content.timestamp : undefined, + type: record.message.message_type, + content: record.message.content, + images: record.message.images.map(exportImage), + }); + } + } + + return messages.sort((a, b) => a.timestamp - b.timestamp); +} + +function parse(raw: string | null): HistoryExport | undefined { + if (!raw) return undefined; + try { + return JSON.parse(raw) as HistoryExport; + } catch { + return undefined; + } +} + +/** Everything but the timestamp, to skip rewriting an unchanged file. */ +function contentKey(history: HistoryExport): string { + const { exportedAt: _exportedAt, ...rest } = history; + return JSON.stringify(rest); +} + +/** Archived conversations already read this launch; see `exportHistory`. */ +const archivedReadThisLaunch = new Set(); + +let running = false; + +/** + * Export the history of every conversation. Never throws, and a second call + * while one is running is skipped rather than queued. + * + * Archived conversations are disabled cells and have to be enabled briefly to + * be read, which is visible, so each is read at most once per launch. + */ +export async function exportHistory( + relayClient: RelayClient, + conversationStore: ConversationStore, + myPubKeyB64: AgentPubKeyB64, +): Promise { + if (running) return; + running = true; + const started = performance.now(); + let written = 0; + let unchanged = 0; + let messages = 0; + let failed = 0; + + try { + const conversations = Object.values(get(conversationStore).data) as ConversationExtended[]; + for (const conversation of conversations) { + const cellIdB64 = encodeCellIdToBase64(conversation.cellInfo.cell_id); + const seed = conversation.cellInfo.dna_modifiers.network_seed; + const archived = !conversation.cellInfo.enabled; + if (archived && archivedReadThisLaunch.has(cellIdB64)) continue; + + try { + const read = () => readHistory(relayClient, conversation); + const history: HistoryExport = { + version: HISTORY_EXPORT_VERSION, + networkSeed: seed, + cellIdB64, + exportedAt: Date.now(), + messages: archived + ? await withArchivedCellEnabled( + relayClient, + conversation.cellInfo.cell_id, + cellIdB64, + myPubKeyB64, + read, + ) + : await read(), + }; + if (archived) archivedReadThisLaunch.add(cellIdB64); + + const previous = parse( + await invoke("read_history_export", { seed, agent: myPubKeyB64 }), + ); + + // Reading nothing where there used to be messages is far more likely + // a fault (a conversation that failed to load) than a real change. + if (history.messages.length === 0 && (previous?.messages.length ?? 0) > 0) { + console.warn(`${TAG} read no messages for ${seed}; keeping the previous export`); + continue; + } + messages += history.messages.length; + if (previous && contentKey(previous) === contentKey(history)) { + unchanged++; + continue; + } + + await invoke("write_history_export", { + seed, + contents: JSON.stringify(history), + agent: myPubKeyB64, + }); + written++; + } catch (e) { + failed++; + const message = e instanceof Error ? e.message : JSON.stringify(e); + console.error(`${TAG} could not export ${seed}: ${message}`); + } + } + + // Warn level: the release log drops webview info-level output. + console.warn( + `${TAG} done: ${messages} messages; ${written} file(s) written, ${unchanged} unchanged, ` + + `${failed} failed, in ${((performance.now() - started) / 1000).toFixed(1)} s`, + ); + } finally { + running = false; + } +} diff --git a/ui/src/lib/historyMeasure.ts b/ui/src/lib/historyMeasure.ts new file mode 100644 index 00000000..d4c0e839 --- /dev/null +++ b/ui/src/lib/historyMeasure.ts @@ -0,0 +1,227 @@ +import { get } from "svelte/store"; +import { encodeHashToBase64, type CellId, type EntryHash } from "@holochain/client"; +import { FileStorageClient } from "@holochain-open-dev/file-storage"; +import { BUCKET_RANGE_MS } from "$config"; +import type { RelayClient } from "$store/RelayClient"; +import type { ConversationStore } from "$store/ConversationStore"; +import type { ConversationExtended, MessageRecord } from "$lib/types"; + +/** + * MEASUREMENT ONLY — sizes the 1.0.4 history export before it is built. + * + * Walks every enabled conversation the way the export will (day buckets, read + * from this device only, never the network) and logs what it finds: message + * counts, text size, the size of the JSON the export would write, and images — + * declared size, whether they are actually on this device, and how long + * reading them takes. Image totals are also split by age, to pick a cap. + * + * Read-only: writes no files and does not enable archived conversations. + * Runs only in a build made with VITE_MEASURE_HISTORY=1. + */ + +const TAG = "[history-measure]"; +const BUCKET_CHUNK = 30; +const DAY_MS = 24 * 60 * 60 * 1000; +const AGE_LIMITS_DAYS = [30, 90, 180, 365]; + +interface ImageTotals { + count: number; + declaredBytes: number; + onDevice: number; + onDeviceBytes: number; + missing: number; + readMs: number; + /** Declared bytes of images younger than each limit in AGE_LIMITS_DAYS. */ + bytesByAge: number[]; +} + +interface ConversationResult { + title: string; + days: number; + messages: number; + textBytes: number; + exportJsonBytes: number; + images: ImageTotals; + ms: number; +} + +const utf8 = new TextEncoder(); + +function emptyImages(): ImageTotals { + return { + count: 0, + declaredBytes: 0, + onDevice: 0, + onDeviceBytes: 0, + missing: 0, + readMs: 0, + bytesByAge: AGE_LIMITS_DAYS.map(() => 0), + }; +} + +function mb(bytes: number): string { + return (bytes / 1024 / 1024).toFixed(1); +} + +function kb(bytes: number): string { + return (bytes / 1024).toFixed(1); +} + +/** The shape the export will write per message, to size it realistically. */ +function exportShape(record: MessageRecord) { + const action = record.signed_action.hashed.content; + return { + id: encodeHashToBase64(record.original_action), + author: encodeHashToBase64(action.author), + timestamp: action.timestamp, + type: record.message?.message_type, + content: record.message?.content, + images: (record.message?.images ?? []).map((i) => ({ + name: i.name, + size: i.size, + type: i.file_type, + hash: encodeHashToBase64(i.storage_entry_hash), + })), + }; +} + +/** Read an image's bytes from this device only; resolves to bytes read, or undefined. */ +async function readImageLocally( + files: FileStorageClient, + hash: EntryHash, +): Promise { + try { + const metadata = await files.getFileMetadata(hash, true); + let bytes = 0; + for (const chunkHash of metadata.chunks_hashes) { + const chunk = await files.fetchChunk(chunkHash, true); + bytes += chunk.size; + } + return bytes; + } catch { + return undefined; + } +} + +async function measureConversation( + relayClient: RelayClient, + conversation: ConversationExtended, + now: number, +): Promise { + const started = performance.now(); + const cellId: CellId = conversation.cellInfo.cell_id; + const title = conversation.config?.title ?? conversation.cellInfo.name; + const lastBucket = Math.max( + 0, + Math.round((now - conversation.dnaProperties.created) / BUCKET_RANGE_MS), + ); + + const files = new FileStorageClient(relayClient.client, "UNUSED ROLE NAME", "file_storage", cellId); + const result: ConversationResult = { + title, + days: lastBucket + 1, + messages: 0, + textBytes: 0, + exportJsonBytes: 0, + images: emptyImages(), + ms: 0, + }; + + for (let first = 0; first <= lastBucket; first += BUCKET_CHUNK) { + const buckets: number[] = []; + for (let b = first; b <= Math.min(lastBucket, first + BUCKET_CHUNK - 1); b++) buckets.push(b); + + const records = await relayClient.getMessagesForBuckets(cellId, buckets); + for (const record of records) { + if (!record.message) continue; + result.messages++; + result.textBytes += utf8.encode(record.message.content).length; + result.exportJsonBytes += utf8.encode(JSON.stringify(exportShape(record))).length; + + // Microseconds since the epoch, as Holochain timestamps are. + const ageDays = (now - record.signed_action.hashed.content.timestamp / 1000) / DAY_MS; + for (const image of record.message.images) { + result.images.count++; + result.images.declaredBytes += image.size; + AGE_LIMITS_DAYS.forEach((limit, i) => { + if (ageDays <= limit) result.images.bytesByAge[i] += image.size; + }); + + const readStarted = performance.now(); + const bytes = await readImageLocally(files, image.storage_entry_hash); + result.images.readMs += performance.now() - readStarted; + if (bytes === undefined) { + result.images.missing++; + } else { + result.images.onDevice++; + result.images.onDeviceBytes += bytes; + } + } + } + } + + result.ms = performance.now() - started; + return result; +} + +export async function measureHistory( + relayClient: RelayClient, + conversationStore: ConversationStore, +): Promise { + const now = Date.now(); + const conversations = Object.values(get(conversationStore).data) as ConversationExtended[]; + const enabled = conversations.filter((c) => c.cellInfo.enabled); + console.warn( + `${TAG} starting: ${enabled.length} enabled conversation(s), ` + + `${conversations.length - enabled.length} archived skipped`, + ); + + const totals = { + messages: 0, + textBytes: 0, + exportJsonBytes: 0, + images: emptyImages(), + ms: 0, + }; + + for (const conversation of enabled) { + try { + const r = await measureConversation(relayClient, conversation, now); + console.warn( + `${TAG} "${r.title}": ${r.days} days, ${r.messages} messages, ` + + `text ${kb(r.textBytes)} KB, export JSON ${kb(r.exportJsonBytes)} KB, ` + + `images ${r.images.count} (${mb(r.images.declaredBytes)} MB declared, ` + + `${r.images.onDevice} on device = ${mb(r.images.onDeviceBytes)} MB, ` + + `${r.images.missing} missing, read ${(r.images.readMs / 1000).toFixed(1)} s), ` + + `took ${(r.ms / 1000).toFixed(1)} s`, + ); + totals.messages += r.messages; + totals.textBytes += r.textBytes; + totals.exportJsonBytes += r.exportJsonBytes; + totals.ms += r.ms; + totals.images.count += r.images.count; + totals.images.declaredBytes += r.images.declaredBytes; + totals.images.onDevice += r.images.onDevice; + totals.images.onDeviceBytes += r.images.onDeviceBytes; + totals.images.missing += r.images.missing; + totals.images.readMs += r.images.readMs; + r.images.bytesByAge.forEach((b, i) => (totals.images.bytesByAge[i] += b)); + } catch (e) { + const message = e instanceof Error ? e.message : JSON.stringify(e); + console.warn(`${TAG} failed on "${conversation.cellInfo.name}": ${message}`); + } + } + + const byAge = AGE_LIMITS_DAYS.map( + (limit, i) => `${limit}d ${mb(totals.images.bytesByAge[i])} MB`, + ).join(", "); + console.warn( + `${TAG} TOTAL: ${totals.messages} messages, text ${kb(totals.textBytes)} KB, ` + + `export JSON ${kb(totals.exportJsonBytes)} KB; images ${totals.images.count} ` + + `(${mb(totals.images.declaredBytes)} MB declared, ${totals.images.onDevice} on device = ` + + `${mb(totals.images.onDeviceBytes)} MB, ${totals.images.missing} missing); ` + + `image bytes by age: ${byAge}; ` + + `walk took ${(totals.ms / 1000).toFixed(1)} s of which image reads ` + + `${(totals.images.readMs / 1000).toFixed(1)} s`, + ); +} diff --git a/ui/src/lib/migrationExport.ts b/ui/src/lib/migrationExport.ts index 26f5582a..6c7eec66 100644 --- a/ui/src/lib/migrationExport.ts +++ b/ui/src/lib/migrationExport.ts @@ -2,7 +2,7 @@ import { invoke } from "@tauri-apps/api/core"; import { getVersion } from "@tauri-apps/api/app"; import { get } from "svelte/store"; import { Base64 } from "js-base64"; -import type { AgentPubKeyB64 } from "@holochain/client"; +import type { AgentPubKeyB64, CellId } from "@holochain/client"; import { Privacy, type ConversationExtended, type ProfileExtended } from "$lib/types"; import type { RelayClient } from "$store/RelayClient"; import type { ConversationStore } from "$store/ConversationStore"; @@ -164,25 +164,53 @@ async function recoverArchivedProof( myPubKeyB64: AgentPubKeyB64, ): Promise { const cellId = conversation.cellInfo.cell_id; - - await invoke("set_pending_enable", { cell: cellIdB64, agent: myPubKeyB64 }); - try { - await relayClient.enableConversationCell(cellId); + return withArchivedCellEnabled(relayClient, cellId, cellIdB64, myPubKeyB64, async () => { const proof = await relayClient.getRawMembraneProof(cellId); return proof ? Base64.fromUint8Array(new Uint8Array(proof)) : undefined; - } finally { - // Restore the archived state even if the read failed, then drop the - // marker only once the cell is genuinely disabled again. + }); +} + +/** Serializes every temporary enable: there is one pending-enable marker. */ +let archivedCellQueue: Promise = Promise.resolve(); + +/** + * Run `read` against an archived (disabled) conversation by enabling it for + * the duration, then archiving it again. + * + * The intent is recorded with `set_pending_enable` first, so an interrupted + * run is repaired on the next launch instead of leaving the conversation + * un-archived. That marker holds one cell, so callers are queued: the proof + * recovery and the history export must never have two cells enabled at once. + */ +export function withArchivedCellEnabled( + relayClient: RelayClient, + cellId: CellId, + cellIdB64: string, + myPubKeyB64: AgentPubKeyB64, + read: () => Promise, +): Promise { + const run = async (): Promise => { + await invoke("set_pending_enable", { cell: cellIdB64, agent: myPubKeyB64 }); try { - await relayClient.disableConversationCell(cellId); - await invoke("set_pending_enable", { cell: null, agent: myPubKeyB64 }); - } catch (e) { - console.error( - `[migration-export] could not re-archive ${cellIdB64}; it will be repaired on next launch`, - e, - ); + await relayClient.enableConversationCell(cellId); + return await read(); + } finally { + // Restore the archived state even if the read failed, then drop the + // marker only once the cell is genuinely disabled again. + try { + await relayClient.disableConversationCell(cellId); + await invoke("set_pending_enable", { cell: null, agent: myPubKeyB64 }); + } catch (e) { + console.error( + `[migration-export] could not re-archive ${cellIdB64}; it will be repaired on next launch`, + e, + ); + } } - } + }; + const result = archivedCellQueue.then(run, run); + archivedCellQueue = result.catch(() => undefined); + return result; } /** diff --git a/ui/src/routes/+layout.svelte b/ui/src/routes/+layout.svelte index 318ecb79..afb29888 100644 --- a/ui/src/routes/+layout.svelte +++ b/ui/src/routes/+layout.svelte @@ -51,6 +51,7 @@ import { createNetworkStatsStore, type NetworkStatsStore } from "$store/NetworkStatsStore"; import Dialog from "$lib/Dialog.svelte"; import { exportMigrationData } from "$lib/migrationExport"; + import { exportHistory } from "$lib/historyExport"; // Holochain client let client: AppClient; @@ -225,6 +226,9 @@ migrationExportTimer = undefined; runMigrationExport(); } + if (isStoresSetup && Date.now() - lastHistoryExport > HISTORY_EXPORT_MIN_GAP_MS) { + runHistoryExport(); + } return; } @@ -275,6 +279,21 @@ }, MIGRATION_EXPORT_COALESCE_MS); } + // Message history for the next major release. It changes with every message, + // so it is exported on a timer and when the app is backgrounded rather than + // on store changes. A full run on a real account took a few seconds. + const HISTORY_EXPORT_FIRST_DELAY_MS = 15_000; + const HISTORY_EXPORT_INTERVAL_MS = 30 * 60 * 1000; + const HISTORY_EXPORT_MIN_GAP_MS = 5 * 60 * 1000; + let historyExportInterval: ReturnType | undefined; + let lastHistoryExport = 0; + + function runHistoryExport() { + lastHistoryExport = Date.now(); + // Not awaited and never fatal, like the main export. + void exportHistory(relayClient, conversationStore, myPubKeyB64); + } + async function setupApp() { initLightDarkModeSwitcher(); await initHolochainClient(); @@ -291,6 +310,19 @@ conversationStore.subscribe(scheduleMigrationExport), contactStore.subscribe(scheduleMigrationExport), ]; + + setTimeout(runHistoryExport, HISTORY_EXPORT_FIRST_DELAY_MS); + historyExportInterval = setInterval(runHistoryExport, HISTORY_EXPORT_INTERVAL_MS); + + // MEASUREMENT ONLY: size the 1.0.4 history export. Built in only with + // VITE_MEASURE_HISTORY=1; delayed so it does not compete with startup. + if (import.meta.env.VITE_MEASURE_HISTORY === "1") { + setTimeout(() => { + import("$lib/historyMeasure").then(({ measureHistory }) => + measureHistory(relayClient, conversationStore), + ); + }, 10_000); + } } onMount(async () => { @@ -301,6 +333,7 @@ onDestroy(() => { document.removeEventListener("visibilitychange", handleVisibilityChange); if (migrationExportTimer !== undefined) clearTimeout(migrationExportTimer); + if (historyExportInterval !== undefined) clearInterval(historyExportInterval); migrationExportUnsubscribers.forEach((unsubscribe) => unsubscribe()); }); From d2a561b102ceb51c5dad95af53d901112739d2ef Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Wed, 21 Oct 2026 20:29:15 +0330 Subject: [PATCH 02/11] Feat: Migration - export images for the 2.0 upgrade. --- src-tauri/src/lib.rs | 5 +- src-tauri/src/migration_export.rs | 87 ++++++++++-- ui/src/lib/historyExport.ts | 18 ++- ui/src/lib/imageExport.ts | 219 ++++++++++++++++++++++++++++++ 4 files changed, 312 insertions(+), 17 deletions(-) create mode 100644 ui/src/lib/imageExport.ts diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d7a87797..c6b9f875 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -16,7 +16,10 @@ pub fn run() { migration_export::set_pending_enable, migration_export::get_pending_enable, migration_export::write_history_export, - migration_export::read_history_export + migration_export::read_history_export, + migration_export::write_export_image, + migration_export::list_export_images, + migration_export::write_image_index ]) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_opener::init()) diff --git a/src-tauri/src/migration_export.rs b/src-tauri/src/migration_export.rs index bcca5a25..32c8eb1d 100644 --- a/src-tauri/src/migration_export.rs +++ b/src-tauri/src/migration_export.rs @@ -103,34 +103,42 @@ fn write_atomically(path: &Path, bytes: &[u8]) -> Result<(), String> { Ok(()) } -/// Directory holding one message-history file per conversation, beside the -/// main export. Shares the export's dev and per-agent scoping. -fn history_dir(agent: Option<&str>) -> Result { +/// A subdirectory of the export directory, e.g. `history` or `images`. +/// Shares the export's dev and per-agent scoping. +fn export_subdir(name: &str, agent: Option<&str>) -> Result { let export = export_path(agent)?; let dir = export .parent() .ok_or_else(|| "Export path has no parent directory".to_string())?; let name = match (tauri::is_dev(), agent) { - (true, Some(agent)) => format!("history-{}", agent_fragment(agent)), - _ => "history".to_string(), + (true, Some(agent)) => format!("{name}-{}", agent_fragment(agent)), + _ => name.to_string(), }; Ok(dir.join(name)) } +/// Network seeds and image hashes come from the frontend and become file +/// names, so anything but a plain identifier is refused rather than allowed +/// to form a path. +fn checked_name<'a>(name: &'a str, what: &str) -> Result<&'a str, String> { + let valid = !name.is_empty() + && name.len() <= 128 + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + if valid { + Ok(name) + } else { + Err(format!("Refusing unexpected {what} {name:?} as a file name")) + } +} + /// The history file for a conversation, named after its network seed. -/// -/// The seed comes from the frontend, so anything that is not a plain UUID-like -/// name is refused rather than allowed to form a path. fn history_path(seed: &str, agent: Option<&str>) -> Result { - let valid = !seed.is_empty() - && seed.len() <= 128 - && seed.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); - if !valid { - return Err(format!("Refusing unexpected network seed {seed:?} as a file name")); - } - Ok(history_dir(agent)?.join(format!("{seed}.json"))) + let seed = checked_name(seed, "network seed")?; + Ok(export_subdir("history", agent)?.join(format!("{seed}.json"))) } +const IMAGE_INDEX_FILE_NAME: &str = "index.json"; + /// Write the message history of one conversation, replacing the previous one. #[tauri::command] pub fn write_history_export( @@ -225,3 +233,52 @@ pub fn read_migration_export(agent: Option) -> Result, St Err(e) => Err(format!("Could not read {}: {e}", path.display())), } } + +/// Write one exported image, named after its file-storage entry hash. +/// +/// Takes the bytes as a raw IPC body rather than JSON: a JSON array spends +/// several bytes per image byte, which matters for photos. The hash and agent +/// travel as `x-image-hash` and `x-agent` headers. +#[tauri::command] +pub fn write_export_image(request: tauri::ipc::Request<'_>) -> Result<(), String> { + let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else { + return Err("Expected the image as raw bytes".to_string()); + }; + let header = |key: &str| { + request + .headers() + .get(key) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + }; + let hash = header("x-image-hash").ok_or_else(|| "Missing x-image-hash header".to_string())?; + let agent = header("x-agent"); + + let hash = checked_name(&hash, "image hash")?; + let path = export_subdir("images", agent.as_deref())?.join(hash); + write_atomically(&path, bytes) +} + +/// Hashes of the images already exported, so a run only adds new ones. +#[tauri::command] +pub fn list_export_images(agent: Option) -> Result, String> { + let dir = export_subdir("images", agent.as_deref())?; + let entries = match fs::read_dir(&dir) { + Ok(entries) => entries, + Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(format!("Could not read {}: {e}", dir.display())), + }; + + Ok(entries + .filter_map(|entry| entry.ok()?.file_name().into_string().ok()) + .filter(|name| name != IMAGE_INDEX_FILE_NAME && !name.ends_with(".tmp")) + .collect()) +} + +/// Write the image index: what each exported image is, and which images were +/// left out and why. +#[tauri::command] +pub fn write_image_index(contents: String, agent: Option) -> Result<(), String> { + let path = export_subdir("images", agent.as_deref())?.join(IMAGE_INDEX_FILE_NAME); + write_atomically(&path, contents.as_bytes()) +} diff --git a/ui/src/lib/historyExport.ts b/ui/src/lib/historyExport.ts index ccc16369..a9ca7251 100644 --- a/ui/src/lib/historyExport.ts +++ b/ui/src/lib/historyExport.ts @@ -7,6 +7,7 @@ import type { RelayClient } from "$store/RelayClient"; import type { ConversationStore } from "$store/ConversationStore"; import { encodeCellIdToBase64 } from "$lib/utils"; import { withArchivedCellEnabled } from "$lib/migrationExport"; +import { exportImages, type ExportedConversation } from "$lib/imageExport"; /** * Export every conversation's message history for the next major release. @@ -163,15 +164,26 @@ export async function exportHistory( let messages = 0; let failed = 0; + // What is on disk for every conversation after this run, for the image + // export: a conversation not re-read this time still has its images. + const onDisk: ExportedConversation[] = []; + try { const conversations = Object.values(get(conversationStore).data) as ConversationExtended[]; for (const conversation of conversations) { const cellIdB64 = encodeCellIdToBase64(conversation.cellInfo.cell_id); const seed = conversation.cellInfo.dna_modifiers.network_seed; const archived = !conversation.cellInfo.enabled; - if (archived && archivedReadThisLaunch.has(cellIdB64)) continue; + const keep = (history?: HistoryExport) => { + if (history) onDisk.push({ conversation, cellIdB64, seed, archived, messages: history.messages }); + }; try { + if (archived && archivedReadThisLaunch.has(cellIdB64)) { + keep(parse(await invoke("read_history_export", { seed, agent: myPubKeyB64 }))); + continue; + } + const read = () => readHistory(relayClient, conversation); const history: HistoryExport = { version: HISTORY_EXPORT_VERSION, @@ -198,9 +210,11 @@ export async function exportHistory( // a fault (a conversation that failed to load) than a real change. if (history.messages.length === 0 && (previous?.messages.length ?? 0) > 0) { console.warn(`${TAG} read no messages for ${seed}; keeping the previous export`); + keep(previous); continue; } messages += history.messages.length; + keep(history); if (previous && contentKey(previous) === contentKey(history)) { unchanged++; continue; @@ -224,6 +238,8 @@ export async function exportHistory( `${TAG} done: ${messages} messages; ${written} file(s) written, ${unchanged} unchanged, ` + `${failed} failed, in ${((performance.now() - started) / 1000).toFixed(1)} s`, ); + + await exportImages(relayClient, onDisk, myPubKeyB64); } finally { running = false; } diff --git a/ui/src/lib/imageExport.ts b/ui/src/lib/imageExport.ts new file mode 100644 index 00000000..4570214f --- /dev/null +++ b/ui/src/lib/imageExport.ts @@ -0,0 +1,219 @@ +import { invoke } from "@tauri-apps/api/core"; +import { decodeHashFromBase64, type AgentPubKeyB64, type CellId } from "@holochain/client"; +import { FileStorageClient } from "@holochain-open-dev/file-storage"; +import type { ConversationExtended } from "$lib/types"; +import type { RelayClient } from "$store/RelayClient"; +import { withArchivedCellEnabled } from "$lib/migrationExport"; +import type { ExportedMessage } from "$lib/historyExport"; + +/** + * Export the images referenced by the exported message history. + * + * Message history only carries image references; the bytes live in each + * conversation's file_storage zome, which a 2.x release cannot read. Each image + * is written once to `export/images/`, so later runs only + * add new ones. `export/images/index.json` says what each file is, and lists + * images left out — over the size ceiling, or not on this device — so 2.x can + * tell a missing image from a broken one. + * + * Read from this device only. A real account's 13 MB of images read in under + * a second. + */ + +/** Bump when the index shape changes in a way an importer has to notice. */ +export const IMAGE_INDEX_VERSION = 1; + +/** + * Safety ceiling for all exported images together. Everything is exported + * newest first until it is reached; it exists to protect phones from an + * extreme account, not to trim normal ones. + */ +export const IMAGE_EXPORT_CEILING_BYTES = 500 * 1024 * 1024; + +const TAG = "[image-export]"; + +/** One conversation's history as it stands on disk after a history run. */ +export interface ExportedConversation { + conversation: ConversationExtended; + cellIdB64: string; + seed: string; + archived: boolean; + messages: ExportedMessage[]; +} + +interface ImageRef { + hash: string; + name: string; + type: string; + size: number; + lastModified: number; + /** Send time of the newest message using this image, in microseconds. */ + newest: number; + /** Conversations (network seeds) whose messages use it. */ + seeds: Set; + /** Where to read it from: the conversation of the newest message using it. */ + source: ExportedConversation; +} + +interface ImageIndex { + version: number; + ceilingBytes: number; + images: { + [hash: string]: { + name: string; + type: string; + size: number; + lastModified: number; + newest: number; + seeds: string[]; + }; + }; + /** Left out because the ceiling was reached; newest images are kept first. */ + overCeiling: string[]; + /** Referenced, but not on this device (never received, or unreadable). */ + missing: string[]; +} + +function collectImages(conversations: ExportedConversation[]): ImageRef[] { + const refs = new Map(); + for (const source of conversations) { + for (const message of source.messages) { + for (const image of message.images) { + const ref = refs.get(image.hash); + if (!ref) { + refs.set(image.hash, { + ...image, + newest: message.timestamp, + seeds: new Set([source.seed]), + source, + }); + continue; + } + ref.seeds.add(source.seed); + if (message.timestamp > ref.newest) { + ref.newest = message.timestamp; + ref.source = source; + } + } + } + } + return [...refs.values()].sort((a, b) => b.newest - a.newest); +} + +/** Read an image from this device and write it to the export. */ +async function exportImage( + relayClient: RelayClient, + cellId: CellId, + hash: string, + myPubKeyB64: AgentPubKeyB64, +): Promise { + const files = new FileStorageClient(relayClient.client, "UNUSED ROLE NAME", "file_storage", cellId); + const file = await files.downloadFile(decodeHashFromBase64(hash), true); + const bytes = new Uint8Array(await file.arrayBuffer()); + await invoke("write_export_image", bytes, { + headers: { "x-image-hash": hash, "x-agent": myPubKeyB64 }, + }); +} + +/** Archived conversations already enabled for images this launch. */ +const archivedImagesThisLaunch = new Set(); + +/** Last index written, to skip rewriting an unchanged one. */ +let lastIndex: string | undefined; + +/** Export images for the given history. Never throws. */ +export async function exportImages( + relayClient: RelayClient, + conversations: ExportedConversation[], + myPubKeyB64: AgentPubKeyB64, +): Promise { + const started = performance.now(); + try { + const refs = collectImages(conversations); + const existing = new Set(await invoke("list_export_images", { agent: myPubKeyB64 })); + + // Newest first until the ceiling, counting images already exported too so + // the selection is the same on every run. + const selected: ImageRef[] = []; + const overCeiling: string[] = []; + let total = 0; + for (const ref of refs) { + if (total + ref.size > IMAGE_EXPORT_CEILING_BYTES) { + overCeiling.push(ref.hash); + continue; + } + total += ref.size; + selected.push(ref); + } + + // Group what is still to be written by the conversation to read it from. + const pending = new Map(); + for (const ref of selected.filter((r) => !existing.has(r.hash))) { + pending.set(ref.source, [...(pending.get(ref.source) ?? []), ref]); + } + + const missing = new Set(); + let written = 0; + for (const [source, images] of pending) { + const cellId = source.conversation.cellInfo.cell_id; + const writeAll = async () => { + for (const image of images) { + try { + await exportImage(relayClient, cellId, image.hash, myPubKeyB64); + existing.add(image.hash); + written++; + } catch { + missing.add(image.hash); + } + } + }; + + if (!source.archived) { + await writeAll(); + } else if (!archivedImagesThisLaunch.has(source.cellIdB64)) { + // Enabling an archived conversation is visible; once per launch. + archivedImagesThisLaunch.add(source.cellIdB64); + await withArchivedCellEnabled(relayClient, cellId, source.cellIdB64, myPubKeyB64, writeAll); + } else { + images.forEach((image) => missing.add(image.hash)); + } + } + + const index: ImageIndex = { + version: IMAGE_INDEX_VERSION, + ceilingBytes: IMAGE_EXPORT_CEILING_BYTES, + images: Object.fromEntries( + selected + .filter((r) => existing.has(r.hash)) + .map((r) => [ + r.hash, + { + name: r.name, + type: r.type, + size: r.size, + lastModified: r.lastModified, + newest: r.newest, + seeds: [...r.seeds], + }, + ]), + ), + overCeiling, + missing: [...missing], + }; + const serialized = JSON.stringify(index); + if (serialized !== lastIndex) { + await invoke("write_image_index", { contents: serialized, agent: myPubKeyB64 }); + lastIndex = serialized; + } + + // Warn level: the release log drops webview info-level output. + console.warn( + `${TAG} done: ${refs.length} referenced, ${Object.keys(index.images).length} exported ` + + `(${written} new, ${(total / 1024 / 1024).toFixed(1)} MB), ${overCeiling.length} over the ` + + `ceiling, ${missing.size} missing, in ${((performance.now() - started) / 1000).toFixed(1)} s`, + ); + } catch (e) { + const message = e instanceof Error ? e.message : JSON.stringify(e); + console.error(`${TAG} failed: ${message}`); + } +} From b610a1816b6109c2203c949102f09816bbe0f722 Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Sun, 25 Oct 2026 14:31:50 +0330 Subject: [PATCH 03/11] Chore: Migration - restrict the export to its owner; drop the measurement tool --- CHANGELOG.md | 5 + src-tauri/src/migration_export.rs | 61 ++++++-- ui/src/lib/historyMeasure.ts | 227 ------------------------------ ui/src/routes/+layout.svelte | 10 -- 4 files changed, 58 insertions(+), 245 deletions(-) delete mode 100644 ui/src/lib/historyMeasure.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6baf463d..86ea9529 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +## [1.0.4] - 2026-09-25 + +- Feat: Your message history and the images in your conversations, archived ones included, are now saved too, so they can come with you into the next major update. This happens automatically in the background and only adds new messages and images after the first run. +- Fix: The saved copy of your account is now readable only by your own user on Linux and macOS. + ## [1.0.3] - 2026-09-12 - Fix: The app could hang forever on the "Starting up..." screen, most often on faster machines. Holochain had actually started correctly; the app just never noticed and kept waiting. diff --git a/src-tauri/src/migration_export.rs b/src-tauri/src/migration_export.rs index 32c8eb1d..80a5e357 100644 --- a/src-tauri/src/migration_export.rs +++ b/src-tauri/src/migration_export.rs @@ -93,16 +93,57 @@ fn write_atomically(path: &Path, bytes: &[u8]) -> Result<(), String> { .and_then(|n| n.to_str()) .ok_or_else(|| "Export path has no file name".to_string())?; - fs::create_dir_all(dir).map_err(|e| format!("Could not create {}: {e}", dir.display()))?; + ensure_private_dir(dir)?; let tmp_path = dir.join(format!("{file_name}.tmp")); - fs::write(&tmp_path, bytes) - .map_err(|e| format!("Could not write {}: {e}", tmp_path.display()))?; + write_private_file(&tmp_path, bytes)?; fs::rename(&tmp_path, path) .map_err(|e| format!("Could not replace {}: {e}", path.display()))?; Ok(()) } +/// Create `dir` if needed and make it readable by this user only. +/// +/// The export holds the user's identity, membership proofs, full message +/// history and images. Other accounts on the same machine have no business +/// reading it. Windows profile directories and Android app storage are already +/// private to the user; Unix data directories are not necessarily. +fn ensure_private_dir(dir: &Path) -> Result<(), String> { + fs::create_dir_all(dir).map_err(|e| format!("Could not create {}: {e}", dir.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(dir, fs::Permissions::from_mode(0o700)) + .map_err(|e| format!("Could not restrict {}: {e}", dir.display()))?; + } + Ok(()) +} + +/// Write a file readable by this user only, from the moment it is created. +fn write_private_file(path: &Path, bytes: &[u8]) -> Result<(), String> { + use std::io::Write; + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options + .open(path) + .map_err(|e| format!("Could not write {}: {e}", path.display()))?; + file.write_all(bytes) + .map_err(|e| format!("Could not write {}: {e}", path.display()))?; + // `mode` only applies when the file is created; tighten a leftover one too. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o600)) + .map_err(|e| format!("Could not restrict {}: {e}", path.display()))?; + } + Ok(()) +} + /// A subdirectory of the export directory, e.g. `history` or `images`. /// Shares the export's dev and per-agent scoping. fn export_subdir(name: &str, agent: Option<&str>) -> Result { @@ -110,11 +151,17 @@ fn export_subdir(name: &str, agent: Option<&str>) -> Result { let dir = export .parent() .ok_or_else(|| "Export path has no parent directory".to_string())?; + // Restricted on every lookup, not only when a file is written: a run that + // finds nothing changed writes nothing, and must not leave a directory + // created by an earlier release readable. + ensure_private_dir(dir)?; let name = match (tauri::is_dev(), agent) { (true, Some(agent)) => format!("{name}-{}", agent_fragment(agent)), _ => name.to_string(), }; - Ok(dir.join(name)) + let subdir = dir.join(name); + ensure_private_dir(&subdir)?; + Ok(subdir) } /// Network seeds and image hashes come from the frontend and become file @@ -194,10 +241,8 @@ pub fn set_pending_enable(cell: Option, agent: Option) -> Result let dir = path .parent() .ok_or_else(|| "Pending-enable path has no parent directory".to_string())?; - fs::create_dir_all(dir) - .map_err(|e| format!("Could not create {}: {e}", dir.display()))?; - fs::write(&path, cell.as_bytes()) - .map_err(|e| format!("Could not write {}: {e}", path.display())) + ensure_private_dir(dir)?; + write_private_file(&path, cell.as_bytes()) } None => match fs::remove_file(&path) { Ok(()) => Ok(()), diff --git a/ui/src/lib/historyMeasure.ts b/ui/src/lib/historyMeasure.ts deleted file mode 100644 index d4c0e839..00000000 --- a/ui/src/lib/historyMeasure.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { get } from "svelte/store"; -import { encodeHashToBase64, type CellId, type EntryHash } from "@holochain/client"; -import { FileStorageClient } from "@holochain-open-dev/file-storage"; -import { BUCKET_RANGE_MS } from "$config"; -import type { RelayClient } from "$store/RelayClient"; -import type { ConversationStore } from "$store/ConversationStore"; -import type { ConversationExtended, MessageRecord } from "$lib/types"; - -/** - * MEASUREMENT ONLY — sizes the 1.0.4 history export before it is built. - * - * Walks every enabled conversation the way the export will (day buckets, read - * from this device only, never the network) and logs what it finds: message - * counts, text size, the size of the JSON the export would write, and images — - * declared size, whether they are actually on this device, and how long - * reading them takes. Image totals are also split by age, to pick a cap. - * - * Read-only: writes no files and does not enable archived conversations. - * Runs only in a build made with VITE_MEASURE_HISTORY=1. - */ - -const TAG = "[history-measure]"; -const BUCKET_CHUNK = 30; -const DAY_MS = 24 * 60 * 60 * 1000; -const AGE_LIMITS_DAYS = [30, 90, 180, 365]; - -interface ImageTotals { - count: number; - declaredBytes: number; - onDevice: number; - onDeviceBytes: number; - missing: number; - readMs: number; - /** Declared bytes of images younger than each limit in AGE_LIMITS_DAYS. */ - bytesByAge: number[]; -} - -interface ConversationResult { - title: string; - days: number; - messages: number; - textBytes: number; - exportJsonBytes: number; - images: ImageTotals; - ms: number; -} - -const utf8 = new TextEncoder(); - -function emptyImages(): ImageTotals { - return { - count: 0, - declaredBytes: 0, - onDevice: 0, - onDeviceBytes: 0, - missing: 0, - readMs: 0, - bytesByAge: AGE_LIMITS_DAYS.map(() => 0), - }; -} - -function mb(bytes: number): string { - return (bytes / 1024 / 1024).toFixed(1); -} - -function kb(bytes: number): string { - return (bytes / 1024).toFixed(1); -} - -/** The shape the export will write per message, to size it realistically. */ -function exportShape(record: MessageRecord) { - const action = record.signed_action.hashed.content; - return { - id: encodeHashToBase64(record.original_action), - author: encodeHashToBase64(action.author), - timestamp: action.timestamp, - type: record.message?.message_type, - content: record.message?.content, - images: (record.message?.images ?? []).map((i) => ({ - name: i.name, - size: i.size, - type: i.file_type, - hash: encodeHashToBase64(i.storage_entry_hash), - })), - }; -} - -/** Read an image's bytes from this device only; resolves to bytes read, or undefined. */ -async function readImageLocally( - files: FileStorageClient, - hash: EntryHash, -): Promise { - try { - const metadata = await files.getFileMetadata(hash, true); - let bytes = 0; - for (const chunkHash of metadata.chunks_hashes) { - const chunk = await files.fetchChunk(chunkHash, true); - bytes += chunk.size; - } - return bytes; - } catch { - return undefined; - } -} - -async function measureConversation( - relayClient: RelayClient, - conversation: ConversationExtended, - now: number, -): Promise { - const started = performance.now(); - const cellId: CellId = conversation.cellInfo.cell_id; - const title = conversation.config?.title ?? conversation.cellInfo.name; - const lastBucket = Math.max( - 0, - Math.round((now - conversation.dnaProperties.created) / BUCKET_RANGE_MS), - ); - - const files = new FileStorageClient(relayClient.client, "UNUSED ROLE NAME", "file_storage", cellId); - const result: ConversationResult = { - title, - days: lastBucket + 1, - messages: 0, - textBytes: 0, - exportJsonBytes: 0, - images: emptyImages(), - ms: 0, - }; - - for (let first = 0; first <= lastBucket; first += BUCKET_CHUNK) { - const buckets: number[] = []; - for (let b = first; b <= Math.min(lastBucket, first + BUCKET_CHUNK - 1); b++) buckets.push(b); - - const records = await relayClient.getMessagesForBuckets(cellId, buckets); - for (const record of records) { - if (!record.message) continue; - result.messages++; - result.textBytes += utf8.encode(record.message.content).length; - result.exportJsonBytes += utf8.encode(JSON.stringify(exportShape(record))).length; - - // Microseconds since the epoch, as Holochain timestamps are. - const ageDays = (now - record.signed_action.hashed.content.timestamp / 1000) / DAY_MS; - for (const image of record.message.images) { - result.images.count++; - result.images.declaredBytes += image.size; - AGE_LIMITS_DAYS.forEach((limit, i) => { - if (ageDays <= limit) result.images.bytesByAge[i] += image.size; - }); - - const readStarted = performance.now(); - const bytes = await readImageLocally(files, image.storage_entry_hash); - result.images.readMs += performance.now() - readStarted; - if (bytes === undefined) { - result.images.missing++; - } else { - result.images.onDevice++; - result.images.onDeviceBytes += bytes; - } - } - } - } - - result.ms = performance.now() - started; - return result; -} - -export async function measureHistory( - relayClient: RelayClient, - conversationStore: ConversationStore, -): Promise { - const now = Date.now(); - const conversations = Object.values(get(conversationStore).data) as ConversationExtended[]; - const enabled = conversations.filter((c) => c.cellInfo.enabled); - console.warn( - `${TAG} starting: ${enabled.length} enabled conversation(s), ` + - `${conversations.length - enabled.length} archived skipped`, - ); - - const totals = { - messages: 0, - textBytes: 0, - exportJsonBytes: 0, - images: emptyImages(), - ms: 0, - }; - - for (const conversation of enabled) { - try { - const r = await measureConversation(relayClient, conversation, now); - console.warn( - `${TAG} "${r.title}": ${r.days} days, ${r.messages} messages, ` + - `text ${kb(r.textBytes)} KB, export JSON ${kb(r.exportJsonBytes)} KB, ` + - `images ${r.images.count} (${mb(r.images.declaredBytes)} MB declared, ` + - `${r.images.onDevice} on device = ${mb(r.images.onDeviceBytes)} MB, ` + - `${r.images.missing} missing, read ${(r.images.readMs / 1000).toFixed(1)} s), ` + - `took ${(r.ms / 1000).toFixed(1)} s`, - ); - totals.messages += r.messages; - totals.textBytes += r.textBytes; - totals.exportJsonBytes += r.exportJsonBytes; - totals.ms += r.ms; - totals.images.count += r.images.count; - totals.images.declaredBytes += r.images.declaredBytes; - totals.images.onDevice += r.images.onDevice; - totals.images.onDeviceBytes += r.images.onDeviceBytes; - totals.images.missing += r.images.missing; - totals.images.readMs += r.images.readMs; - r.images.bytesByAge.forEach((b, i) => (totals.images.bytesByAge[i] += b)); - } catch (e) { - const message = e instanceof Error ? e.message : JSON.stringify(e); - console.warn(`${TAG} failed on "${conversation.cellInfo.name}": ${message}`); - } - } - - const byAge = AGE_LIMITS_DAYS.map( - (limit, i) => `${limit}d ${mb(totals.images.bytesByAge[i])} MB`, - ).join(", "); - console.warn( - `${TAG} TOTAL: ${totals.messages} messages, text ${kb(totals.textBytes)} KB, ` + - `export JSON ${kb(totals.exportJsonBytes)} KB; images ${totals.images.count} ` + - `(${mb(totals.images.declaredBytes)} MB declared, ${totals.images.onDevice} on device = ` + - `${mb(totals.images.onDeviceBytes)} MB, ${totals.images.missing} missing); ` + - `image bytes by age: ${byAge}; ` + - `walk took ${(totals.ms / 1000).toFixed(1)} s of which image reads ` + - `${(totals.images.readMs / 1000).toFixed(1)} s`, - ); -} diff --git a/ui/src/routes/+layout.svelte b/ui/src/routes/+layout.svelte index afb29888..97a1d640 100644 --- a/ui/src/routes/+layout.svelte +++ b/ui/src/routes/+layout.svelte @@ -313,16 +313,6 @@ setTimeout(runHistoryExport, HISTORY_EXPORT_FIRST_DELAY_MS); historyExportInterval = setInterval(runHistoryExport, HISTORY_EXPORT_INTERVAL_MS); - - // MEASUREMENT ONLY: size the 1.0.4 history export. Built in only with - // VITE_MEASURE_HISTORY=1; delayed so it does not compete with startup. - if (import.meta.env.VITE_MEASURE_HISTORY === "1") { - setTimeout(() => { - import("$lib/historyMeasure").then(({ measureHistory }) => - measureHistory(relayClient, conversationStore), - ); - }, 10_000); - } } onMount(async () => { From 1785791ec491f3d77a346ca1ee7231aba64906aa Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Sun, 25 Oct 2026 14:47:39 +0330 Subject: [PATCH 04/11] Fix: changelog date corrected. --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86ea9529..e57b61d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased -## [1.0.4] - 2026-09-25 +## [1.0.4] - 2026-10-25 - Feat: Your message history and the images in your conversations, archived ones included, are now saved too, so they can come with you into the next major update. This happens automatically in the background and only adds new messages and images after the first run. - Fix: The saved copy of your account is now readable only by your own user on Linux and macOS. From bd55da06394a19c0a57a56f45bb25170a0405b29 Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Sun, 25 Oct 2026 15:59:09 +0330 Subject: [PATCH 05/11] Test: unit-test the export's file handling. --- src-tauri/src/migration_export.rs | 98 +++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/src-tauri/src/migration_export.rs b/src-tauri/src/migration_export.rs index 80a5e357..8ca2b62f 100644 --- a/src-tauri/src/migration_export.rs +++ b/src-tauri/src/migration_export.rs @@ -327,3 +327,101 @@ pub fn write_image_index(contents: String, agent: Option) -> Result<(), let path = export_subdir("images", agent.as_deref())?.join(IMAGE_INDEX_FILE_NAME); write_atomically(&path, contents.as_bytes()) } + +#[cfg(test)] +mod tests { + use super::*; + use tempdir::TempDir; + + #[test] + fn accepts_network_seeds_and_image_hashes_as_file_names() { + for name in [ + "218dcd9d-4c19-47fa-bdf6-8ee4ae1b8f14", + "uhCEk1NmHJ2MPm4gVelKbPcshrn3ZUl38EVprEb7FuoUuQI6Wrk1k", + "uhCEkfWwAdnPAhKW7HploXXvMC0ror3HxkXNiwlXsu3bkb6A_Gt4Z", + ] { + assert_eq!(checked_name(name, "test").unwrap(), name); + } + } + + #[test] + fn refuses_names_that_could_form_a_path() { + let too_long = "a".repeat(129); + for name in [ + "", ".", "..", "../x", "a/b", "a\\b", "/etc/passwd", "x y", "x\0y", "ü", &too_long, + ] { + assert!(checked_name(name, "test").is_err(), "accepted {name:?}"); + } + } + + #[test] + fn writes_and_replaces_a_file_atomically() { + let root = TempDir::new("export").unwrap(); + let path = root.path().join("nested").join("history").join("seed.json"); + + write_atomically(&path, b"first").unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"first"); + + write_atomically(&path, b"second").unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"second"); + + // Nothing left over from the temporary-file step. + let names: Vec<_> = fs::read_dir(path.parent().unwrap()) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names, vec!["seed.json"]); + } + + #[test] + fn a_failed_write_leaves_the_previous_file_intact() { + let root = TempDir::new("export").unwrap(); + let path = root.path().join("migration-export.json"); + write_atomically(&path, b"good export").unwrap(); + + // Make the temporary file impossible to create, as a full disk or a + // crash mid-write would. + fs::create_dir(root.path().join("migration-export.json.tmp")).unwrap(); + + assert!(write_atomically(&path, b"").is_err()); + assert_eq!(fs::read(&path).unwrap(), b"good export"); + } + + #[test] + fn recovers_from_a_stale_temporary_file() { + let root = TempDir::new("export").unwrap(); + let path = root.path().join("seed.json"); + fs::write(root.path().join("seed.json.tmp"), b"half written by a crash").unwrap(); + + write_atomically(&path, b"complete").unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"complete"); + assert!(!root.path().join("seed.json.tmp").exists()); + } + + #[cfg(unix)] + #[test] + fn export_files_are_readable_by_their_owner_only() { + use std::os::unix::fs::PermissionsExt; + let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777; + + let root = TempDir::new("export").unwrap(); + let dir = root.path().join("history"); + let path = dir.join("seed.json"); + + // As an earlier release left them: world-readable. + fs::create_dir(&dir).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); + fs::write(&path, b"old").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + + write_atomically(&path, b"new").unwrap(); + assert_eq!(mode(&dir), 0o700); + assert_eq!(mode(&path), 0o600); + + // A newly created directory and file are private from the start. + let fresh = root.path().join("images").join("hash"); + write_atomically(&fresh, b"bytes").unwrap(); + assert_eq!(mode(fresh.parent().unwrap()), 0o700); + assert_eq!(mode(&fresh), 0o600); + } +} From 1fa7bd3824b2f86acfcb854df089570725669cd1 Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Sun, 25 Oct 2026 16:00:18 +0330 Subject: [PATCH 06/11] CI: test release branches and run the app's unit tests --- .github/workflows/test.yaml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index efba116e..cf1d78d7 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -5,6 +5,8 @@ on: branches: - develop - main + # Maintenance lines, e.g. release/1.0 for 1.x releases. + - "release/**" workflow_dispatch: # Cancel an in-progress run when new commits are pushed to the same PR. @@ -47,6 +49,14 @@ jobs: with: name: darksoil-studio + # Reuses compiled dependencies between runs: the zome workspace and the + # app crate, which embeds a full Holochain conductor. + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + . -> target + src-tauri -> target + # `npm test` builds the zomes (wasm), packs the .happ, then runs the # Tryorama/Vitest suite in the `tests` workspace against that .happ. - name: Install and run tests @@ -54,3 +64,12 @@ jobs: nix develop --no-update-lock-file --accept-flake-config --command bash -c "npm install && npm test" env: CARGO_REGISTRIES_CARGO_HOSTED_TOKEN: ${{ secrets.VOLLA_NEXUS_TOKEN }} + + # Unit tests of the app crate (keystore carry-over, export file + # handling). Runs after `npm test` because the crate embeds the .happ + # that step builds. + - name: Run app unit tests + run: | + nix develop --no-update-lock-file --accept-flake-config --command bash -c "cd src-tauri && cargo test --features holochain_bundled --lib" + env: + CARGO_REGISTRIES_CARGO_HOSTED_TOKEN: ${{ secrets.VOLLA_NEXUS_TOKEN }} From 1eab5115f565c20b1856436e126780a061462c55 Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Mon, 26 Oct 2026 18:27:02 +0330 Subject: [PATCH 07/11] Fix: never archive an active conversation while reading its proof. --- ui/src/lib/migrationExport.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/ui/src/lib/migrationExport.ts b/ui/src/lib/migrationExport.ts index 6c7eec66..b9cb7062 100644 --- a/ui/src/lib/migrationExport.ts +++ b/ui/src/lib/migrationExport.ts @@ -7,6 +7,7 @@ import { Privacy, type ConversationExtended, type ProfileExtended } from "$lib/t import type { RelayClient } from "$store/RelayClient"; import type { ConversationStore } from "$store/ConversationStore"; import type { ContactStore } from "$store/ContactStore"; +import { encodeCellIdToBase64 } from "$lib/utils"; /** * Snapshot of everything a future major release needs to rebuild this account. @@ -190,6 +191,16 @@ export function withArchivedCellEnabled( read: () => Promise, ): Promise { const run = async (): Promise => { + // Never archive a conversation that is not archived right now: if a caller + // passes an active one, just read it. Checked here, inside the queue, so + // the state cannot change between the check and the enable. + const current = (await relayClient.getRelayClonedCellInfos()).find( + (c) => encodeCellIdToBase64(c.cell_id) === cellIdB64, + ); + if (current?.enabled !== false) { + return read(); + } + await invoke("set_pending_enable", { cell: cellIdB64, agent: myPubKeyB64 }); try { await relayClient.enableConversationCell(cellId); @@ -299,7 +310,17 @@ async function collect( // Archived conversation with no cached proof: its cell is disabled and // cannot be zome-called, so enable it just long enough to read the proof. - if (membraneProofB64 === undefined && !attemptedProofRecovery.has(cellIdB64)) { + // + // Archived ones only. 1.0.3 lacked this check, and its released builds + // shipped a happ without get_raw_membrane_proof, so the read above + // failed for every active private conversation the user had not + // created, fell through to here, and the "re-archive afterwards" step + // archived conversations that had never been archived. + if ( + membraneProofB64 === undefined && + !conversation.cellInfo.enabled && + !attemptedProofRecovery.has(cellIdB64) + ) { attemptedProofRecovery.add(cellIdB64); try { console.log(`[migration-export] recovering membrane proof for archived "${title}"`); From 77e1b148f9d472bc8d45442f6ebb8bdacd8549e1 Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Mon, 26 Oct 2026 21:05:50 +0330 Subject: [PATCH 08/11] Feat: In app update process - tell 1.x users about 2.0 and update from inside the app. --- src-tauri/Cargo.lock | 73 ++++++++++++ src-tauri/Cargo.toml | 6 + src-tauri/capabilities/main.json | 4 + src-tauri/src/app_update.rs | 94 ++++++++++++++++ src-tauri/src/lib.rs | 10 +- src-tauri/tauri.conf.json | 8 ++ src-tauri/tauri.desktop.conf.json | 8 ++ ui/src/lib/UpdateBar.svelte | 48 ++++++++ ui/src/lib/historyExport.ts | 28 +++-- ui/src/lib/updateNotice.ts | 169 ++++++++++++++++++++++++++++ ui/src/routes/+layout.svelte | 38 +++++++ ui/src/translations/index.ts | 3 +- ui/src/translations/locales/bg.json | 8 +- ui/src/translations/locales/da.json | 8 +- ui/src/translations/locales/de.json | 8 +- ui/src/translations/locales/en.json | 10 +- ui/src/translations/locales/es.json | 8 +- ui/src/translations/locales/fr.json | 8 +- ui/src/translations/locales/hi.json | 8 +- ui/src/translations/locales/it.json | 8 +- ui/src/translations/locales/nl.json | 8 +- ui/src/translations/locales/no.json | 8 +- ui/src/translations/locales/ro.json | 8 +- ui/src/translations/locales/sk.json | 8 +- ui/src/translations/locales/sv.json | 8 +- 25 files changed, 571 insertions(+), 24 deletions(-) create mode 100644 src-tauri/src/app_update.rs create mode 100644 ui/src/lib/UpdateBar.svelte create mode 100644 ui/src/lib/updateNotice.ts diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 817edb29..323de025 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -6546,6 +6546,18 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-osa-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" +dependencies = [ + "bitflags 2.9.4", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + [[package]] name = "objc2-quartz-core" version = "0.3.2" @@ -6791,6 +6803,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "osakit" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" +dependencies = [ + "objc2", + "objc2-foundation", + "objc2-osa-kit", + "serde", + "serde_json", + "thiserror 2.0.18", +] + [[package]] name = "pango" version = "0.18.3" @@ -10221,6 +10247,39 @@ dependencies = [ "tokio", ] +[[package]] +name = "tauri-plugin-updater" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5cad8ed5948d988e1018ecd31e27cacedbf72ce3fb972940c3e4bf51639e4b" +dependencies = [ + "base64 0.22.1", + "dirs", + "flate2", + "futures-util", + "http", + "infer", + "log", + "minisign-verify", + "osakit", + "percent-encoding", + "reqwest 0.13.2", + "rustls", + "semver", + "serde", + "serde_json", + "tar", + "tauri", + "tauri-plugin", + "tempfile", + "thiserror 2.0.18", + "time", + "tokio", + "url", + "windows-sys 0.60.2", + "zip 4.6.1", +] + [[package]] name = "tauri-runtime" version = "2.10.1" @@ -11294,6 +11353,7 @@ dependencies = [ "holochain_types", "lair_keystore", "log", + "serde", "serde_json", "tauri", "tauri-build", @@ -11309,6 +11369,7 @@ dependencies = [ "tauri-plugin-os", "tauri-plugin-sharesheet", "tauri-plugin-shell", + "tauri-plugin-updater", "tauri-runtime", "tempdir", "url2", @@ -13111,6 +13172,18 @@ dependencies = [ "zstd 0.13.3", ] +[[package]] +name = "zip" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +dependencies = [ + "arbitrary", + "crc32fast", + "indexmap 2.11.1", + "memchr", +] + [[package]] name = "zip" version = "7.2.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4dfaf02d..00b8a92a 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -48,10 +48,16 @@ url2 = "0.0.6" app_dirs2 = "2.5.5" tempdir = "0.3.7" anyhow = "1" +serde = { version = "1", features = ["derive"] } serde_json = "1" uuid = { version = "1.12.0", features = ["v4", "fast-rng"] } base64ct = "=1.7.3" +# In-app updates (app_update.rs). Desktop only; mobile updates through its store. +# Pinned below 2.13, which requires tauri 2.12; this line ships on tauri 2.10. +[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] +tauri-plugin-updater = "~2.12" + [features] default = [] diff --git a/src-tauri/capabilities/main.json b/src-tauri/capabilities/main.json index 991334a1..0fb74ef1 100644 --- a/src-tauri/capabilities/main.json +++ b/src-tauri/capabilities/main.json @@ -22,6 +22,10 @@ "shell:default", "opener:default", "opener:allow-open-url", + { + "identifier": "opener:allow-open-url", + "allow": [{ "url": "market://details?id=com.volla.messages.bundled" }, { "url": "openstore://volla-messages.volla" }] + }, "barcode-scanner:default", "os:allow-platform", "dialog:allow-save", diff --git a/src-tauri/src/app_update.rs b/src-tauri/src/app_update.rs new file mode 100644 index 00000000..578f76cc --- /dev/null +++ b/src-tauri/src/app_update.rs @@ -0,0 +1,94 @@ +//! In-app updates, used to move 1.x users to 2.0. +//! +//! Desktop builds that can replace themselves (Windows, macOS, Linux AppImage) +//! install the update through Tauri's updater, which downloads the build named +//! in the release's `latest.json` and refuses it unless it carries a valid +//! signature from Volla's updater key (the public half is in the desktop +//! config). Everything else — Linux `.deb`, Android, Ubuntu Touch — is updated +//! by its package manager or store, and the UI only links there. +//! +//! Driven from Rust rather than the updater's JS API, so the app needs no extra +//! capabilities, and mobile builds compile without the plugin. + +use serde::Serialize; + +/// How this copy of the app was installed, which decides how it can update. +#[tauri::command] +pub fn install_kind() -> &'static str { + if cfg!(target_os = "android") { + return "android"; + } + if cfg!(target_os = "windows") { + return "windows"; + } + if cfg!(target_os = "macos") { + return "macos"; + } + // The Ubuntu Touch launcher (ut/volla-messages.wrapper) sets this. A click + // package is read-only and updated by OpenStore, so it must never be taken + // for a self-updating build. + if std::env::var_os("VOLLA_LAUNCHED").is_some() { + return "ubuntu-touch"; + } + // Set by the AppImage runtime; the only Linux package that can replace + // itself. Anything else on Linux is treated as a `.deb`. + if std::env::var_os("APPIMAGE").is_some() { + return "appimage"; + } + "deb" +} + +#[derive(Serialize)] +pub struct DesktopUpdate { + version: String, +} + +/// The update the updater would install, if any. +#[cfg(desktop)] +#[tauri::command] +pub async fn check_desktop_update(app: tauri::AppHandle) -> Result, String> { + use tauri_plugin_updater::UpdaterExt; + let update = app + .updater() + .map_err(|e| e.to_string())? + .check() + .await + .map_err(|e| e.to_string())?; + Ok(update.map(|u| DesktopUpdate { version: u.version })) +} + +/// Download, verify and install the update, then restart into it. +/// +/// The caller must have flushed the migration export first: after the restart +/// the new version runs, and a 2.x release can no longer write it. +#[cfg(desktop)] +#[tauri::command] +pub async fn install_desktop_update(app: tauri::AppHandle) -> Result<(), String> { + use tauri_plugin_updater::UpdaterExt; + let update = app + .updater() + .map_err(|e| e.to_string())? + .check() + .await + .map_err(|e| e.to_string())? + .ok_or_else(|| "No update is available".to_string())?; + + log::info!("[update] installing {}", update.version); + update + .download_and_install(|_, _| {}, || {}) + .await + .map_err(|e| e.to_string())?; + app.restart() +} + +#[cfg(mobile)] +#[tauri::command] +pub async fn check_desktop_update() -> Result, String> { + Ok(None) +} + +#[cfg(mobile)] +#[tauri::command] +pub async fn install_desktop_update() -> Result<(), String> { + Err("In-app installation is only available on desktop".to_string()) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c6b9f875..edbe8a41 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,5 +1,6 @@ mod builder; use builder::setup_builder; +mod app_update; mod config; mod migration_export; @@ -19,7 +20,10 @@ pub fn run() { migration_export::read_history_export, migration_export::write_export_image, migration_export::list_export_images, - migration_export::write_image_index + migration_export::write_image_index, + app_update::install_kind, + app_update::check_desktop_update, + app_update::install_desktop_update ]) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_opener::init()) @@ -47,6 +51,10 @@ pub fn run() { .level_for("iroh", log::LevelFilter::Warn) .build(), ); + #[cfg(desktop)] + { + builder = builder.plugin(tauri_plugin_updater::Builder::new().build()); + } #[cfg(mobile)] { builder = builder.plugin(tauri_plugin_sharesheet::init()); diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 51eb420f..37a1efaf 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -33,5 +33,13 @@ "label": "splashscreen" } ] + }, + "plugins": { + "updater": { + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDFFMEQ0NzRDODc0RTlDMEYKUldRUG5FNkhURWNOSHFwc0RhaDl5ajBSQ091dmhkTjhjSWp6bklvV0JoMHkvNmZ1R3VPOE5DZ3gK", + "endpoints": [ + "https://github.com/HelloVolla/volla-messages/releases/latest/download/latest.json" + ] + } } } diff --git a/src-tauri/tauri.desktop.conf.json b/src-tauri/tauri.desktop.conf.json index 51eb420f..37a1efaf 100644 --- a/src-tauri/tauri.desktop.conf.json +++ b/src-tauri/tauri.desktop.conf.json @@ -33,5 +33,13 @@ "label": "splashscreen" } ] + }, + "plugins": { + "updater": { + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDFFMEQ0NzRDODc0RTlDMEYKUldRUG5FNkhURWNOSHFwc0RhaDl5ajBSQ091dmhkTjhjSWp6bklvV0JoMHkvNmZ1R3VPOE5DZ3gK", + "endpoints": [ + "https://github.com/HelloVolla/volla-messages/releases/latest/download/latest.json" + ] + } } } diff --git a/ui/src/lib/UpdateBar.svelte b/ui/src/lib/UpdateBar.svelte new file mode 100644 index 00000000..c8c4491c --- /dev/null +++ b/ui/src/lib/UpdateBar.svelte @@ -0,0 +1,48 @@ + + + diff --git a/ui/src/lib/historyExport.ts b/ui/src/lib/historyExport.ts index a9ca7251..a45f2d0d 100644 --- a/ui/src/lib/historyExport.ts +++ b/ui/src/lib/historyExport.ts @@ -142,22 +142,33 @@ function contentKey(history: HistoryExport): string { /** Archived conversations already read this launch; see `exportHistory`. */ const archivedReadThisLaunch = new Set(); -let running = false; +/** The run in progress, which a second caller waits for instead of starting another. */ +let current: Promise | undefined; /** - * Export the history of every conversation. Never throws, and a second call - * while one is running is skipped rather than queued. + * Export the history of every conversation. Never throws. A call while a run + * is in progress returns that run, so awaiting it — as the in-app update does + * before installing — always waits for a complete export. * * Archived conversations are disabled cells and have to be enabled briefly to * be read, which is visible, so each is read at most once per launch. */ -export async function exportHistory( +export function exportHistory( + relayClient: RelayClient, + conversationStore: ConversationStore, + myPubKeyB64: AgentPubKeyB64, +): Promise { + current ??= runExportHistory(relayClient, conversationStore, myPubKeyB64).finally(() => { + current = undefined; + }); + return current; +} + +async function runExportHistory( relayClient: RelayClient, conversationStore: ConversationStore, myPubKeyB64: AgentPubKeyB64, ): Promise { - if (running) return; - running = true; const started = performance.now(); let written = 0; let unchanged = 0; @@ -240,7 +251,8 @@ export async function exportHistory( ); await exportImages(relayClient, onDisk, myPubKeyB64); - } finally { - running = false; + } catch (e) { + const message = e instanceof Error ? e.message : JSON.stringify(e); + console.error(`${TAG} failed: ${message}`); } } diff --git a/ui/src/lib/updateNotice.ts b/ui/src/lib/updateNotice.ts new file mode 100644 index 00000000..f8a5ac4a --- /dev/null +++ b/ui/src/lib/updateNotice.ts @@ -0,0 +1,169 @@ +import { invoke } from "@tauri-apps/api/core"; +import { getIdentifier, getVersion } from "@tauri-apps/api/app"; +import { openUrl } from "@tauri-apps/plugin-opener"; +import { enqueueNotification } from "$lib/utils"; + +/** + * Tell 1.x users when 2.0 is out, and get them there. + * + * 2.0 runs on a new Holochain version that cannot talk to 1.x, so contacts who + * have updated stop receiving a 1.x user's messages. The app is not blocked; a + * red bar and a daily notification explain it and offer an Update button. + * + * Detection reads the latest *release* (not pre-release) from GitHub's API, + * which, unlike release downloads, allows cross-origin requests from the + * webview. Only a new major version counts. How the button updates depends on + * how the app was installed (`install_kind` in app_update.rs). + */ + +export type InstallKind = "windows" | "macos" | "appimage" | "deb" | "android" | "ubuntu-touch"; + +export interface AvailableUpdate { + version: string; + kind: InstallKind; +} + +const LATEST_RELEASE_API = + "https://api.github.com/repos/HelloVolla/volla-messages/releases/latest"; +const RELEASES_PAGE = "https://github.com/HelloVolla/volla-messages/releases/latest"; +/** Opens F-Droid on the app; Volla's repos and GitHub APKs share one signing key. */ +const FDROID_URL = "market://details?id=com.volla.messages.bundled"; +const OPENSTORE_URL = "openstore://volla-messages.volla"; +const OPENSTORE_WEB_URL = "https://open-store.io/app/volla-messages.volla"; + +/** The Lite app (Android service runtime) has no 2.0 build yet. */ +const LITE_IDENTIFIER = "com.volla.messages"; + +const DAY_MS = 24 * 60 * 60 * 1000; +/** F-Droid repos (and OpenStore) pick up a release on their nightly sync. */ +const STORE_DELAY_MS = DAY_MS; + +const LAST_CHECK_KEY = "UPDATE.LAST_CHECK"; +const LATEST_KEY = "UPDATE.LATEST"; +const LAST_NOTIFIED_KEY = "UPDATE.LAST_NOTIFIED"; +/** Dev only: pretend this version is the latest release, to test the notice. */ +const TEST_VERSION_KEY = "UPDATE.TEST_VERSION"; + +interface LatestRelease { + version: string; + /** Milliseconds since the epoch. */ + publishedAt: number; +} + +function major(version: string): number { + return Number.parseInt(version.replace(/^v/, "").split(".")[0], 10); +} + +function readLocal(key: string): T | undefined { + try { + const raw = localStorage.getItem(key); + return raw ? (JSON.parse(raw) as T) : undefined; + } catch { + return undefined; + } +} + +function writeLocal(key: string, value: unknown): void { + try { + localStorage.setItem(key, JSON.stringify(value)); + } catch { + // Storage can be unavailable; the check simply runs again next time. + } +} + +/** The latest release, from GitHub at most once a day. */ +async function latestRelease(): Promise { + if (import.meta.env.DEV) { + const test = localStorage.getItem(TEST_VERSION_KEY); + if (test) return { version: test, publishedAt: 0 }; + } + + const lastCheck = readLocal(LAST_CHECK_KEY) ?? 0; + const cached = readLocal(LATEST_KEY); + if (cached && Date.now() - lastCheck < DAY_MS) return cached; + + const response = await fetch(LATEST_RELEASE_API, { + headers: { Accept: "application/vnd.github+json" }, + }); + if (!response.ok) return cached; + + const release = await response.json(); + const latest: LatestRelease = { + version: String(release.tag_name ?? "").replace(/^v/, ""), + publishedAt: Date.parse(release.published_at ?? "") || Date.now(), + }; + writeLocal(LAST_CHECK_KEY, Date.now()); + writeLocal(LATEST_KEY, latest); + return latest; +} + +/** A newer major release this installation can be moved to, if there is one. */ +export async function checkForUpdate(): Promise { + try { + if ((await getIdentifier()) === LITE_IDENTIFIER) return undefined; + + const latest = await latestRelease(); + if (!latest || !(major(latest.version) > major(await getVersion()))) return undefined; + + const kind = await invoke("install_kind"); + // Store-updated installs only see the release after the store syncs. + const viaStore = kind === "android" || kind === "ubuntu-touch"; + if (viaStore && Date.now() - latest.publishedAt < STORE_DELAY_MS) return undefined; + + return { version: latest.version, kind }; + } catch (e) { + console.warn("[update] check failed", e); + return undefined; + } +} + +/** A system notification about the update, at most once a day. */ +export async function notifyAboutUpdate(title: string, body: string): Promise { + const lastNotified = readLocal(LAST_NOTIFIED_KEY) ?? 0; + if (Date.now() - lastNotified < DAY_MS) return; + writeLocal(LAST_NOTIFIED_KEY, Date.now()); + await enqueueNotification(title, body); +} + +/** + * Start the update for this kind of installation. + * + * Self-updating desktop builds run `flushExports` first: after the restart the + * 2.0 version runs, and only this one can still write the migration export. + * Resolves for store/download links; for desktop installs the app restarts. + */ +export async function startUpdate( + update: AvailableUpdate, + flushExports: () => Promise, +): Promise { + switch (update.kind) { + case "windows": + case "macos": + case "appimage": + await flushExports(); + await invoke("install_desktop_update"); + return; + case "android": + try { + await openUrl(FDROID_URL); + } catch { + await openUrl(RELEASES_PAGE); + } + return; + case "ubuntu-touch": + try { + await openUrl(OPENSTORE_URL); + } catch { + await openUrl(OPENSTORE_WEB_URL); + } + return; + case "deb": + await openUrl(RELEASES_PAGE); + return; + } +} + +/** Where to send someone whose in-app installation failed. */ +export function openReleasesPage(): Promise { + return openUrl(RELEASES_PAGE); +} diff --git a/ui/src/routes/+layout.svelte b/ui/src/routes/+layout.svelte index 97a1d640..e906a127 100644 --- a/ui/src/routes/+layout.svelte +++ b/ui/src/routes/+layout.svelte @@ -52,6 +52,8 @@ import Dialog from "$lib/Dialog.svelte"; import { exportMigrationData } from "$lib/migrationExport"; import { exportHistory } from "$lib/historyExport"; + import UpdateBar from "$lib/UpdateBar.svelte"; + import { checkForUpdate, notifyAboutUpdate, type AvailableUpdate } from "$lib/updateNotice"; // Holochain client let client: AppClient; @@ -294,6 +296,35 @@ void exportHistory(relayClient, conversationStore, myPubKeyB64); } + // A newer major version: contacts who updated can no longer receive this + // user's messages. Checked on startup and every few hours; GitHub itself is + // asked at most once a day (see updateNotice.ts). + const UPDATE_RECHECK_MS = 6 * 60 * 60 * 1000; + let availableUpdate: AvailableUpdate | undefined; + let updateInterval: ReturnType | undefined; + + async function refreshUpdate() { + availableUpdate = await checkForUpdate(); + if (availableUpdate) { + await notifyAboutUpdate( + $t("common.update_notification_title", { version: availableUpdate.version }), + $t("common.update_notification_body"), + ); + } + } + + /** Everything the next major release imports, written once more before it installs. */ + async function flushExports() { + await exportMigrationData( + relayClient, + conversationStore, + contactStore, + myPubKeyB64, + get(provisionedRelayCellProfileStore).data[myPubKeyB64], + ); + await exportHistory(relayClient, conversationStore, myPubKeyB64); + } + async function setupApp() { initLightDarkModeSwitcher(); await initHolochainClient(); @@ -313,6 +344,9 @@ setTimeout(runHistoryExport, HISTORY_EXPORT_FIRST_DELAY_MS); historyExportInterval = setInterval(runHistoryExport, HISTORY_EXPORT_INTERVAL_MS); + + void refreshUpdate(); + updateInterval = setInterval(refreshUpdate, UPDATE_RECHECK_MS); } onMount(async () => { @@ -324,6 +358,7 @@ document.removeEventListener("visibilitychange", handleVisibilityChange); if (migrationExportTimer !== undefined) clearTimeout(migrationExportTimer); if (historyExportInterval !== undefined) clearInterval(historyExportInterval); + if (updateInterval !== undefined) clearInterval(updateInterval); migrationExportUnsubscribers.forEach((unsubscribe) => unsubscribe()); }); @@ -397,6 +432,9 @@
{#if isClientConnected && isStoresSetup && myProfileExists} + {#if availableUpdate} + + {/if} {:else if isClientConnected && isStoresSetup && !myProfileExists && !isUserCreatingProfile} diff --git a/ui/src/translations/index.ts b/ui/src/translations/index.ts index ea01bdbf..8ebdf925 100644 --- a/ui/src/translations/index.ts +++ b/ui/src/translations/index.ts @@ -22,7 +22,8 @@ type Params = | { count: number } | { date: number } | { public: boolean } - | { existingConversation: boolean }; + | { existingConversation: boolean } + | { version: string }; const config: Config = { fallbackLocale: "en", diff --git a/ui/src/translations/locales/bg.json b/ui/src/translations/locales/bg.json index 520db097..72c570b7 100644 --- a/ui/src/translations/locales/bg.json +++ b/ui/src/translations/locales/bg.json @@ -62,5 +62,11 @@ "welcome_text_1": "В Volla Messages данните ви се предават само на хората, с които споделяте съобщения..", "welcome_text_2": "Лични, криптирани и защитени с ключове, които само вие контролирате..", "what_is_your_name": "Как се казвате?", - "you": "Вие" + "you": "Вие", + "update_bar_text": "Volla Messages {{version}} вече е тук. Контактите, които са обновили, вече не могат да получават вашите съобщения — обновете, за да продължите да чатите.", + "update_now": "Обнови", + "updating": "Обновяване…", + "update_failed": "Обновяването не можа да бъде инсталирано. Изтеглете го от страницата с версиите.", + "update_notification_title": "Volla Messages {{version}} е налично", + "update_notification_body": "Обновете, за да продължите да чатите с контактите, които вече са обновили." } diff --git a/ui/src/translations/locales/da.json b/ui/src/translations/locales/da.json index 3b8ffba4..ee53e07c 100644 --- a/ui/src/translations/locales/da.json +++ b/ui/src/translations/locales/da.json @@ -70,5 +70,11 @@ "welcome_text_1": "Volla Messages deler data kun med de personer, du konverserer med.", "welcome_text_2": "Privat, krypteret og sikret med nøgler, som kun du kontrollerer.", "what_is_your_name": "Hvad hedder du?", - "you": "Du" + "you": "Du", + "update_bar_text": "Volla Messages {{version}} er her. Kontakter, der har opdateret, kan ikke længere modtage dine beskeder — opdater for at blive ved med at chatte.", + "update_now": "Opdater", + "updating": "Opdaterer…", + "update_failed": "Opdateringen kunne ikke installeres. Hent den fra udgivelsessiden.", + "update_notification_title": "Volla Messages {{version}} er tilgængelig", + "update_notification_body": "Opdater for at blive ved med at chatte med kontakter, der allerede har opdateret." } diff --git a/ui/src/translations/locales/de.json b/ui/src/translations/locales/de.json index 209eaa49..0733d87e 100644 --- a/ui/src/translations/locales/de.json +++ b/ui/src/translations/locales/de.json @@ -101,5 +101,11 @@ "welcome_text_1": "Auf Volla Messages werden Ihre Daten nur an die Personen weitergegeben, mit denen Sie Nachrichten teilen.", "welcome_text_2": "Privat, verschlüsselt und gesichert durch Schlüssel, die nur Sie kontrollieren.", "what_is_your_name": "Wie ist Ihr Name?", - "you": "Du" + "you": "Du", + "update_bar_text": "Volla Messages {{version}} ist da. Kontakte, die bereits aktualisiert haben, können deine Nachrichten nicht mehr empfangen — aktualisiere, um weiter zu chatten.", + "update_now": "Aktualisieren", + "updating": "Wird aktualisiert…", + "update_failed": "Das Update konnte nicht installiert werden. Bitte lade es von der Release-Seite herunter.", + "update_notification_title": "Volla Messages {{version}} ist verfügbar", + "update_notification_body": "Aktualisiere, um weiter mit Kontakten zu chatten, die bereits aktualisiert haben." } diff --git a/ui/src/translations/locales/en.json b/ui/src/translations/locales/en.json index 9efcde0a..ee0d1159 100644 --- a/ui/src/translations/locales/en.json +++ b/ui/src/translations/locales/en.json @@ -101,5 +101,11 @@ "welcome_text_1": "On Volla Messages, your data is only shared with the people you message with.", "welcome_text_2": "Private, encrypted and secured by keys only you control.", "what_is_your_name": "What is your name?", - "you": "You" -} \ No newline at end of file + "you": "You", + "update_bar_text": "Volla Messages {{version}} is here. Contacts who have updated can no longer receive your messages — update to keep chatting.", + "update_now": "Update", + "updating": "Updating…", + "update_failed": "The update could not be installed. Please download it from the release page.", + "update_notification_title": "Volla Messages {{version}} is available", + "update_notification_body": "Update to keep chatting with contacts who have already updated." +} diff --git a/ui/src/translations/locales/es.json b/ui/src/translations/locales/es.json index 46032ed6..f0529d1e 100644 --- a/ui/src/translations/locales/es.json +++ b/ui/src/translations/locales/es.json @@ -102,5 +102,11 @@ "welcome_text_1": "En Volla Messages, tus datos sólo se transmiten a las personas con las que compartes mensajes.", "welcome_text_2": "Privado, encriptado y protegido por claves que sólo usted controla.", "what_is_your_name": "¿Cuál es su nombre?", - "you": "Usted" + "you": "Usted", + "update_bar_text": "Ya está aquí Volla Messages {{version}}. Los contactos que han actualizado ya no pueden recibir tus mensajes: actualiza para seguir chateando.", + "update_now": "Actualizar", + "updating": "Actualizando…", + "update_failed": "No se pudo instalar la actualización. Descárgala desde la página de versiones.", + "update_notification_title": "Volla Messages {{version}} está disponible", + "update_notification_body": "Actualiza para seguir chateando con los contactos que ya han actualizado." } diff --git a/ui/src/translations/locales/fr.json b/ui/src/translations/locales/fr.json index e9c6e43b..fe561c36 100644 --- a/ui/src/translations/locales/fr.json +++ b/ui/src/translations/locales/fr.json @@ -62,5 +62,11 @@ "welcome_text_1": "Sur Volla Messages, vos données ne sont communiquées qu'aux personnes avec lesquelles vous partagez des messages..", "welcome_text_2": "Privé, crypté et sécurisé par des clés que vous seul contrôlez.", "what_is_your_name": "Quel est votre nom?", - "you": "Tu" + "you": "Tu", + "update_bar_text": "Volla Messages {{version}} est arrivé. Les contacts qui ont mis à jour ne peuvent plus recevoir vos messages — mettez à jour pour continuer à discuter.", + "update_now": "Mettre à jour", + "updating": "Mise à jour…", + "update_failed": "La mise à jour n'a pas pu être installée. Veuillez la télécharger depuis la page des versions.", + "update_notification_title": "Volla Messages {{version}} est disponible", + "update_notification_body": "Mettez à jour pour continuer à discuter avec les contacts qui ont déjà mis à jour." } diff --git a/ui/src/translations/locales/hi.json b/ui/src/translations/locales/hi.json index 9f5fd443..d926d5ef 100644 --- a/ui/src/translations/locales/hi.json +++ b/ui/src/translations/locales/hi.json @@ -101,5 +101,11 @@ "welcome_text_1": "Volla Messages पर, आपका डेटा केवल उन्हीं लोगों के साथ साझा किया जाता है जिनके साथ आप संदेश भेजते हैं।", "welcome_text_2": "निजी, एन्क्रिप्टेड और केवल आपके नियंत्रण वाली कुंजियों द्वारा सुरक्षित।", "what_is_your_name": "आपका नाम क्या है?", - "you": "आप" + "you": "आप", + "update_bar_text": "Volla Messages {{version}} आ गया है। जिन संपर्कों ने अपडेट कर लिया है, वे अब आपके संदेश प्राप्त नहीं कर सकते — चैट जारी रखने के लिए अपडेट करें।", + "update_now": "अपडेट करें", + "updating": "अपडेट हो रहा है…", + "update_failed": "अपडेट इंस्टॉल नहीं हो सका। कृपया इसे रिलीज़ पेज से डाउनलोड करें।", + "update_notification_title": "Volla Messages {{version}} उपलब्ध है", + "update_notification_body": "पहले से अपडेट कर चुके संपर्कों से चैट जारी रखने के लिए अपडेट करें।" } diff --git a/ui/src/translations/locales/it.json b/ui/src/translations/locales/it.json index 5a765e6d..0b2f0f46 100644 --- a/ui/src/translations/locales/it.json +++ b/ui/src/translations/locales/it.json @@ -102,5 +102,11 @@ "welcome_text_1": "Su Volla Messages, i vostri dati vengono trasmessi solo alle persone con cui condividete i messaggi..", "welcome_text_2": "Privati, crittografati e protetti da chiavi che solo voi potete controllare.", "what_is_your_name": "Qual è il suo nome?", - "you": "Tu" + "you": "Tu", + "update_bar_text": "Volla Messages {{version}} è disponibile. I contatti che hanno aggiornato non possono più ricevere i tuoi messaggi: aggiorna per continuare a chattare.", + "update_now": "Aggiorna", + "updating": "Aggiornamento in corso…", + "update_failed": "Impossibile installare l'aggiornamento. Scaricalo dalla pagina delle release.", + "update_notification_title": "Volla Messages {{version}} è disponibile", + "update_notification_body": "Aggiorna per continuare a chattare con i contatti che hanno già aggiornato." } diff --git a/ui/src/translations/locales/nl.json b/ui/src/translations/locales/nl.json index 8535be9a..8c46d45a 100644 --- a/ui/src/translations/locales/nl.json +++ b/ui/src/translations/locales/nl.json @@ -73,5 +73,11 @@ "welcome_text_1": "Volla Berichten worden je gegevens alleen gedeeld met de mensen met wie je een bericht stuurt.", "welcome_text_2": "Privé, versleuteld en beveiligd met sleutels die alleen jij beheert.", "what_is_your_name": "Wat is je naam?", - "you": "Jij" + "you": "Jij", + "update_bar_text": "Volla Messages {{version}} is er. Contacten die al hebben bijgewerkt, kunnen je berichten niet meer ontvangen — werk bij om te blijven chatten.", + "update_now": "Bijwerken", + "updating": "Bijwerken…", + "update_failed": "De update kon niet worden geïnstalleerd. Download hem van de releasepagina.", + "update_notification_title": "Volla Messages {{version}} is beschikbaar", + "update_notification_body": "Werk bij om te blijven chatten met contacten die al hebben bijgewerkt." } diff --git a/ui/src/translations/locales/no.json b/ui/src/translations/locales/no.json index 5a50b7da..ff9a3a49 100644 --- a/ui/src/translations/locales/no.json +++ b/ui/src/translations/locales/no.json @@ -70,5 +70,11 @@ "welcome_text_1": "Volla Messages deler data kun med personer du kommuniserer med.", "welcome_text_2": "Privat, kryptert og sikret med nøkler som kun du kontrollerer.", "what_is_your_name": "Hvad heter du?", - "you": "Du" + "you": "Du", + "update_bar_text": "Volla Messages {{version}} er her. Kontakter som har oppdatert, kan ikke lenger motta meldingene dine — oppdater for å fortsette å chatte.", + "update_now": "Oppdater", + "updating": "Oppdaterer…", + "update_failed": "Oppdateringen kunne ikke installeres. Last den ned fra utgivelsessiden.", + "update_notification_title": "Volla Messages {{version}} er tilgjengelig", + "update_notification_body": "Oppdater for å fortsette å chatte med kontakter som allerede har oppdatert." } diff --git a/ui/src/translations/locales/ro.json b/ui/src/translations/locales/ro.json index e0f6da5b..54f9019e 100644 --- a/ui/src/translations/locales/ro.json +++ b/ui/src/translations/locales/ro.json @@ -62,5 +62,11 @@ "welcome_text_1": "Pe Volla Messages, datele dvs. sunt transmise numai persoanelor cu care partajați mesaje.", "welcome_text_2": "Privat, criptat și securizat prin chei pe care doar tu le controlezi.", "what_is_your_name": "Care este numele dvs.?", - "you": "Tu" + "you": "Tu", + "update_bar_text": "Volla Messages {{version}} este aici. Contactele care au actualizat nu îți mai pot primi mesajele — actualizează pentru a continua conversațiile.", + "update_now": "Actualizează", + "updating": "Se actualizează…", + "update_failed": "Actualizarea nu a putut fi instalată. Descarc-o de pe pagina de versiuni.", + "update_notification_title": "Volla Messages {{version}} este disponibil", + "update_notification_body": "Actualizează pentru a continua conversațiile cu contactele care au actualizat deja." } diff --git a/ui/src/translations/locales/sk.json b/ui/src/translations/locales/sk.json index 39050962..40cc7db3 100644 --- a/ui/src/translations/locales/sk.json +++ b/ui/src/translations/locales/sk.json @@ -62,5 +62,11 @@ "welcome_text_1": "V službe Volla Messages sa vaše údaje odovzdávajú len ľuďom, s ktorými zdieľate správy..", "welcome_text_2": "Súkromné, zašifrované a zabezpečené kľúčmi, ktoré máte pod kontrolou len vy..", "what_is_your_name": "Ako sa voláte?", - "you": "Vy" + "you": "Vy", + "update_bar_text": "Volla Messages {{version}} je tu. Kontakty, ktoré aktualizovali, už nemôžu prijímať vaše správy — aktualizujte, aby ste mohli ďalej četovať.", + "update_now": "Aktualizovať", + "updating": "Aktualizuje sa…", + "update_failed": "Aktualizáciu sa nepodarilo nainštalovať. Stiahnite si ju zo stránky s vydaniami.", + "update_notification_title": "Volla Messages {{version}} je k dispozícii", + "update_notification_body": "Aktualizujte, aby ste mohli ďalej četovať s kontaktmi, ktoré už aktualizovali." } diff --git a/ui/src/translations/locales/sv.json b/ui/src/translations/locales/sv.json index fe7ee1cb..1ef187cd 100644 --- a/ui/src/translations/locales/sv.json +++ b/ui/src/translations/locales/sv.json @@ -70,5 +70,11 @@ "welcome_text_1": "I Volla Messages delas dina uppgifter endast med de personer som du skickar meddelanden till.", "welcome_text_2": "Privat, krypterat och säkrat med nycklar som bara du kontrollerar.", "what_is_your_name": "Vad heter du?", - "you": "Du" + "you": "Du", + "update_bar_text": "Volla Messages {{version}} är här. Kontakter som har uppdaterat kan inte längre ta emot dina meddelanden — uppdatera för att fortsätta chatta.", + "update_now": "Uppdatera", + "updating": "Uppdaterar…", + "update_failed": "Uppdateringen kunde inte installeras. Ladda ner den från versionssidan.", + "update_notification_title": "Volla Messages {{version}} är tillgänglig", + "update_notification_body": "Uppdatera för att fortsätta chatta med kontakter som redan har uppdaterat." } From d7fd115a7c3ac414b862924020ec23b6172150ad Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Mon, 26 Oct 2026 21:34:53 +0330 Subject: [PATCH 09/11] Feat: In app update process - notify about normal updates and follow the release channel --- src-tauri/Cargo.lock | 1 - src-tauri/Cargo.toml | 1 - src-tauri/capabilities/main.json | 2 +- src-tauri/src/app_update.rs | 58 ++++----- src-tauri/src/lib.rs | 1 - ui/src/lib/UpdateBar.svelte | 52 +++++--- ui/src/lib/updateNotice.ts | 185 ++++++++++++++++++---------- ui/src/routes/+layout.svelte | 28 +++-- ui/src/translations/locales/bg.json | 5 +- ui/src/translations/locales/da.json | 5 +- ui/src/translations/locales/de.json | 5 +- ui/src/translations/locales/en.json | 5 +- ui/src/translations/locales/es.json | 5 +- ui/src/translations/locales/fr.json | 5 +- ui/src/translations/locales/hi.json | 5 +- ui/src/translations/locales/it.json | 5 +- ui/src/translations/locales/nl.json | 5 +- ui/src/translations/locales/no.json | 5 +- ui/src/translations/locales/ro.json | 5 +- ui/src/translations/locales/sk.json | 5 +- ui/src/translations/locales/sv.json | 5 +- 21 files changed, 256 insertions(+), 137 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 323de025..9962fcd3 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -11353,7 +11353,6 @@ dependencies = [ "holochain_types", "lair_keystore", "log", - "serde", "serde_json", "tauri", "tauri-build", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 00b8a92a..d0a118cb 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -48,7 +48,6 @@ url2 = "0.0.6" app_dirs2 = "2.5.5" tempdir = "0.3.7" anyhow = "1" -serde = { version = "1", features = ["derive"] } serde_json = "1" uuid = { version = "1.12.0", features = ["v4", "fast-rng"] } base64ct = "=1.7.3" diff --git a/src-tauri/capabilities/main.json b/src-tauri/capabilities/main.json index 0fb74ef1..e8ea42c4 100644 --- a/src-tauri/capabilities/main.json +++ b/src-tauri/capabilities/main.json @@ -24,7 +24,7 @@ "opener:allow-open-url", { "identifier": "opener:allow-open-url", - "allow": [{ "url": "market://details?id=com.volla.messages.bundled" }, { "url": "openstore://volla-messages.volla" }] + "allow": [{ "url": "market://details?id=com.volla.messages.bundled" }, { "url": "market://details?id=com.volla.messages" }, { "url": "openstore://volla-messages.volla" }] }, "barcode-scanner:default", "os:allow-platform", diff --git a/src-tauri/src/app_update.rs b/src-tauri/src/app_update.rs index 578f76cc..2b3ec626 100644 --- a/src-tauri/src/app_update.rs +++ b/src-tauri/src/app_update.rs @@ -10,8 +10,6 @@ //! Driven from Rust rather than the updater's JS API, so the app needs no extra //! capabilities, and mobile builds compile without the plugin. -use serde::Serialize; - /// How this copy of the app was installed, which decides how it can update. #[tauri::command] pub fn install_kind() -> &'static str { @@ -38,40 +36,43 @@ pub fn install_kind() -> &'static str { "deb" } -#[derive(Serialize)] -pub struct DesktopUpdate { - version: String, -} +/// Where a release's updater manifest lives. Each release, pre-releases +/// included, carries its own `latest.json`, so the app installs exactly the +/// release it found — not whatever GitHub currently calls "latest". +const RELEASE_MANIFEST_URL: &str = + "https://github.com/HelloVolla/volla-messages/releases/download/{tag}/latest.json"; -/// The update the updater would install, if any. -#[cfg(desktop)] -#[tauri::command] -pub async fn check_desktop_update(app: tauri::AppHandle) -> Result, String> { - use tauri_plugin_updater::UpdaterExt; - let update = app - .updater() - .map_err(|e| e.to_string())? - .check() - .await - .map_err(|e| e.to_string())?; - Ok(update.map(|u| DesktopUpdate { version: u.version })) -} - -/// Download, verify and install the update, then restart into it. +/// Download, verify and install the release `tag`, then restart into it. /// /// The caller must have flushed the migration export first: after the restart /// the new version runs, and a 2.x release can no longer write it. #[cfg(desktop)] #[tauri::command] -pub async fn install_desktop_update(app: tauri::AppHandle) -> Result<(), String> { +pub async fn install_desktop_update(app: tauri::AppHandle, tag: String) -> Result<(), String> { use tauri_plugin_updater::UpdaterExt; + + // The tag comes from the UI and becomes part of a URL: a plain version tag + // only, never something that could point the updater elsewhere. + let valid = tag.len() <= 64 + && tag + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_'); + if !valid { + return Err(format!("Refusing unexpected release tag {tag:?}")); + } + let endpoint = tauri::Url::parse(&RELEASE_MANIFEST_URL.replace("{tag}", &tag)) + .map_err(|e| e.to_string())?; + let update = app - .updater() + .updater_builder() + .endpoints(vec![endpoint]) + .map_err(|e| e.to_string())? + .build() .map_err(|e| e.to_string())? .check() .await .map_err(|e| e.to_string())? - .ok_or_else(|| "No update is available".to_string())?; + .ok_or_else(|| format!("Release {tag} offers no update for this installation"))?; log::info!("[update] installing {}", update.version); update @@ -83,12 +84,7 @@ pub async fn install_desktop_update(app: tauri::AppHandle) -> Result<(), String> #[cfg(mobile)] #[tauri::command] -pub async fn check_desktop_update() -> Result, String> { - Ok(None) -} - -#[cfg(mobile)] -#[tauri::command] -pub async fn install_desktop_update() -> Result<(), String> { +pub async fn install_desktop_update(tag: String) -> Result<(), String> { + let _ = tag; Err("In-app installation is only available on desktop".to_string()) } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index edbe8a41..62752f95 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -22,7 +22,6 @@ pub fn run() { migration_export::list_export_images, migration_export::write_image_index, app_update::install_kind, - app_update::check_desktop_update, app_update::install_desktop_update ]) .plugin(tauri_plugin_shell::init()) diff --git a/ui/src/lib/UpdateBar.svelte b/ui/src/lib/UpdateBar.svelte index c8c4491c..f6b64214 100644 --- a/ui/src/lib/UpdateBar.svelte +++ b/ui/src/lib/UpdateBar.svelte @@ -1,21 +1,20 @@ diff --git a/ui/src/lib/updateNotice.ts b/ui/src/lib/updateNotice.ts index f8a5ac4a..271342c4 100644 --- a/ui/src/lib/updateNotice.ts +++ b/ui/src/lib/updateNotice.ts @@ -4,56 +4,64 @@ import { openUrl } from "@tauri-apps/plugin-opener"; import { enqueueNotification } from "$lib/utils"; /** - * Tell 1.x users when 2.0 is out, and get them there. + * Tell users about new versions, and get them there. * - * 2.0 runs on a new Holochain version that cannot talk to 1.x, so contacts who - * have updated stop receiving a 1.x user's messages. The app is not blocked; a - * red bar and a daily notification explain it and offer an Update button. + * Two levels: + * - **Major** (1.x → 2.0): 2.0 runs on a Holochain version that cannot talk to + * 1.x, so contacts who updated stop receiving this user's messages. Red bar + * that cannot be dismissed, and a notification at most once a day. + * - **Normal** (e.g. 1.0.4 → 1.0.5): a neutral bar the user can dismiss until + * the next version, and one notification per version. * - * Detection reads the latest *release* (not pre-release) from GitHub's API, - * which, unlike release downloads, allows cross-origin requests from the - * webview. Only a new major version counts. How the button updates depends on - * how the app was installed (`install_kind` in app_update.rs). + * Channels follow GitHub: an installation whose own version is published as a + * pre-release is on the tester channel and is offered pre-releases too; + * everyone else only sees releases. Promoting a pre-release moves everyone on + * it to the regular channel. + * + * Releases are read from GitHub's API, which (unlike release downloads) allows + * cross-origin requests from the webview, at most once a day. */ export type InstallKind = "windows" | "macos" | "appimage" | "deb" | "android" | "ubuntu-touch"; export interface AvailableUpdate { version: string; + tag: string; + /** A new major version: the network changes, so it is urgent. */ + major: boolean; kind: InstallKind; } -const LATEST_RELEASE_API = - "https://api.github.com/repos/HelloVolla/volla-messages/releases/latest"; -const RELEASES_PAGE = "https://github.com/HelloVolla/volla-messages/releases/latest"; -/** Opens F-Droid on the app; Volla's repos and GitHub APKs share one signing key. */ -const FDROID_URL = "market://details?id=com.volla.messages.bundled"; -const OPENSTORE_URL = "openstore://volla-messages.volla"; -const OPENSTORE_WEB_URL = "https://open-store.io/app/volla-messages.volla"; +interface Release { + tag: string; + version: string; + prerelease: boolean; + /** Milliseconds since the epoch. */ + publishedAt: number; +} -/** The Lite app (Android service runtime) has no 2.0 build yet. */ +const REPO = "HelloVolla/volla-messages"; +const RELEASES_API = `https://api.github.com/repos/${REPO}/releases?per_page=30`; +const releasePage = (tag: string) => `https://github.com/${REPO}/releases/tag/${tag}`; +/** The Lite app runs on the Android service runtime and has no 2.0 build yet. */ const LITE_IDENTIFIER = "com.volla.messages"; +/** Opens F-Droid on this app; Volla's repos and GitHub APKs share one signing key. */ +const fdroidUrl = (identifier: string) => `market://details?id=${identifier}`; +const OPENSTORE_URL = "openstore://volla-messages.volla"; +const OPENSTORE_WEB_URL = "https://open-store.io/app/volla-messages.volla"; const DAY_MS = 24 * 60 * 60 * 1000; -/** F-Droid repos (and OpenStore) pick up a release on their nightly sync. */ +/** F-Droid repos and OpenStore pick a release up on their nightly sync. */ const STORE_DELAY_MS = DAY_MS; const LAST_CHECK_KEY = "UPDATE.LAST_CHECK"; -const LATEST_KEY = "UPDATE.LATEST"; +const RELEASES_KEY = "UPDATE.RELEASES"; const LAST_NOTIFIED_KEY = "UPDATE.LAST_NOTIFIED"; -/** Dev only: pretend this version is the latest release, to test the notice. */ +const NOTIFIED_VERSION_KEY = "UPDATE.NOTIFIED_VERSION"; +const DISMISSED_VERSION_KEY = "UPDATE.DISMISSED_VERSION"; +/** Dev only: pretend this version is released (`"2.0.0"`, or `"1.9.0-pre"` for a pre-release). */ const TEST_VERSION_KEY = "UPDATE.TEST_VERSION"; -interface LatestRelease { - version: string; - /** Milliseconds since the epoch. */ - publishedAt: number; -} - -function major(version: string): number { - return Number.parseInt(version.replace(/^v/, "").split(".")[0], 10); -} - function readLocal(key: string): T | undefined { try { const raw = localStorage.getItem(key); @@ -71,57 +79,108 @@ function writeLocal(key: string, value: unknown): void { } } -/** The latest release, from GitHub at most once a day. */ -async function latestRelease(): Promise { +/** `[major, minor, patch]` of a version such as `1.0.4` or `v2.0.0`. */ +function parts(version: string): number[] { + return version + .replace(/^v/, "") + .split(/[.-]/) + .slice(0, 3) + .map((p) => Number.parseInt(p, 10) || 0); +} + +function compare(a: string, b: string): number { + const [pa, pb] = [parts(a), parts(b)]; + for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] - pb[i]; + return 0; +} + +/** Published releases and pre-releases, from GitHub at most once a day. */ +async function releases(): Promise { if (import.meta.env.DEV) { const test = localStorage.getItem(TEST_VERSION_KEY); - if (test) return { version: test, publishedAt: 0 }; + if (test) { + const prerelease = test.endsWith("-pre"); + const version = test.replace(/-pre$/, ""); + return [{ tag: `v${version}`, version, prerelease, publishedAt: 0 }]; + } } const lastCheck = readLocal(LAST_CHECK_KEY) ?? 0; - const cached = readLocal(LATEST_KEY); + const cached = readLocal(RELEASES_KEY); if (cached && Date.now() - lastCheck < DAY_MS) return cached; - const response = await fetch(LATEST_RELEASE_API, { + const response = await fetch(RELEASES_API, { headers: { Accept: "application/vnd.github+json" }, }); - if (!response.ok) return cached; - - const release = await response.json(); - const latest: LatestRelease = { - version: String(release.tag_name ?? "").replace(/^v/, ""), - publishedAt: Date.parse(release.published_at ?? "") || Date.now(), - }; + if (!response.ok) return cached ?? []; + + // Only app releases: the repository also publishes happ releases (`happ-v…`). + const fetched: Release[] = (await response.json()) + .filter((r: any) => !r.draft && /^v\d/.test(String(r.tag_name))) + .map((r: any) => ({ + tag: String(r.tag_name), + version: String(r.tag_name).replace(/^v/, ""), + prerelease: Boolean(r.prerelease), + publishedAt: Date.parse(r.published_at ?? "") || Date.now(), + })); writeLocal(LAST_CHECK_KEY, Date.now()); - writeLocal(LATEST_KEY, latest); - return latest; + writeLocal(RELEASES_KEY, fetched); + return fetched; } -/** A newer major release this installation can be moved to, if there is one. */ +/** The newest version this installation can move to, if there is one. */ export async function checkForUpdate(): Promise { try { - if ((await getIdentifier()) === LITE_IDENTIFIER) return undefined; + const [identifier, current, all] = await Promise.all([ + getIdentifier(), + getVersion(), + releases(), + ]); + const onTesterChannel = all.find((r) => r.version === current)?.prerelease ?? false; + + const newest = all + .filter((r) => (onTesterChannel || !r.prerelease) && compare(r.version, current) > 0) + .sort((a, b) => compare(b.version, a.version))[0]; + if (!newest) return undefined; - const latest = await latestRelease(); - if (!latest || !(major(latest.version) > major(await getVersion()))) return undefined; + const major = parts(newest.version)[0] > parts(current)[0]; + if (major && identifier === LITE_IDENTIFIER) return undefined; const kind = await invoke("install_kind"); - // Store-updated installs only see the release after the store syncs. + // Store-updated installs only see a release after the store has synced. const viaStore = kind === "android" || kind === "ubuntu-touch"; - if (viaStore && Date.now() - latest.publishedAt < STORE_DELAY_MS) return undefined; + if (viaStore && Date.now() - newest.publishedAt < STORE_DELAY_MS) return undefined; - return { version: latest.version, kind }; + return { version: newest.version, tag: newest.tag, major, kind }; } catch (e) { console.warn("[update] check failed", e); return undefined; } } -/** A system notification about the update, at most once a day. */ -export async function notifyAboutUpdate(title: string, body: string): Promise { - const lastNotified = readLocal(LAST_NOTIFIED_KEY) ?? 0; - if (Date.now() - lastNotified < DAY_MS) return; - writeLocal(LAST_NOTIFIED_KEY, Date.now()); +/** A normal update the user chose to hide stays hidden until a newer one. */ +export function isDismissed(update: AvailableUpdate): boolean { + return !update.major && readLocal(DISMISSED_VERSION_KEY) === update.version; +} + +export function dismiss(update: AvailableUpdate): void { + writeLocal(DISMISSED_VERSION_KEY, update.version); +} + +/** A system notification: daily for a major update, once per version otherwise. */ +export async function notifyAboutUpdate( + update: AvailableUpdate, + title: string, + body: string, +): Promise { + if (update.major) { + const lastNotified = readLocal(LAST_NOTIFIED_KEY) ?? 0; + if (Date.now() - lastNotified < DAY_MS) return; + writeLocal(LAST_NOTIFIED_KEY, Date.now()); + } else { + if (readLocal(NOTIFIED_VERSION_KEY) === update.version) return; + writeLocal(NOTIFIED_VERSION_KEY, update.version); + } await enqueueNotification(title, body); } @@ -129,8 +188,8 @@ export async function notifyAboutUpdate(title: string, body: string): Promise { - return openUrl(RELEASES_PAGE); +export function openReleasePage(update: AvailableUpdate): Promise { + return openUrl(releasePage(update.tag)); } diff --git a/ui/src/routes/+layout.svelte b/ui/src/routes/+layout.svelte index e906a127..f38a8924 100644 --- a/ui/src/routes/+layout.svelte +++ b/ui/src/routes/+layout.svelte @@ -53,7 +53,13 @@ import { exportMigrationData } from "$lib/migrationExport"; import { exportHistory } from "$lib/historyExport"; import UpdateBar from "$lib/UpdateBar.svelte"; - import { checkForUpdate, notifyAboutUpdate, type AvailableUpdate } from "$lib/updateNotice"; + import { + checkForUpdate, + dismiss, + isDismissed, + notifyAboutUpdate, + type AvailableUpdate, + } from "$lib/updateNotice"; // Holochain client let client: AppClient; @@ -296,23 +302,31 @@ void exportHistory(relayClient, conversationStore, myPubKeyB64); } - // A newer major version: contacts who updated can no longer receive this - // user's messages. Checked on startup and every few hours; GitHub itself is - // asked at most once a day (see updateNotice.ts). + // A newer version, major or normal (see updateNotice.ts). Checked on + // startup and every few hours; GitHub itself is asked at most once a day. const UPDATE_RECHECK_MS = 6 * 60 * 60 * 1000; let availableUpdate: AvailableUpdate | undefined; let updateInterval: ReturnType | undefined; async function refreshUpdate() { - availableUpdate = await checkForUpdate(); + const update = await checkForUpdate(); + availableUpdate = update && !isDismissed(update) ? update : undefined; if (availableUpdate) { await notifyAboutUpdate( + availableUpdate, $t("common.update_notification_title", { version: availableUpdate.version }), - $t("common.update_notification_body"), + availableUpdate.major + ? $t("common.update_notification_body") + : $t("common.update_available_notification_body"), ); } } + function dismissUpdate() { + if (availableUpdate) dismiss(availableUpdate); + availableUpdate = undefined; + } + /** Everything the next major release imports, written once more before it installs. */ async function flushExports() { await exportMigrationData( @@ -433,7 +447,7 @@
{#if isClientConnected && isStoresSetup && myProfileExists} {#if availableUpdate} - + {/if} {:else if isClientConnected && isStoresSetup && !myProfileExists && !isUserCreatingProfile} diff --git a/ui/src/translations/locales/bg.json b/ui/src/translations/locales/bg.json index 72c570b7..cef5690a 100644 --- a/ui/src/translations/locales/bg.json +++ b/ui/src/translations/locales/bg.json @@ -68,5 +68,8 @@ "updating": "Обновяване…", "update_failed": "Обновяването не можа да бъде инсталирано. Изтеглете го от страницата с версиите.", "update_notification_title": "Volla Messages {{version}} е налично", - "update_notification_body": "Обновете, за да продължите да чатите с контактите, които вече са обновили." + "update_notification_body": "Обновете, за да продължите да чатите с контактите, които вече са обновили.", + "update_available_text": "Налична е нова версия на Volla Messages ({{version}}).", + "update_later": "По-късно", + "update_available_notification_body": "Обновете за най-новите корекции и подобрения." } diff --git a/ui/src/translations/locales/da.json b/ui/src/translations/locales/da.json index ee53e07c..95304250 100644 --- a/ui/src/translations/locales/da.json +++ b/ui/src/translations/locales/da.json @@ -76,5 +76,8 @@ "updating": "Opdaterer…", "update_failed": "Opdateringen kunne ikke installeres. Hent den fra udgivelsessiden.", "update_notification_title": "Volla Messages {{version}} er tilgængelig", - "update_notification_body": "Opdater for at blive ved med at chatte med kontakter, der allerede har opdateret." + "update_notification_body": "Opdater for at blive ved med at chatte med kontakter, der allerede har opdateret.", + "update_available_text": "En ny version af Volla Messages ({{version}}) er tilgængelig.", + "update_later": "Senere", + "update_available_notification_body": "Opdater for at få de seneste rettelser og forbedringer." } diff --git a/ui/src/translations/locales/de.json b/ui/src/translations/locales/de.json index 0733d87e..802a1a58 100644 --- a/ui/src/translations/locales/de.json +++ b/ui/src/translations/locales/de.json @@ -107,5 +107,8 @@ "updating": "Wird aktualisiert…", "update_failed": "Das Update konnte nicht installiert werden. Bitte lade es von der Release-Seite herunter.", "update_notification_title": "Volla Messages {{version}} ist verfügbar", - "update_notification_body": "Aktualisiere, um weiter mit Kontakten zu chatten, die bereits aktualisiert haben." + "update_notification_body": "Aktualisiere, um weiter mit Kontakten zu chatten, die bereits aktualisiert haben.", + "update_available_text": "Eine neue Version von Volla Messages ({{version}}) ist verfügbar.", + "update_later": "Später", + "update_available_notification_body": "Aktualisiere für die neuesten Fehlerbehebungen und Verbesserungen." } diff --git a/ui/src/translations/locales/en.json b/ui/src/translations/locales/en.json index ee0d1159..7d353dbd 100644 --- a/ui/src/translations/locales/en.json +++ b/ui/src/translations/locales/en.json @@ -107,5 +107,8 @@ "updating": "Updating…", "update_failed": "The update could not be installed. Please download it from the release page.", "update_notification_title": "Volla Messages {{version}} is available", - "update_notification_body": "Update to keep chatting with contacts who have already updated." + "update_notification_body": "Update to keep chatting with contacts who have already updated.", + "update_available_text": "A new version of Volla Messages ({{version}}) is available.", + "update_later": "Later", + "update_available_notification_body": "Update for the latest fixes and improvements." } diff --git a/ui/src/translations/locales/es.json b/ui/src/translations/locales/es.json index f0529d1e..46d07403 100644 --- a/ui/src/translations/locales/es.json +++ b/ui/src/translations/locales/es.json @@ -108,5 +108,8 @@ "updating": "Actualizando…", "update_failed": "No se pudo instalar la actualización. Descárgala desde la página de versiones.", "update_notification_title": "Volla Messages {{version}} está disponible", - "update_notification_body": "Actualiza para seguir chateando con los contactos que ya han actualizado." + "update_notification_body": "Actualiza para seguir chateando con los contactos que ya han actualizado.", + "update_available_text": "Hay una nueva versión de Volla Messages ({{version}}) disponible.", + "update_later": "Más tarde", + "update_available_notification_body": "Actualiza para obtener las últimas correcciones y mejoras." } diff --git a/ui/src/translations/locales/fr.json b/ui/src/translations/locales/fr.json index fe561c36..e725ae32 100644 --- a/ui/src/translations/locales/fr.json +++ b/ui/src/translations/locales/fr.json @@ -68,5 +68,8 @@ "updating": "Mise à jour…", "update_failed": "La mise à jour n'a pas pu être installée. Veuillez la télécharger depuis la page des versions.", "update_notification_title": "Volla Messages {{version}} est disponible", - "update_notification_body": "Mettez à jour pour continuer à discuter avec les contacts qui ont déjà mis à jour." + "update_notification_body": "Mettez à jour pour continuer à discuter avec les contacts qui ont déjà mis à jour.", + "update_available_text": "Une nouvelle version de Volla Messages ({{version}}) est disponible.", + "update_later": "Plus tard", + "update_available_notification_body": "Mettez à jour pour profiter des derniers correctifs et améliorations." } diff --git a/ui/src/translations/locales/hi.json b/ui/src/translations/locales/hi.json index d926d5ef..58aabcc9 100644 --- a/ui/src/translations/locales/hi.json +++ b/ui/src/translations/locales/hi.json @@ -107,5 +107,8 @@ "updating": "अपडेट हो रहा है…", "update_failed": "अपडेट इंस्टॉल नहीं हो सका। कृपया इसे रिलीज़ पेज से डाउनलोड करें।", "update_notification_title": "Volla Messages {{version}} उपलब्ध है", - "update_notification_body": "पहले से अपडेट कर चुके संपर्कों से चैट जारी रखने के लिए अपडेट करें।" + "update_notification_body": "पहले से अपडेट कर चुके संपर्कों से चैट जारी रखने के लिए अपडेट करें।", + "update_available_text": "Volla Messages का नया संस्करण ({{version}}) उपलब्ध है।", + "update_later": "बाद में", + "update_available_notification_body": "नवीनतम सुधारों और बेहतरियों के लिए अपडेट करें।" } diff --git a/ui/src/translations/locales/it.json b/ui/src/translations/locales/it.json index 0b2f0f46..fd1546ee 100644 --- a/ui/src/translations/locales/it.json +++ b/ui/src/translations/locales/it.json @@ -108,5 +108,8 @@ "updating": "Aggiornamento in corso…", "update_failed": "Impossibile installare l'aggiornamento. Scaricalo dalla pagina delle release.", "update_notification_title": "Volla Messages {{version}} è disponibile", - "update_notification_body": "Aggiorna per continuare a chattare con i contatti che hanno già aggiornato." + "update_notification_body": "Aggiorna per continuare a chattare con i contatti che hanno già aggiornato.", + "update_available_text": "È disponibile una nuova versione di Volla Messages ({{version}}).", + "update_later": "Più tardi", + "update_available_notification_body": "Aggiorna per le ultime correzioni e i miglioramenti." } diff --git a/ui/src/translations/locales/nl.json b/ui/src/translations/locales/nl.json index 8c46d45a..fa8dd24a 100644 --- a/ui/src/translations/locales/nl.json +++ b/ui/src/translations/locales/nl.json @@ -79,5 +79,8 @@ "updating": "Bijwerken…", "update_failed": "De update kon niet worden geïnstalleerd. Download hem van de releasepagina.", "update_notification_title": "Volla Messages {{version}} is beschikbaar", - "update_notification_body": "Werk bij om te blijven chatten met contacten die al hebben bijgewerkt." + "update_notification_body": "Werk bij om te blijven chatten met contacten die al hebben bijgewerkt.", + "update_available_text": "Er is een nieuwe versie van Volla Messages ({{version}}) beschikbaar.", + "update_later": "Later", + "update_available_notification_body": "Werk bij voor de nieuwste oplossingen en verbeteringen." } diff --git a/ui/src/translations/locales/no.json b/ui/src/translations/locales/no.json index ff9a3a49..8576ddf6 100644 --- a/ui/src/translations/locales/no.json +++ b/ui/src/translations/locales/no.json @@ -76,5 +76,8 @@ "updating": "Oppdaterer…", "update_failed": "Oppdateringen kunne ikke installeres. Last den ned fra utgivelsessiden.", "update_notification_title": "Volla Messages {{version}} er tilgjengelig", - "update_notification_body": "Oppdater for å fortsette å chatte med kontakter som allerede har oppdatert." + "update_notification_body": "Oppdater for å fortsette å chatte med kontakter som allerede har oppdatert.", + "update_available_text": "En ny versjon av Volla Messages ({{version}}) er tilgjengelig.", + "update_later": "Senere", + "update_available_notification_body": "Oppdater for å få de nyeste rettelsene og forbedringene." } diff --git a/ui/src/translations/locales/ro.json b/ui/src/translations/locales/ro.json index 54f9019e..e5f8006e 100644 --- a/ui/src/translations/locales/ro.json +++ b/ui/src/translations/locales/ro.json @@ -68,5 +68,8 @@ "updating": "Se actualizează…", "update_failed": "Actualizarea nu a putut fi instalată. Descarc-o de pe pagina de versiuni.", "update_notification_title": "Volla Messages {{version}} este disponibil", - "update_notification_body": "Actualizează pentru a continua conversațiile cu contactele care au actualizat deja." + "update_notification_body": "Actualizează pentru a continua conversațiile cu contactele care au actualizat deja.", + "update_available_text": "Este disponibilă o versiune nouă a Volla Messages ({{version}}).", + "update_later": "Mai târziu", + "update_available_notification_body": "Actualizează pentru cele mai noi remedieri și îmbunătățiri." } diff --git a/ui/src/translations/locales/sk.json b/ui/src/translations/locales/sk.json index 40cc7db3..89bf3392 100644 --- a/ui/src/translations/locales/sk.json +++ b/ui/src/translations/locales/sk.json @@ -68,5 +68,8 @@ "updating": "Aktualizuje sa…", "update_failed": "Aktualizáciu sa nepodarilo nainštalovať. Stiahnite si ju zo stránky s vydaniami.", "update_notification_title": "Volla Messages {{version}} je k dispozícii", - "update_notification_body": "Aktualizujte, aby ste mohli ďalej četovať s kontaktmi, ktoré už aktualizovali." + "update_notification_body": "Aktualizujte, aby ste mohli ďalej četovať s kontaktmi, ktoré už aktualizovali.", + "update_available_text": "Je k dispozícii nová verzia Volla Messages ({{version}}).", + "update_later": "Neskôr", + "update_available_notification_body": "Aktualizujte pre najnovšie opravy a vylepšenia." } diff --git a/ui/src/translations/locales/sv.json b/ui/src/translations/locales/sv.json index 1ef187cd..859b3c8b 100644 --- a/ui/src/translations/locales/sv.json +++ b/ui/src/translations/locales/sv.json @@ -76,5 +76,8 @@ "updating": "Uppdaterar…", "update_failed": "Uppdateringen kunde inte installeras. Ladda ner den från versionssidan.", "update_notification_title": "Volla Messages {{version}} är tillgänglig", - "update_notification_body": "Uppdatera för att fortsätta chatta med kontakter som redan har uppdaterat." + "update_notification_body": "Uppdatera för att fortsätta chatta med kontakter som redan har uppdaterat.", + "update_available_text": "En ny version av Volla Messages ({{version}}) finns tillgänglig.", + "update_later": "Senare", + "update_available_notification_body": "Uppdatera för de senaste korrigeringarna och förbättringarna." } From 98ed4811138885259f726df98453f9e349b927ad Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Thu, 11 Jun 2026 17:16:57 +0330 Subject: [PATCH 10/11] Fix: Add a ddefault message type in Message --- dnas/relay/zomes/integrity/relay/src/message.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dnas/relay/zomes/integrity/relay/src/message.rs b/dnas/relay/zomes/integrity/relay/src/message.rs index d1ad8e1f..937dff8a 100644 --- a/dnas/relay/zomes/integrity/relay/src/message.rs +++ b/dnas/relay/zomes/integrity/relay/src/message.rs @@ -1,7 +1,8 @@ use hdi::prelude::*; -#[derive(Serialize, Deserialize, Debug, Clone, SerializedBytes, PartialEq)] +#[derive(Serialize, Deserialize, Debug, Clone, SerializedBytes, PartialEq, Default)] pub enum MessageType { + #[default] User, System, } @@ -21,6 +22,7 @@ pub struct Message { pub content: String, pub bucket: u32, pub images: Vec, + #[serde(default)] pub message_type: MessageType, } From b1e05c08a47aae933a7a0afd8493d770a5e206b2 Mon Sep 17 00:00:00 2001 From: Amirhesp Date: Tue, 27 Oct 2026 17:16:30 +0330 Subject: [PATCH 11/11] Build: bump happ to version 1.0.4 --- .github/scripts/enable-updater-artifacts.mjs | 17 +++ .github/scripts/updater-manifest.mjs | 131 ++++++++++++++++++ .github/workflows/release-tauri-app.yaml | 121 +++++++++++++++- CHANGELOG.md | 4 +- package-lock.json | 6 +- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- .../app/build.gradle.kts | 4 +- .../app/build.gradle.kts | 4 +- src-tauri/src/app_update.rs | 34 ++++- src-tauri/tauri.conf.json | 2 +- src-tauri/tauri.desktop.conf.json | 2 +- .../tauri.mobile.holochain_bundled.conf.json | 2 +- .../tauri.mobile.holochain_service.conf.json | 2 +- ui/package.json | 2 +- 16 files changed, 318 insertions(+), 19 deletions(-) create mode 100644 .github/scripts/enable-updater-artifacts.mjs create mode 100644 .github/scripts/updater-manifest.mjs diff --git a/.github/scripts/enable-updater-artifacts.mjs b/.github/scripts/enable-updater-artifacts.mjs new file mode 100644 index 00000000..346a960b --- /dev/null +++ b/.github/scripts/enable-updater-artifacts.mjs @@ -0,0 +1,17 @@ +// Turn on Tauri's signed updater files for a desktop release build. +// +// Kept out of tauri.desktop.conf.json on purpose: with it on, every +// `tauri build` needs TAURI_SIGNING_PRIVATE_KEY, which only CI has. +// Run after the desktop config has been copied to src-tauri/tauri.conf.json. +import { readFileSync, writeFileSync } from "node:fs"; + +const path = "src-tauri/tauri.conf.json"; +const config = JSON.parse(readFileSync(path, "utf8")); + +if (!config.plugins?.updater?.pubkey) { + throw new Error(`${path} has no updater public key; is it the desktop config?`); +} + +config.bundle = { ...config.bundle, createUpdaterArtifacts: true }; +writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`); +console.log(`Enabled updater artifacts in ${path}`); diff --git a/.github/scripts/updater-manifest.mjs b/.github/scripts/updater-manifest.mjs new file mode 100644 index 00000000..52813cc8 --- /dev/null +++ b/.github/scripts/updater-manifest.mjs @@ -0,0 +1,131 @@ +// Build the `latest.json` the in-app updater reads (src-tauri/src/app_update.rs). +// +// Every release, pre-releases included, carries its own manifest, and the app +// asks for exactly `releases/download//latest.json`. +// +// The updater looks up `--` first and falls back to +// `-` (tauri-plugin-updater 2.12, `get_urls`); the installer part is +// only known when the bundler stamped it into the binary, so both are written. + +import { createHash, createPublicKey, verify } from "node:crypto"; + +/** + * Check a Tauri updater signature the way the app will, so a release signed + * with the wrong key, or changed after signing, fails here and not on users' + * machines. Both values are base64 of minisign text files. + * + * @param {object} input + * @param {string} input.pubkey `plugins.updater.pubkey` from the app config + * @param {string} input.signature contents of the `.sig` file + * @param {Buffer} input.data the signed file + */ +export function verifySignature({ pubkey, signature, data }) { + const key = minisignLine(pubkey, "public key"); + const sig = minisignLine(signature, "signature"); + if (key.length !== 42 || sig.length !== 74) throw new Error("Malformed key or signature"); + + const keyId = key.subarray(2, 10); + if (!sig.subarray(2, 10).equals(keyId)) { + throw new Error( + `Signed with key ${hex(sig.subarray(2, 10))}, but the app trusts ${hex(keyId)}`, + ); + } + + // "ED" signs the BLAKE2b-512 hash of the file (what Tauri writes); "Ed" the file itself. + const algorithm = sig.subarray(0, 2).toString("latin1"); + let message; + if (algorithm === "ED") message = createHash("blake2b512").update(data).digest(); + else if (algorithm === "Ed") message = data; + else throw new Error(`Unknown signature algorithm ${algorithm}`); + + const publicKey = createPublicKey({ + key: { kty: "OKP", crv: "Ed25519", x: key.subarray(10).toString("base64url") }, + format: "jwk", + }); + if (!verify(null, message, publicKey, sig.subarray(10))) { + throw new Error("Signature does not match the file"); + } +} + +/** The binary second line of a minisign key or signature file. */ +function minisignLine(base64Text, what) { + const lines = Buffer.from(base64Text.trim(), "base64").toString("utf8").split("\n"); + if (!lines[0]?.startsWith("untrusted comment:") || !lines[1]) { + throw new Error(`Not a minisign ${what}`); + } + return Buffer.from(lines[1].trim(), "base64"); +} + +const hex = (bytes) => bytes.toString("hex").toUpperCase(); + +/** Signature file name pattern → the manifest keys it serves. */ +const PLATFORMS = [ + { pattern: /_amd64\.AppImage\.sig$/, keys: ["linux-x86_64-appimage", "linux-x86_64"] }, + { pattern: /_aarch64\.AppImage\.sig$/, keys: ["linux-aarch64-appimage", "linux-aarch64"] }, + { pattern: /_aarch64\.app\.tar\.gz\.sig$/, keys: ["darwin-aarch64-app", "darwin-aarch64"] }, + { pattern: /_(x64|x86_64)\.app\.tar\.gz\.sig$/, keys: ["darwin-x86_64-app", "darwin-x86_64"] }, + // NSIS is the default for Windows: it can update in place without admin rights. + { pattern: /_x64-setup\.exe\.sig$/, keys: ["windows-x86_64-nsis", "windows-x86_64"] }, + { pattern: /_x64_[A-Za-z-]+\.msi\.sig$/, keys: ["windows-x86_64-msi"] }, +]; + +/** + * Every platform a desktop release builds; a missing one fails the release. + * The app asks for `windows-x86_64-msi` / `-nsis` by name (app_update.rs), and + * an explicit target has no fallback, so both must be present. + */ +export const REQUIRED = [ + "windows-x86_64", + "windows-x86_64-nsis", + "windows-x86_64-msi", + "darwin-aarch64", + "darwin-x86_64", + "linux-x86_64", + "linux-aarch64", +]; + +/** + * @param {object} input + * @param {string} input.repo `owner/name` + * @param {string} input.tag release tag, e.g. `v1.0.4` + * @param {string} input.notes + * @param {string} input.pubDate RFC 3339 + * @param {{ name: string, signature?: string }[]} input.assets + * release assets; `.sig` assets carry their file contents in `signature` + */ +export function buildManifest({ repo, tag, notes, pubDate, assets }) { + const names = new Set(assets.map((a) => a.name)); + const platforms = {}; + + for (const asset of assets) { + const platform = PLATFORMS.find((p) => p.pattern.test(asset.name)); + if (!platform) continue; + + const target = asset.name.slice(0, -".sig".length); + if (!names.has(target)) { + throw new Error(`${asset.name} has no matching ${target} in the release`); + } + const signature = asset.signature?.trim(); + if (!signature) throw new Error(`${asset.name} is empty`); + + for (const key of platform.keys) { + if (platforms[key]) throw new Error(`Two release assets claim ${key}`); + platforms[key] = { + signature, + url: `https://github.com/${repo}/releases/download/${tag}/${encodeURIComponent(target)}`, + }; + } + } + + const missing = REQUIRED.filter((key) => !platforms[key]); + if (missing.length > 0) { + throw new Error(`No signed update for: ${missing.join(", ")}`); + } + + return { + version: tag.replace(/^v/, ""), + notes, + pub_date: pubDate, + platforms, + }; +} diff --git a/.github/workflows/release-tauri-app.yaml b/.github/workflows/release-tauri-app.yaml index 098e5b0f..1a4d4bce 100644 --- a/.github/workflows/release-tauri-app.yaml +++ b/.github/workflows/release-tauri-app.yaml @@ -188,6 +188,9 @@ jobs: run: | cp -f src-tauri/tauri.desktop.conf.json src-tauri/tauri.conf.json + - name: Enable signed update files + run: node .github/scripts/enable-updater-artifacts.mjs + - name: Set up cross-compilation environment for armv7 if: matrix.arch == 'armv7' run: | @@ -203,9 +206,13 @@ jobs: uses: tauri-apps/tauri-action@v0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} with: releaseId: ${{ needs.create-release.outputs.releaseId }} args: --verbose --features holochain_bundled --target ${{ matrix.target }} + # latest.json is written once, by publish-updater-manifest, after all builds. + includeUpdaterJson: false - name: Upload aarch64 AppImage for Ubuntu Touch job if: matrix.arch == 'aarch64' @@ -381,13 +388,22 @@ jobs: run: | Copy-Item -Path src-tauri\tauri.desktop.conf.json -Destination src-tauri\tauri.conf.json + - name: Enable signed update files + run: node .github/scripts/enable-updater-artifacts.mjs + - name: Build the App uses: tauri-apps/tauri-action@v0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} with: args: --verbose --features holochain_bundled + includeUpdaterJson: false + # Code signing changes the installer bytes, so the updater signatures + # (.sig) the build wrote no longer match. If this step is turned back on, + # "Re-sign update files" below must run after it, before the upload. - name: Sign the App if: false run: | @@ -424,6 +440,26 @@ jobs: CertUtil -hashfile $BUNDLE_OUT_PATH_1 SHA256 CertUtil -hashfile $BUNDLE_OUT_PATH_2 SHA256 + # Sign the final installers for the in-app updater. Runs always: without + # code signing it reproduces what the build wrote; with it, it replaces + # signatures that no longer match. The installers must not change after this. + - name: Re-sign update files + shell: powershell + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + run: | + $ErrorActionPreference = "Stop" + $nsis = @(Get-ChildItem src-tauri\target\release\bundle\nsis\*-setup.exe) + $msi = @(Get-ChildItem src-tauri\target\release\bundle\msi\*.msi) + if ($nsis.Count -eq 0 -or $msi.Count -eq 0) { throw "Expected both an NSIS and an MSI installer to sign" } + $installers = $nsis + $msi + foreach ($installer in $installers) { + npx tauri signer sign --private-key "$env:TAURI_SIGNING_PRIVATE_KEY" --password "$env:TAURI_SIGNING_PRIVATE_KEY_PASSWORD" "$($installer.FullName)" + if ($LASTEXITCODE -ne 0) { throw "Signing $($installer.Name) failed" } + if (-not (Test-Path "$($installer.FullName).sig")) { throw "No signature written for $($installer.Name)" } + } + - name: Upload the Signed App uses: AButler/upload-release-assets@v3.0 with: @@ -485,10 +521,15 @@ jobs: ls -la ls -la src-tauri + - name: Enable signed update files + run: node .github/scripts/enable-updater-artifacts.mjs + - name: Build the App uses: tauri-apps/tauri-action@v0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} @@ -499,6 +540,7 @@ jobs: with: releaseId: ${{ needs.create-release.outputs.releaseId }} args: --verbose --features holochain_bundled --target ${{ matrix.target }} + includeUpdaterJson: false release-tauri-app-ubuntu-touch: name: Build Ubuntu Touch click @@ -558,4 +600,81 @@ jobs: with: files: "ut/build/aarch64-linux-gnu/app/*.click" repo-token: ${{ secrets.GITHUB_TOKEN }} - release-id: ${{ needs.create-release.outputs.releaseId }} \ No newline at end of file + release-id: ${{ needs.create-release.outputs.releaseId }} + # The in-app updater (desktop only) reads releases/download//latest.json. + # Written once, after every desktop build has uploaded its installer and + # updater signature, so parallel jobs cannot overwrite each other's entries. + publish-updater-manifest: + needs: + - create-release + - release-tauri-app-linux + - release-tauri-app-windows + - release-tauri-app-macos + permissions: + contents: write + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Write latest.json to the release + uses: actions/github-script@v7 + env: + RELEASE_ID: ${{ needs.create-release.outputs.releaseId }} + with: + script: | + const fs = require("node:fs"); + const { buildManifest, verifySignature } = await import( + `${process.env.GITHUB_WORKSPACE}/.github/scripts/updater-manifest.mjs` + ); + const { owner, repo } = context.repo; + const release_id = Number(process.env.RELEASE_ID); + const tag = context.ref.replace("refs/tags/", ""); + // The key the shipped app trusts, not whatever the secret holds. + const pubkey = JSON.parse( + fs.readFileSync("src-tauri/tauri.desktop.conf.json", "utf8"), + ).plugins.updater.pubkey; + + const listed = await github.paginate(github.rest.repos.listReleaseAssets, { + owner, repo, release_id, per_page: 100, + }); + const download = async (asset) => { + const { data } = await github.request( + "GET /repos/{owner}/{repo}/releases/assets/{asset_id}", + { owner, repo, asset_id: asset.id, headers: { accept: "application/octet-stream" } }, + ); + return Buffer.from(data); + }; + + const assets = []; + for (const asset of listed) { + if (asset.name === "latest.json") continue; + let signature; + if (asset.name.endsWith(".sig")) { + signature = (await download(asset)).toString("utf8"); + const target = listed.find((a) => `${a.name}.sig` === asset.name); + if (target) { + verifySignature({ pubkey, signature, data: await download(target) }); + core.info(`${target.name}: updater signature valid`); + } + } + assets.push({ name: asset.name, signature }); + } + + const manifest = buildManifest({ + repo: `${owner}/${repo}`, + tag, + notes: `See https://github.com/${owner}/${repo}/releases/tag/${tag}`, + pubDate: new Date().toISOString(), + assets, + }); + core.info(JSON.stringify(manifest, null, 2)); + + for (const old of listed.filter((a) => a.name === "latest.json")) { + await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id }); + } + await github.rest.repos.uploadReleaseAsset({ + owner, repo, release_id, + name: "latest.json", + data: JSON.stringify(manifest, null, 2), + headers: { "content-type": "application/json" }, + }); diff --git a/CHANGELOG.md b/CHANGELOG.md index e57b61d1..bcfdd28f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased -## [1.0.4] - 2026-10-25 +## [1.0.4] - 2026-10-27 +- Fix: Version 1.0.3 could archive active one-to-one and private conversations on its own. This no longer happens. If 1.0.3 archived some of your chats, open your archived conversations and un-archive them; nothing in them was lost. +- Feat: The app now tells you when a new version is available. On Windows, macOS and the Linux AppImage you can install it from inside the app; on Android it opens F-Droid, and on Ubuntu Touch the OpenStore. - Feat: Your message history and the images in your conversations, archived ones included, are now saved too, so they can come with you into the next major update. This happens automatically in the background and only adds new messages and images after the first run. - Fix: The saved copy of your account is now readable only by your own user on Linux and macOS. diff --git a/package-lock.json b/package-lock.json index 24c448ad..406bcfff 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "volla_messages", - "version": "1.0.3", + "version": "1.0.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "volla_messages", - "version": "1.0.3", + "version": "1.0.4", "workspaces": [ "ui", "tests" @@ -9679,7 +9679,7 @@ } }, "ui": { - "version": "1.0.3", + "version": "1.0.4", "dependencies": { "@buildyourwebapp/tauri-plugin-sharesheet": "0.0.1", "@holochain-open-dev/elements": "^0.601.0", diff --git a/package.json b/package.json index 0500b8e2..80269651 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "volla_messages", - "version": "1.0.3", + "version": "1.0.4", "private": true, "workspaces": [ "ui", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 9962fcd3..f5851b82 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -11343,7 +11343,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "volla_messages" -version = "1.0.3" +version = "1.0.4" dependencies = [ "anyhow", "app_dirs2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index d0a118cb..9307fe0c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "volla_messages" -version = "1.0.3" +version = "1.0.4" description = "Volla Messages" authors = ["Tibet Sprague", "Eric Harris-Braun"] license = "" diff --git a/src-tauri/gen/android-holochain_bundled/app/build.gradle.kts b/src-tauri/gen/android-holochain_bundled/app/build.gradle.kts index aa73bde7..5b34fdd1 100644 --- a/src-tauri/gen/android-holochain_bundled/app/build.gradle.kts +++ b/src-tauri/gen/android-holochain_bundled/app/build.gradle.kts @@ -33,8 +33,8 @@ android { applicationId = "com.volla.messages.bundled" minSdk = 27 targetSdk = 34 - versionCode = 1000003 - versionName = "1.0.3" + versionCode = 1000004 + versionName = "1.0.4" // versionCode = tauriProperties.getProperty("tauri.android.versionCode", "1").toInt() // versionName = tauriProperties.getProperty("tauri.android.versionName", "1.0") } diff --git a/src-tauri/gen/android-holochain_service/app/build.gradle.kts b/src-tauri/gen/android-holochain_service/app/build.gradle.kts index fb230f88..00b655fd 100644 --- a/src-tauri/gen/android-holochain_service/app/build.gradle.kts +++ b/src-tauri/gen/android-holochain_service/app/build.gradle.kts @@ -33,8 +33,8 @@ android { applicationId = "com.volla.messages" minSdk = 27 targetSdk = 34 - versionCode = 1000003 - versionName = "1.0.3" + versionCode = 1000004 + versionName = "1.0.4" // versionCode = tauriProperties.getProperty("tauri.android.versionCode", "1").toInt() // versionName = tauriProperties.getProperty("tauri.android.versionName", "1.0") } diff --git a/src-tauri/src/app_update.rs b/src-tauri/src/app_update.rs index 2b3ec626..e89be2e5 100644 --- a/src-tauri/src/app_update.rs +++ b/src-tauri/src/app_update.rs @@ -63,10 +63,14 @@ pub async fn install_desktop_update(app: tauri::AppHandle, tag: String) -> Resul let endpoint = tauri::Url::parse(&RELEASE_MANIFEST_URL.replace("{tag}", &tag)) .map_err(|e| e.to_string())?; - let update = app + let mut builder = app .updater_builder() .endpoints(vec![endpoint]) - .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + if let Some(target) = windows_update_target() { + builder = builder.target(target); + } + let update = builder .build() .map_err(|e| e.to_string())? .check() @@ -82,6 +86,32 @@ pub async fn install_desktop_update(app: tauri::AppHandle, tag: String) -> Resul app.restart() } +/// Which Windows installer to update with: the one this copy came from. +/// +/// The updater would pick it itself if the bundler had stamped the bundle type +/// into the binary, but the CLI we build with (2.5) does not, so it falls back +/// to `windows-x86_64` (the NSIS installer). Running the NSIS installer over an +/// MSI install leaves two copies side by side. The MSI installs per machine +/// under Program Files; our NSIS installer installs per user, never there. +#[cfg(desktop)] +fn windows_update_target() -> Option<&'static str> { + if !cfg!(target_os = "windows") { + return None; + } + let exe = std::env::current_exe().ok()?; + let exe = exe.to_string_lossy().to_lowercase(); + let per_machine = ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"] + .iter() + .filter_map(std::env::var_os) + .map(|dir| dir.to_string_lossy().to_lowercase()) + .any(|dir| !dir.is_empty() && exe.starts_with(&dir)); + Some(if per_machine { + "windows-x86_64-msi" + } else { + "windows-x86_64-nsis" + }) +} + #[cfg(mobile)] #[tauri::command] pub async fn install_desktop_update(tag: String) -> Result<(), String> { diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 37a1efaf..56ec93cb 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "productName": "Volla Messages", "identifier": "com.volla.messages.bundled", - "version": "1.0.3", + "version": "1.0.4", "build": { "beforeBuildCommand": "npm run build -w ui", "devUrl": "http://localhost:1420", diff --git a/src-tauri/tauri.desktop.conf.json b/src-tauri/tauri.desktop.conf.json index 37a1efaf..56ec93cb 100644 --- a/src-tauri/tauri.desktop.conf.json +++ b/src-tauri/tauri.desktop.conf.json @@ -1,7 +1,7 @@ { "productName": "Volla Messages", "identifier": "com.volla.messages.bundled", - "version": "1.0.3", + "version": "1.0.4", "build": { "beforeBuildCommand": "npm run build -w ui", "devUrl": "http://localhost:1420", diff --git a/src-tauri/tauri.mobile.holochain_bundled.conf.json b/src-tauri/tauri.mobile.holochain_bundled.conf.json index 8707090d..96be21c6 100644 --- a/src-tauri/tauri.mobile.holochain_bundled.conf.json +++ b/src-tauri/tauri.mobile.holochain_bundled.conf.json @@ -1,7 +1,7 @@ { "productName": "Volla Messages (Standalone)", "identifier": "com.volla.messages.bundled", - "version": "1.0.3", + "version": "1.0.4", "build": { "beforeBuildCommand": "npm run build -w ui", "devUrl": "http://localhost:1420", diff --git a/src-tauri/tauri.mobile.holochain_service.conf.json b/src-tauri/tauri.mobile.holochain_service.conf.json index 441dee33..84fc190c 100644 --- a/src-tauri/tauri.mobile.holochain_service.conf.json +++ b/src-tauri/tauri.mobile.holochain_service.conf.json @@ -1,7 +1,7 @@ { "productName": "Volla Messages", "identifier": "com.volla.messages", - "version": "1.0.3", + "version": "1.0.4", "build": { "beforeBuildCommand": "npm run build -w ui", "devUrl": "http://localhost:1420", diff --git a/ui/package.json b/ui/package.json index 51c1f1ae..ddaabb02 100644 --- a/ui/package.json +++ b/ui/package.json @@ -1,6 +1,6 @@ { "name": "ui", - "version": "1.0.3", + "version": "1.0.4", "private": true, "scripts": { "start": "vite --clearScreen false",