release: 0.1.3 — the Recent list survives an upgrade

The Updates tab drops the "installs the ... artifact" chip, and the state label
now leads the status row instead of floating right, since the version it used to
sit beside moved into the header.

The file list no longer disappears on upgrade:

- The library already lived in the app data directory, outside the bundle, so an
  in-app update or reinstall never touched `history.json`. What it never had was a
  bridge from the store 0.1 used: that list lived in the webview's own storage,
  which a reinstall does not survive, so the first launch of a newer build showed
  an empty Recent list over files that were all still on disk.
- `history_import` merges those rows once, on the first launch after an upgrade.
  An entry the library already lists keeps its own timestamp, the kind is
  re-derived from the file rather than taken from the older store's guess, and the
  legacy key is dropped only after the merge succeeds so a later upgrade cannot
  resurrect rows the user has since removed.
- `HistoryEntry.kind`/`.at` gained serde defaults, so a row from the older store
  degrades to a usable entry instead of failing the whole import.

Verified on this machine that the legacy `shift.recent` key is still present in the
installed app's webview store, so the import has rows to adopt.

Gates: cargo fmt --check clean, `cargo test --lib` 149 passed / 2 ignored,
`pnpm check` clean, `pnpm test` 38 passed, `pnpm build` ok.
main v0.1.3
mula.liu 2026-10-26 04:02:31 +08:00
parent 15498482fa
commit c98d554a88
17 changed files with 244 additions and 49 deletions

View File

@ -214,7 +214,7 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page
## Capture history library
Every capture, conversion result and received file is written by Rust into one library in the app data directory (`history.json`, capped at 300 entries), so all windows share a single list and a webview cache clear cannot throw it away. The main window's **Recent** card is that library:
Every capture, conversion result and received file is written by Rust into one library in the app data directory (`history.json`, capped at 300 entries), so all windows share a single list and a webview cache clear cannot throw it away. Because it sits outside the bundle, **it survives an update and a reinstall**; the first launch after upgrading also adopts whatever the 0.1 webview had kept in its own store, so a list built before that change is not lost either. The main window's **Recent** card is that library:
- **Search** once the list grows past a few rows; it filters on the file name.
- **Pin** a row to keep it through the capacity limit, a deleted file, and Clear.

View File

@ -214,7 +214,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001
## 截图历史库
每一次截图、每一个转换结果、每一个收到的文件,都由 Rust 写入应用数据目录中的同一个历史库(`history.json`,上限 300 条),因此所有窗口共用一份列表,清理 Webview 缓存也不会丢失。主窗口的「最近使用」卡片就是这个历史库:
每一次截图、每一个转换结果、每一个收到的文件,都由 Rust 写入应用数据目录中的同一个历史库(`history.json`,上限 300 条),因此所有窗口共用一份列表,清理 Webview 缓存也不会丢失。这份文件在应用包之外,**升级与重装都不会清空它**;升级后的首次启动还会接管 0.1 版本留在 Webview 自己的存储里的旧记录,因此那条改动之前积累的列表也不会丢。主窗口的「最近使用」卡片就是这个历史库:
- 列表超过几行后出现**搜索**框,按文件名过滤。
- **收藏**某一行,即可在容量上限、文件被删除、以及「清空」之后仍然保留。

View File

@ -266,13 +266,13 @@ test, which is the proof that the check is real and not a pass-through.
Checked against the live `releases` branch of this repository:
Version **0.1.2**, checked by downloading each artifact back from the raw endpoint rather
Version **0.1.3**, checked by downloading each artifact back from the raw endpoint rather
than trusting the local copy:
| Key | Artifact | Verified from the remote |
| --- | --- | --- |
| `macos` | `Shift-macOS-universal.dmg` (55,509,300 B) | bytes downloaded, SHA256 matches the manifest |
| `windows` | `Shift-Setup-0.1.2-win-x64.exe` (24,524,080 B) | bytes downloaded, SHA256 matches the manifest |
| `macos` | `Shift-macOS-universal.dmg` (55,528,662 B) | bytes downloaded, SHA256 matches the manifest |
| `windows` | `Shift-Setup-0.1.3-win-x64.exe` (24,517,835 B) | bytes downloaded, SHA256 matches the manifest |
| `windows-arm64` | not published | by choice — see "Supported release targets" |
| `linux` | not published | by choice: Linux is a build target here, not a shipped product |

View File

@ -98,6 +98,12 @@ names what is still missing.
a busy image left the old copy running instead of leaving Shift closed. The Windows
script is cross-built and its `${Silent}` gate compiles, but the restart itself needs
real hardware. See "Applying an update" in `docs/RELEASE.md`.
- An update no longer costs the user the Recent list. That library lives in the app data
directory rather than in the bundle, and since the move out of the webview's own storage
it had no bridge from the old store: `history_import` adopts those rows on the first
launch after an upgrade, re-deriving each entry's kind from the file rather than trusting
the older store's guess, then the legacy key is dropped so a later upgrade cannot
resurrect rows the user has since removed.
- Signed and notarized macOS package: pending (builds are signed with a local identity).
- Signed Windows installer: pending.
- Manifest signing is done. `scripts/release-key.py` mints the release key,

View File

@ -1,7 +1,7 @@
{
"name": "shift",
"private": true,
"version": "0.1.2",
"version": "0.1.3",
"type": "module",
"scripts": {
"prepare:ocr": "bash scripts/prepare-ocr-assets.sh",

2
src-tauri/Cargo.lock generated
View File

@ -3899,7 +3899,7 @@ dependencies = [
[[package]]
name = "shift"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"base64 0.22.1",
"calamine",

View File

@ -1,6 +1,6 @@
[package]
name = "shift"
version = "0.1.2"
version = "0.1.3"
description = "A radial file utility with screenshot, recording and OCR."
authors = ["Shift Contributors"]
edition = "2021"

View File

@ -26,8 +26,12 @@ const CAPACITY: usize = 300;
pub struct HistoryEntry {
pub path: String,
/// "image" | "video" | "text" | "file", matching the editor's own kinds.
/// Defaults so a row imported from an older store, which may not have recorded
/// it, still parses; every writer re-derives it from the path anyway.
#[serde(default)]
pub kind: String,
/// Milliseconds since the epoch, as the webview already reports them.
#[serde(default)]
pub at: i64,
/// Pinned entries survive both the capacity limit and a missing file.
#[serde(default)]
@ -109,6 +113,29 @@ fn publish(app: &AppHandle, entries: Vec<HistoryEntry>) {
let _ = app.emit("history://changed", entries);
}
/// Merge imported rows into the library. An entry the library already lists keeps
/// its own timestamp, so an import cannot make yesterday's file look new.
///
/// The kind is re-derived from the path rather than taken from the store being
/// imported from: that field is the importer's own opinion about a file it may not
/// have been able to read, and the current classifier is the one the editor uses.
fn merge(existing: Vec<HistoryEntry>, incoming: Vec<HistoryEntry>) -> Vec<HistoryEntry> {
let mut merged = existing;
for entry in incoming {
if entry.path.trim().is_empty() {
continue;
}
if merged.iter().any(|have| have.path == entry.path) {
continue;
}
merged.push(HistoryEntry {
kind: crate::files::editor_kind(Path::new(&entry.path)).to_string(),
..entry
});
}
tidy(merged)
}
/// Record files that just became available. Called by the result pipeline rather
/// than by whichever window happens to be open.
pub fn record(app: &AppHandle, paths: &[String]) {
@ -192,6 +219,25 @@ pub async fn history_remove(app: AppHandle, path: String) -> Result<Vec<HistoryE
.map_err(|error| error.to_string())?
}
/// Adopt a list a previous version kept somewhere else. Until 0.1 the library lived
/// in the webview's own storage, which a reinstall does not survive, so the first
/// launch of a newer build would otherwise show an empty list over files that are
/// all still on disk.
#[tauri::command]
pub async fn history_import(
app: AppHandle,
entries: Vec<HistoryEntry>,
) -> Result<Vec<HistoryEntry>, String> {
tauri::async_runtime::spawn_blocking(move || {
let entries = merge(snapshot(&app), entries);
write(&app, &entries)?;
publish(&app, entries.clone());
Ok(entries)
})
.await
.map_err(|error| error.to_string())?
}
#[tauri::command]
pub async fn history_clear(app: AppHandle) -> Result<Vec<HistoryEntry>, String> {
tauri::async_runtime::spawn_blocking(move || {
@ -222,6 +268,60 @@ mod tests {
}
}
#[test]
fn a_row_from_the_older_webview_store_parses() {
// What 0.1.0 kept in localStorage: a path, a kind it guessed, and a
// timestamp. No pin, since that column did not exist yet.
let here = real_path();
let json = format!(r#"[{{"path":"{here}","kind":"image","at":1730000000000}}]"#);
let legacy: Vec<HistoryEntry> = serde_json::from_str(&json).unwrap();
assert_eq!(legacy.len(), 1);
assert!(!legacy[0].pinned);
let merged = merge(vec![], legacy);
assert_eq!(merged.len(), 1);
// The importer's guess is replaced by what this build's classifier says.
assert_eq!(merged[0].kind, "file");
assert_eq!(merged[0].at, 1_730_000_000_000);
}
fn an_import_adds_unknown_paths_and_never_refreshes_a_timestamp() {
let here = real_path();
// The folder holding the test binary: a second path that really exists,
// since a tidy pass drops anything that does not.
let other = std::env::current_exe()
.unwrap()
.parent()
.unwrap()
.to_string_lossy()
.to_string();
let merged = merge(
vec![entry(&here, 500, false)],
vec![
// Same file, older stamp: the library's own row wins.
entry(&here, 100, false),
entry(&other, 400, false),
],
);
assert_eq!(merged.len(), 2, "the imported path should have landed");
let kept = merged.iter().find(|e| e.path == here).unwrap();
assert_eq!(kept.at, 500, "an import must not refresh a timestamp");
}
#[test]
fn an_import_drops_entries_that_point_at_nothing() {
let missing = format!("/nonexistent/shift-import-{}.png", std::process::id());
let merged = merge(vec![], vec![entry(&missing, 100, false)]);
assert!(merged.is_empty());
}
#[test]
fn an_import_keeps_a_pinned_flag_from_the_older_store() {
let here = real_path();
let merged = merge(vec![], vec![entry(&here, 100, true)]);
assert_eq!(merged.len(), 1);
assert!(merged[0].pinned);
}
#[test]
fn entries_kind_follows_the_editor_classification() {
assert_eq!(HistoryEntry::new("/x/a.png").kind, "image");

View File

@ -391,6 +391,7 @@ pub fn run() {
history::history_record,
history::history_set_pinned,
history::history_remove,
history::history_import,
history::history_clear,
settings::get_app_settings,
settings::set_output_directory,

View File

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Shift",
"version": "0.1.2",
"version": "0.1.3",
"identifier": "app.nex.shift",
"build": {
"beforeDevCommand": "pnpm dev",

View File

@ -540,7 +540,7 @@ export function MainWindow() {
.catch(() => setHotkeys(null));
// Rust prunes entries whose file is gone as it reads the library, so there is
// no separate sweep to run here.
void history.list().then(setRecent).catch(() => undefined);
void history.adopt().then(setRecent).catch(() => undefined);
// Settings are loaded once when the main window starts.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

View File

@ -68,8 +68,6 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P
} = useUpdateFlow();
const verified = status?.state === "ready";
// Rust reports the key it resolved; the panel only repeats it.
const artifactKey = status?.artifactKey ?? "";
const available = status?.state === "available" || verified;
const failed = status?.state === "error" || status?.state === "unavailable";
@ -92,15 +90,6 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P
) : (
<span className="update-system-pending">{t("updateSystemPending")}</span>
)}
{artifactKey ? (
<span className="update-system-key">
{t("updateSystemArtifact", { key: artifactKey })}
</span>
) : status && status.state === "unavailable" ? (
<span className="update-system-key is-unknown">
{t("updateSystemArtifactUnknown")}
</span>
) : null}
</div>
<div className="update-meta-line">
<Rss size={13} />
@ -133,15 +122,6 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P
</div>
<div className="update-status-row">
{available && status ? (
<span className="update-arrow">
<span className="update-new">
<Sparkle size={11} />
{status.availableVersion}
</span>
<small>{status.date}</small>
</span>
) : null}
<span className={`update-state is-${status?.state ?? "idle"}`}>
{status
? t(
@ -155,6 +135,15 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P
)
: t("updateIdle")}
</span>
{available && status ? (
<span className="update-arrow">
<span className="update-new">
<Sparkle size={11} />
{status.availableVersion}
</span>
<small>{status.date}</small>
</span>
) : null}
</div>
{status?.notes ? <p className="update-notes">{status.notes}</p> : null}

View File

@ -200,8 +200,6 @@ const messages: Record<Lang, Record<string, string>> = {
updateFeedNone: "Not configured for this build",
updateSystem: "This machine",
updateSystemPending: "Reading operating system…",
updateSystemArtifact: "Installs the \u201c{key}\u201d artifact",
updateSystemArtifactUnknown: "This release names no artifact for this machine",
updateIdle: "Not checked yet",
updateAvailable: "Update available",
updateCurrent: "Up to date",
@ -471,8 +469,6 @@ const messages: Record<Lang, Record<string, string>> = {
updateFeedNone: "当前构建未配置更新源",
updateSystem: "本机",
updateSystemPending: "正在读取系统信息…",
updateSystemArtifact: "将安装「{key}」产物",
updateSystemArtifactUnknown: "本次发布没有为本机准备产物",
updateIdle: "尚未检查",
updateAvailable: "发现新版本",
updateCurrent: "已是最新版本",

View File

@ -3,9 +3,11 @@ import { listen } from "@tauri-apps/api/event";
import { invoke } from "@tauri-apps/api/core";
import {
announceRecentChange,
clearLegacyRecentItems,
getLocalRecentItems,
type RecentItem,
setLocalRecentItems,
takeLegacyRecentItems,
} from "./utils";
/**
@ -31,6 +33,25 @@ export const history = {
return request<RecentItem[]>("history_list");
},
/**
* Read the library, adopting the rows a 0.1 webview kept for itself if any are
* waiting. Rust merges them, so this is safe to call more than once and cannot
* reorder or re-date what the library already lists.
*/
async adopt(): Promise<RecentItem[]> {
if (!isTauri()) return getLocalRecentItems();
const legacy = takeLegacyRecentItems();
if (legacy.length === 0) return request<RecentItem[]>("history_list");
try {
const merged = await request<RecentItem[]>("history_import", { entries: legacy });
// Only drop the old store once its rows are safe in the library.
clearLegacyRecentItems();
return merged;
} catch {
return request<RecentItem[]>("history_list");
}
},
/** Record paths that just became available, e.g. an editor save. */
async record(paths: string[]): Promise<RecentItem[]> {
const usable = paths.filter(Boolean);

View File

@ -0,0 +1,64 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { getLocalRecentItems, takeLegacyRecentItems, clearLegacyRecentItems } from "./utils.ts";
/** Minimal store stand-in, installed before the module reads it. */
function withStore(items: Record<string, string | null>, run: () => void) {
const store = new Map(Object.entries(items));
const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
Object.defineProperty(globalThis, "localStorage", {
configurable: true,
value: {
getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => void store.set(key, value),
removeItem: (key: string) => void store.delete(key),
},
});
try {
run();
} finally {
if (previous) Object.defineProperty(globalThis, "localStorage", previous);
else delete (globalThis as Record<string, unknown>).localStorage;
}
}
test("an empty store yields nothing", () => {
withStore({}, () => {
assert.deepEqual(takeLegacyRecentItems(), []);
assert.deepEqual(getLocalRecentItems(), []);
});
});
test("the 0.1 rows are read whole, including paths outside the eight it displayed", () => {
const rows = JSON.stringify([
{ path: "/tmp/a.png", kind: "image", at: 5 },
{ path: "/tmp/b.pdf", kind: "file", at: 4 },
]);
withStore({ "shift.recent": rows }, () => {
assert.deepEqual(takeLegacyRecentItems(), [
{ path: "/tmp/a.png", kind: "image", at: 5 },
{ path: "/tmp/b.pdf", kind: "file", at: 4 },
]);
});
});
test("clearing the legacy key makes the handoff a one-shot", () => {
withStore({ "shift.recent": JSON.stringify([{ path: "/tmp/a.png", kind: "image", at: 5 }]) }, () => {
assert.equal(takeLegacyRecentItems().length, 1);
clearLegacyRecentItems();
assert.deepEqual(takeLegacyRecentItems(), []);
});
});
test("junk in the store is ignored rather than imported", () => {
withStore({ "shift.recent": "[null,{\"path\":\"\"},{\"path\":\"/tmp/ok.png\",\"at\":1}]" }, () => {
assert.deepEqual(takeLegacyRecentItems(), [{ path: "/tmp/ok.png", at: 1 }]);
});
withStore({ "shift.recent": "{not json" }, () => {
assert.deepEqual(takeLegacyRecentItems(), []);
});
withStore({ "shift.recent": "{\"path\":\"/tmp/a.png\"}" }, () => {
assert.deepEqual(takeLegacyRecentItems(), []);
});
});

View File

@ -130,6 +130,39 @@ export function setLocalRecentItems(items: RecentItem[]) {
announceRecentChange();
}
/**
* Rows the 0.1 webview wrote for itself, before Rust owned the library.
*
* That list lived in `localStorage`, which a reinstall does not survive, so the
* first launch of a newer build shows an empty Recent list even though every file
* it names is still on disk. Read it once, hand it to Rust, then drop the key: the
* store keeps no authority after that, and dropping it means a later upgrade cannot
* resurrect rows the user has since removed.
*/
export function takeLegacyRecentItems(): RecentItem[] {
try {
const stored = localStorage.getItem(RECENT_KEY);
if (!stored) return [];
const parsed = JSON.parse(stored);
if (!Array.isArray(parsed)) return [];
const items = parsed.filter(
(entry: RecentItem) => typeof entry?.path === "string" && entry.path.length > 0,
);
return items;
} catch {
return [];
}
}
/** Forget the legacy key once its rows are safe in the Rust library. */
export function clearLegacyRecentItems() {
try {
localStorage.removeItem(RECENT_KEY);
} catch {
// A store we cannot clear only risks a second harmless import.
}
}
/** Notify listeners in this window; other windows hear the Rust broadcast. */
export function announceRecentChange() {
window.dispatchEvent(new Event(RECENT_EVENT));

View File

@ -2375,20 +2375,6 @@ kbd {
font-weight: 620;
}
.update-system-key {
padding: 2px 7px;
border-radius: 999px;
color: #12703f;
background: rgba(26, 162, 96, 0.1);
font-size: 10.5px;
font-weight: 620;
}
.update-system-key.is-unknown {
color: #a3401b;
background: rgba(242, 106, 51, 0.12);
}
.home-main {
position: relative;
z-index: 2;
@ -4501,7 +4487,6 @@ body[data-view="radial"] .share-backdrop {
}
.update-state {
margin-left: auto;
font-size: 12px;
font-weight: 600;
color: rgba(91, 55, 35, 0.6);