Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(sessions): preserve ambiguous legacy titles during upgrade (#1848)
ShawTimc099b6a4cdb4
diff --git a/crates/host-core/src/db/session_title_source_migration.rs b/crates/host-core/src/db/session_title_source_migration.rsindex 0cc485c8e..0970ea696 100644--- a/crates/host-core/src/db/session_title_source_migration.rs+++ b/crates/host-core/src/db/session_title_source_migration.rs@@ -12,24 +12,12 @@ fn migrate_v22_to_v23_tx(tx: &Transaction<'_>) -> Result<()> {"ALTER TABLE sessions ADD COLUMN title_source TEXT NOT NULL DEFAULT 'legacy'CHECK (title_source IN ('legacy', 'default', 'manual', 'generated'));",)?;- // Older releases stored default and manually-entered titles in the- // same column. Preserve the distinction where it is observable: only- // known placeholders remain eligible for automatic replacement; every- // other pre-existing title is treated as manual. The list mirrors- // `sessions::PLACEHOLDER_TITLES` and covers the localized- // `chat.untitledTask` / `nav.newChat` labels the renderer writes.- tx.execute(- "UPDATE sessions SET title_source = CASE- WHEN title IN ('', 'New task', 'New chat', '新建任务', '新对话',- '新建任務', '新對話', '새 작업', '새 채팅',- 'Tarefa sem título', 'Nova conversa',- 'Yeni görev', 'Yeni sohbet', 'Neue Aufgabe',- 'Nouvelle tâche', 'Nueva tarea', 'Neuer Chat',- 'Nuevo chat', 'Nouvelle discussion') THEN 'default'- ELSE 'manual'- END",- [],- )?;+ // Historical v22 sessions lack provenance metadata to distinguish an+ // untouched default placeholder from a deliberate manual rename to the+ // same text (e.g. `new task`). All pre-existing titles remain `legacy`,+ // safely protecting them from automatic replacement by first-prompt+ // title derivation or title plugins. Newly created sessions after+ // upgrade set `default` or `manual` as appropriate.}tx.pragma_update(None, "user_version", 23i64)?;Ok(())diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rsindex 8f5ed4f1e..74e57989a 100644--- a/crates/host-core/src/db/tests.rs+++ b/crates/host-core/src/db/tests.rs@@ -122,18 +122,35 @@ fn v18_database_migrates_session_thinking_omit() {assert!(sql.contains("'omit'"), "{sql}");}+/// Historical v22 databases lack provenance metadata to distinguish whether+/// a title was an untouched placeholder or a deliberate manual rename to that+/// same text. Schema v23 leaves pre-existing sessions classified as `legacy`+/// with their original titles preserved, safely protecting deliberate renames+/// (such as lowercase "new task") from being overwritten by subsequent prompts.#[test]fn v22_database_migrates_session_title_sources_without_losing_titles() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("pi.sqlite");- let (default_id, localized_id, manual_id) = {+ let (default_id, lowercase_id, renamed_v22_id, manual_id) = {let db = Database::open(&path).unwrap();+ // 1. Untouched session created with the default placeholder.let default_session =crate::sessions::create_session(&db, None, None, None, None, None).unwrap();- // A v22 install wrote the active locale's placeholder into the title.- let localized_session =- crate::sessions::create_session(&db, Some("새 작업".into()), None, None, None, None)+ // 2. Untouched session created with the lowercase placeholder.+ let lowercase_session =+ crate::sessions::create_session(&db, Some("new task".into()), None, None, None, None).unwrap();+ // 3. Session that will be renamed while the fixture is at v22.+ let renamed_session = crate::sessions::create_session(+ &db,+ Some("Initial task name".into()),+ None,+ None,+ None,+ None,+ )+ .unwrap();+ // 4. Ordinary manual title.let manual_session = crate::sessions::create_session(&db,Some("A title chosen by the user".into()),@@ -143,38 +160,158 @@ fn v22_database_migrates_session_title_sources_without_losing_titles() {None,).unwrap();++ // Downgrade fixture to schema v22 (no title_source column).db.conn().execute_batch("ALTER TABLE sessions DROP COLUMN title_source;").unwrap();db.conn().pragma_update(None, "user_version", 22).unwrap();- (default_session.id, localized_session.id, manual_session.id)+ // Use the historical title-only rename: v22 has no title_source column.+ db.conn()+ .execute(+ "UPDATE sessions SET title = 'new task' WHERE id = ?1",+ params![renamed_session.id],+ )+ .unwrap();+ (+ default_session.id,+ lowercase_session.id,+ renamed_session.id,+ manual_session.id,+ )};+ // Reopen walks the real v22 -> v23 migration.let db = Database::open(&path).unwrap();assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);assert!(migration_backup_path(&path, 22).exists());- let sources: (String, String, String) = db++ let sources: (String, String, String, String) = db.conn().query_row("SELECT(SELECT title_source FROM sessions WHERE id = ?1),(SELECT title_source FROM sessions WHERE id = ?2),- (SELECT title_source FROM sessions WHERE id = ?3)",- params![default_id, localized_id, manual_id],- |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ (SELECT title_source FROM sessions WHERE id = ?3),+ (SELECT title_source FROM sessions WHERE id = ?4)",+ params![default_id, lowercase_id, renamed_v22_id, manual_id],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),).unwrap();assert_eq!(sources,- ("default".into(), "default".into(), "manual".into())+ (+ "legacy".into(),+ "legacy".into(),+ "legacy".into(),+ "legacy".into()+ ));++ // Stored titles are preserved exactly as they were in v22.+ let titles: (String, String, String) = db+ .conn()+ .query_row(+ "SELECT+ (SELECT title FROM sessions WHERE id = ?1),+ (SELECT title FROM sessions WHERE id = ?2),+ (SELECT title FROM sessions WHERE id = ?3)",+ params![lowercase_id, renamed_v22_id, manual_id],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .unwrap();+ assert_eq!(titles.0, "new task");+ assert_eq!(titles.1, "new task");+ assert_eq!(titles.2, "A title chosen by the user");++ // Because legacy rows are protected, automatic derivation refuses to overwrite them.+ assert!(!crate::sessions::derive_session_title(&db, &renamed_v22_id, "Fix the login").unwrap());+ assert_eq!(+ crate::sessions::get_session(&db, &renamed_v22_id)+ .unwrap()+ .unwrap()+ .summary+ .title,+ "new task"+ );++ // Automatic title plugin CAS write also refuses legacy rows.+ assert!(!crate::sessions::set_automatic_session_title(+ &db,+ &renamed_v22_id,+ "new task",+ "Plugin generated title",+ )+ .unwrap());+ assert_eq!(+ crate::sessions::get_session(&db, &renamed_v22_id)+ .unwrap()+ .unwrap()+ .summary+ .title,+ "new task"+ );++ // Newly created sessions after upgrade correctly set default or manual.+ let new_default = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ assert_eq!(+ db.conn()+ .query_row(+ "SELECT title_source FROM sessions WHERE id = ?1",+ params![new_default.id],+ |row| row.get::<_, String>(0)+ )+ .unwrap(),+ "default"+ );+ assert!(crate::sessions::derive_session_title(&db, &new_default.id, "New turn title").unwrap());+ assert_eq!(+ crate::sessions::get_session(&db, &new_default.id)+ .unwrap()+ .unwrap()+ .summary+ .title,+ "New turn title"+ );+}++#[test]+fn manual_placeholder_title_is_never_overwritten_after_upgrade() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ let session_id = {+ let db = Database::open(&path).unwrap();+ let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ // The user explicitly renamed the session to a placeholder title like "New task".+ assert!(crate::sessions::rename_session(&db, &session.id, "New task").unwrap());+ // Stamp as schema v23, simulating a database that already migrated past v22.+ db.conn().pragma_update(None, "user_version", 23).unwrap();+ session.id+ };++ // Reopen walks the real v23 -> v24 upgrade path.+ let db = Database::open(&path).unwrap();+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);+ let (title, source): (String, String) = db+ .conn()+ .query_row(+ "SELECT title, title_source FROM sessions WHERE id = ?1",+ params![session_id],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .unwrap();+ assert_eq!(source, "manual");+ assert_eq!(title, "New task");++ // The user-selected title must not be overwritten on the next prompt.+ assert!(!crate::sessions::derive_session_title(&db, &session_id, "Fix the login").unwrap());assert_eq!(- crate::sessions::get_session(&db, &manual_id)+ crate::sessions::get_session(&db, &session_id).unwrap().unwrap().summary.title,- "A title chosen by the user"+ "New task");}diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex f99efbab9..20847a075 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -347,9 +347,8 @@ pub struct SearchHit {/// keys the renderer writes — `chat.untitledTask` and `nav.newChat` — have/// their own label per locale, and a non-ASCII uppercase letter (a future/// "Ñö..." entry) would slip past ASCII-case-insensitive matching (#1755).-/// Keep this in sync with the migration list in-/// `db/session_title_source_migration.rs` and `LEGACY_DEFAULT_TITLES` in the-/// renderer.+/// Keep this in sync with `LEGACY_DEFAULT_TITLES` in+/// `apps/desktop/src/lib/session-title-utils.ts`.const PLACEHOLDER_TITLES: [&str; 19] = ["","new task",diff --git a/docs/adr/0323-plugin-owned-session-titles.md b/docs/adr/0323-plugin-owned-session-titles.mdindex 7ceece130..eb3266458 100644--- a/docs/adr/0323-plugin-owned-session-titles.md+++ b/docs/adr/0323-plugin-owned-session-titles.md@@ -57,10 +57,9 @@ model-composed title moves to the plugin.- The new permission allows the plugin to see bounded excerpts from anyactive default-titled Desktop session. It does not expose attachments, tools,later messages, or a general transcript-read method.-- Schema v23 classifies existing default placeholders as `default` and other- existing titles as `manual`, preserving user-chosen titles during migration.-- Existing sessions that still hold a known placeholder title receive the- first-prompt fallback on their next prompt, exactly like a new session.+- Schema v23 leaves pre-existing v22 titles as `legacy` to protect deliberate+ renames from automatic replacement; newly created sessions receive `default`+ or `manual` as appropriate.## Alternatives considereddiff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 30aea15a3..004f687a8 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -647,16 +647,22 @@ CREATE INDEX idx_session_import_origins_pluginrename does not update `updated_at`, so changing a label cannot reorderrecent activity; transcript rows, message count, and session state remainunchanged.-- `title_source` records `legacy`, `default`, `manual`, or `generated`. Schema- v23 classifies pre-existing known placeholder titles as `default` and all- other titles as `manual`; new session creation and manual rename write the- corresponding source. `default` means "not chosen by the user and still- replaceable": it covers a new session's placeholder and the deterministic+- `title_source` records `legacy`, `default`, `manual`, or `generated`. The+ v22→v23 migration leaves pre-existing titles as `legacy`; new session creation+ and manual rename write the corresponding source. `default` means "not chosen+ by the user and still replaceable": it covers a new session's placeholder and+ the deterministicfirst-prompt fallback, which host-core writes only while the stored title isstill a recognized placeholder. A placeholder is recognized in every shippedlocale, because the renderer writes its localized `chat.untitledTask` label- when it creates a session. The standalone title plugin can read- exact-title compare-and-set, so a manual rename wins a race.+ when it creates a session; recognition trims and lowercases the stored title+ against the placeholder set. Schema v23 retains pre-existing v22 titles as+ `legacy` to protect them from automatic replacement, because historical+ sessions lack provenance to distinguish an untouched placeholder from a+ deliberate rename to the same text. Existing v23/v24 rows are not reclassified.+ The standalone title plugin can read first-turn text only while `default`,+ and writes using exact-title+ compare-and-set, so a manual rename wins a race.- Import binds every non-empty normalized `projectPath` to `project_id`;path-less imports remain `NULL`. Re-importing a deterministic session idcreates neither another session nor another project row.@@ -1637,9 +1643,9 @@ truncating at a guessed position.- **Schema v22 is additive.** It replaces `idx_sessions_updated` with`idx_sessions_updated_id(updated_at DESC, id DESC)` for session-list ordering.It changes no rows or persisted fields; a v21 backup precedes the migration.-- **Schema v23 is additive.** It adds `sessions.title_source` and classifies- existing placeholder titles as `default`; every other existing title is- preserved and classified as `manual`. The migration keeps a v22 backup.+- **Schema v23 is additive.** It adds `sessions.title_source` with default+ `legacy`. Pre-existing v22 titles remain `legacy`, safely protecting deliberate+ renames from automatic replacement. The migration keeps a v22 backup.- **Schema v14 is additive.** It adds nullable `sessions.deleted_at`, thepartial deletion index, and `session_import_origins`. Existing sessions stayactive and have no origin rows. The migration runs in the same guardeddiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 65d91ced0..1e8b666fd 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3233,6 +3233,11 @@ identify the platform validation still needed.is replaced by the deterministic test title after the completed turn; after amanual rename, a later plugin completion cannot replace it. A session withoutthe plugin keeps its prompt fallback, and a second prompt never changes it.+- **Upgrade regression**: In an isolated v22 fixture, manually rename a session+ to lowercase `new task` before opening it in the current build. After upgrade,+ the title remains `new task` with source `legacy`; first-prompt derivation and+ plugin title writes cannot replace it. New sessions still derive titles.+ Host regression: `v22_database_migrates_session_title_sources_without_losing_titles`.- **Specs linked**: `03-runtime/01-ipc-protocol.md`,`03-runtime/04-data-storage.md`, `03-runtime/06-host-rpc-protocol.md`,`03-runtime/02-agent-runtime.md`, `07-plugins/03-plugin-api.md`,diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 94f093322..3ec3db405 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -377,14 +377,14 @@ CREATE INDEX idx_sessions_project ON sessions(project_id) WHERE project_id IS NOCREATE INDEX idx_sessions_deleted ON sessions(deleted_at) WHERE deleted_at IS NOT NULL;```-`title_source` 记录 `legacy`、`default`、`manual` 或 `generated`。架构 v23 会将已有的-已知占位标题归类为 `default`,其余标题归类为 `manual`,不改写标题。新建会话和手动重命名+`title_source` 记录 `legacy`、`default`、`manual` 或 `generated`。v22→v23 迁移将已有标题+保留为 `legacy`,不改写标题;已有 v23/v24 数据不会重新分类。新建会话和手动重命名会写入相应来源。`default` 表示“非用户选择、仍可替换”:它既覆盖新会话的占位标题,也覆盖确定性的首条提示兜底标题(host-core 只在存储标题仍是可识别占位标题时才写入)。占位标题在-所有已发布的语言下都会被识别,因为渲染器创建会话时会写入本地化的 `chat.untitledTask` 文案。-独立标题插件只能读取 `default` 会话的首轮文本,并且只能用精确标题比较并设置,因此并发手动-重命名会胜出。-会胜出。+所有已发布的语言下都会被识别,因为渲染器创建会话时会写入本地化的 `chat.untitledTask` 文案;+识别会先 trim 再转小写,并与占位标题集合比较。架构 v23 将已有的 v22 标题保留为 `legacy`,以防止+其被自动替换,因为历史会话缺少来源元数据来区分未修改的占位符与同名的主动重命名。独立标题插件只能读取+`default` 会话的首轮文本,并且只能用精确标题比较并设置,因此并发手动重命名会胜出。插件导入增加一个由主机拥有的来源 sidecar。它与核心会话身份分离,每次插件读写都必须匹配创建该行的 `plugin_id`:@@ -1186,8 +1186,8 @@ outbox 排空。渲染器侧的停止绝不重写已有已开始回复的转录- **架构 v17 是增量的。** 它增加可为空的 `providers.owner_plugin_id` 归属列及其部分索引(ADR 0259),从而把插件在 `contributes.providers` 中声明的 provider 行与用户创建的行区分开—— 所有 v17 之前的行保持 NULL 归属。该步骤之前保留 `pi.sqlite.v16.bak` 副本。-- **架构 v23 是增量的。** 它增加 `sessions.title_source`,并将现有占位标题归类为- `default`;其余现有标题保持原样并归类为 `manual`。迁移前保留 v22 备份。+- **架构 v23 是增量的。** 它增加 `sessions.title_source`,默认值为 `legacy`。已有+ v22 标题保留为 `legacy`,防止主动重命名被自动覆盖。迁移前保留 v22 备份。v15→v16 会话协作步骤现在写入 `16`(它自己的版本)而不是最新的架构常量,因此 v15 文件可以在一次启动中走完两个步骤。- **架构 v7 首先到达 v8,然后使用受保护的路径。** v7→v8