fix(desktop): V2 imports stashed prompts and drafts from the V1 profile (#15072)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
06e627448b
commit
c408737628
11 files changed
+853
-1
No files matched your search
@@ -19,6 +19,7 @@ import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
|
||||
import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
@@ -179,6 +180,10 @@ const bootstrap = Effect.gen(function* () {
|
||||
});
|
||||
yield* installDesktopIpcHandlers();
|
||||
yield* logBootstrapInfo("bootstrap ipc handlers registered");
|
||||
// Before any window: the preload merges these items before the app reads storage.
|
||||
yield* (yield* DesktopLegacyLocalStorage.DesktopLegacyLocalStorage).load(
|
||||
yield* (yield* DesktopAppIdentity.DesktopAppIdentity).resolveUserDataPath,
|
||||
);
|
||||
|
||||
yield* snapShot.initialize;
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import { readChromiumLocalStorage } from "./chromiumLocalStorage.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
|
||||
/**
|
||||
* Carries the renderer's localStorage (prompt stash, unsent drafts, layout,
|
||||
* theme) over from the V1 desktop profile, which V2 replaced with its own
|
||||
* `t3code-v2` profile. The V1 profile is only read, never opened by Chromium,
|
||||
* so this works while V1 is still running.
|
||||
*
|
||||
* `load` runs before the window opens; the preload takes the items once,
|
||||
* merges them into the new profile, and calls `complete`, which writes a
|
||||
* marker so later launches skip the read. A failed read or merge, or a window
|
||||
* that never completes, leaves no marker and retries next launch.
|
||||
*/
|
||||
export class DesktopLegacyLocalStorage extends Context.Service<
|
||||
DesktopLegacyLocalStorage,
|
||||
{
|
||||
readonly load: (userDataPath: string) => Effect.Effect<void>;
|
||||
readonly take: Effect.Effect<Option.Option<Readonly<Record<string, string>>>>;
|
||||
readonly complete: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLegacyLocalStorage") {}
|
||||
|
||||
const MARKER_FILE_NAME = "v1-local-storage-imported";
|
||||
// V1 used "T3 Code (Alpha)" when that folder existed and "t3code" otherwise.
|
||||
const V1_PROFILE_NAMES = ["T3 Code (Alpha)", "t3code"];
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const items = yield* Ref.make(Option.none<Readonly<Record<string, string>>>());
|
||||
const markerPath = yield* Ref.make(Option.none<string>());
|
||||
|
||||
/** Newest file mtime in a directory; appending to a log leaves the directory's own mtime alone. */
|
||||
const newestFileMtime = (directory: string) =>
|
||||
Effect.gen(function* () {
|
||||
let newest = 0;
|
||||
for (const name of yield* fs.readDirectory(directory)) {
|
||||
const info = yield* fs.stat(path.join(directory, name)).pipe(Effect.option);
|
||||
if (Option.isNone(info)) continue;
|
||||
const mtime = Option.match(info.value.mtime, {
|
||||
onNone: () => 0,
|
||||
onSome: (date) => date.getTime(),
|
||||
});
|
||||
newest = Math.max(newest, mtime);
|
||||
}
|
||||
return newest;
|
||||
}).pipe(Effect.option);
|
||||
|
||||
/** The V1 profile whose Local Storage was written most recently, if any. */
|
||||
const findV1LocalStorage = Effect.gen(function* () {
|
||||
let newest: { readonly directory: string; readonly mtime: number } | null = null;
|
||||
for (const name of V1_PROFILE_NAMES) {
|
||||
const directory = path.join(environment.appDataDirectory, name, "Local Storage", "leveldb");
|
||||
const mtime = yield* newestFileMtime(directory);
|
||||
if (Option.isNone(mtime)) continue;
|
||||
if (newest === null || mtime.value > newest.mtime) newest = { directory, mtime: mtime.value };
|
||||
}
|
||||
return newest?.directory ?? null;
|
||||
});
|
||||
|
||||
const writeMarker = Effect.gen(function* () {
|
||||
const marker = yield* Ref.get(markerPath);
|
||||
if (Option.isNone(marker)) return;
|
||||
yield* fs
|
||||
.writeFileString(marker.value, "")
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Could not record the V1 Local Storage import", error),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const load = Effect.fn("desktop.legacyLocalStorage.load")(function* (userDataPath: string) {
|
||||
// Development already shares its profile between versions.
|
||||
if (environment.isDevelopment) return;
|
||||
const marker = path.join(userDataPath, MARKER_FILE_NAME);
|
||||
if (yield* fs.exists(marker).pipe(Effect.orElseSucceed(() => true))) return;
|
||||
yield* Ref.set(markerPath, Option.some(marker));
|
||||
const directory = yield* findV1LocalStorage;
|
||||
if (directory === null) return yield* writeMarker;
|
||||
const origin = ElectronProtocol.getDesktopUrl(false).replace(/\/$/, "");
|
||||
const read = yield* readChromiumLocalStorage(directory, origin).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fs),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.tapError((error) =>
|
||||
Effect.logWarning("Could not read V1 Local Storage; will retry next launch", error),
|
||||
),
|
||||
Effect.option,
|
||||
);
|
||||
if (Option.isNone(read)) return;
|
||||
yield* Effect.logInfo("V1 Local Storage ready to import", {
|
||||
directory,
|
||||
keys: read.value.size,
|
||||
});
|
||||
yield* Ref.set(items, Option.some(Object.fromEntries(read.value)));
|
||||
});
|
||||
|
||||
return DesktopLegacyLocalStorage.of({
|
||||
load,
|
||||
// Taking clears the items, so a reload before `complete` cannot merge twice.
|
||||
take: Ref.getAndSet(items, Option.none()),
|
||||
complete: writeMarker,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLegacyLocalStorage, make);
|
||||
@@ -0,0 +1,460 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
/**
|
||||
* Read-only decoder for a Chromium profile's `Local Storage/leveldb`.
|
||||
*
|
||||
* It reads the database files directly and never takes LevelDB's lock, so it
|
||||
* works while another app version has the profile open. Live files come from
|
||||
* the MANIFEST that CURRENT names, and the newest sequence number wins, which
|
||||
* is how LevelDB itself resolves overwrites and deletions.
|
||||
*/
|
||||
|
||||
const LOG_BLOCK_SIZE = 32 * 1024;
|
||||
const LOG_HEADER_SIZE = 7;
|
||||
const TABLE_FOOTER_SIZE = 48;
|
||||
const BLOCK_TRAILER_SIZE = 5;
|
||||
|
||||
class LevelDbFormatError extends Schema.TaggedError<LevelDbFormatError>()("LevelDbFormatError", {
|
||||
detail: Schema.String,
|
||||
}) {}
|
||||
|
||||
const isLevelDbFormatError = Schema.is(LevelDbFormatError);
|
||||
|
||||
const fail = (detail: string): never => {
|
||||
throw new LevelDbFormatError({ detail });
|
||||
};
|
||||
|
||||
// ignoreBOM keeps a leading U+FEFF that is part of the stored string.
|
||||
const textDecoderUtf16 = new TextDecoder("utf-16le", { ignoreBOM: true });
|
||||
const textDecoderUtf8 = new TextDecoder();
|
||||
|
||||
/** True ISO-8859-1. WHATWG's "latin1" label is windows-1252, which remaps 0x80-0x9F. */
|
||||
function decodeLatin1(bytes: Uint8Array): string {
|
||||
let result = "";
|
||||
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
|
||||
result += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
class Reader {
|
||||
readonly bytes: Uint8Array;
|
||||
offset: number;
|
||||
constructor(bytes: Uint8Array, offset = 0) {
|
||||
this.bytes = bytes;
|
||||
this.offset = offset;
|
||||
}
|
||||
get done() {
|
||||
return this.offset >= this.bytes.length;
|
||||
}
|
||||
byte(): number {
|
||||
if (this.offset >= this.bytes.length) fail("unexpected end of data");
|
||||
return this.bytes[this.offset++]!;
|
||||
}
|
||||
varint(): number {
|
||||
let result = 0;
|
||||
let multiplier = 1;
|
||||
for (let shift = 0; shift < 64; shift += 7) {
|
||||
const byte = this.byte();
|
||||
result += (byte & 0x7f) * multiplier;
|
||||
if ((byte & 0x80) === 0) return result;
|
||||
multiplier *= 128;
|
||||
}
|
||||
return fail("varint too long");
|
||||
}
|
||||
take(length: number): Uint8Array {
|
||||
if (length < 0 || this.offset + length > this.bytes.length) fail("length out of range");
|
||||
const slice = this.bytes.subarray(this.offset, this.offset + length);
|
||||
this.offset += length;
|
||||
return slice;
|
||||
}
|
||||
lengthPrefixed(): Uint8Array {
|
||||
return this.take(this.varint());
|
||||
}
|
||||
}
|
||||
|
||||
const readUint32 = (bytes: Uint8Array, offset: number) =>
|
||||
(bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16)) +
|
||||
bytes[offset + 3]! * 0x1000000;
|
||||
|
||||
const CRC32C_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let index = 0; index < 256; index++) {
|
||||
let crc = index;
|
||||
for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? (crc >>> 1) ^ 0x82f63b78 : crc >>> 1;
|
||||
table[index] = crc >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function crc32c(bytes: Uint8Array): number {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) crc = CRC32C_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
/** LevelDB stores CRCs masked so a CRC of data containing CRCs stays well distributed. */
|
||||
const unmaskCrc = (masked: number) => {
|
||||
const rotated = (masked - 0xa282ead8) >>> 0;
|
||||
return ((rotated >>> 17) | (rotated << 15)) >>> 0;
|
||||
};
|
||||
|
||||
function decompressSnappy(input: Uint8Array): Uint8Array {
|
||||
const reader = new Reader(input);
|
||||
const output = new Uint8Array(reader.varint());
|
||||
let written = 0;
|
||||
while (!reader.done) {
|
||||
const tag = reader.byte();
|
||||
const kind = tag & 3;
|
||||
if (kind === 0) {
|
||||
let length = tag >>> 2;
|
||||
if (length >= 60) {
|
||||
const extraBytes = length - 59;
|
||||
length = 0;
|
||||
for (let index = 0; index < extraBytes; index++) length += reader.byte() * 256 ** index;
|
||||
}
|
||||
length += 1;
|
||||
if (written + length > output.length) fail("snappy literal overflows output");
|
||||
output.set(reader.take(length), written);
|
||||
written += length;
|
||||
continue;
|
||||
}
|
||||
let length: number;
|
||||
let offset: number;
|
||||
if (kind === 1) {
|
||||
length = 4 + ((tag >>> 2) & 7);
|
||||
offset = ((tag >>> 5) << 8) | reader.byte();
|
||||
} else if (kind === 2) {
|
||||
length = (tag >>> 2) + 1;
|
||||
offset = reader.byte() | (reader.byte() << 8);
|
||||
} else {
|
||||
length = (tag >>> 2) + 1;
|
||||
offset = readUint32(reader.take(4), 0);
|
||||
}
|
||||
if (offset === 0 || offset > written || written + length > output.length) {
|
||||
fail("snappy copy out of range");
|
||||
}
|
||||
// Copies may overlap their own output, so they go byte by byte.
|
||||
for (let index = 0; index < length; index++) {
|
||||
output[written] = output[written - offset]!;
|
||||
written++;
|
||||
}
|
||||
}
|
||||
if (written !== output.length) fail("snappy output length mismatch");
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a LevelDB log (write-ahead log or MANIFEST) into its records. Like
|
||||
* LevelDB's own reader, a corrupt record or zero padding skips the rest of its
|
||||
* block, since a reused log keeps appending after a torn write, and a record
|
||||
* cut off by the end of the file ends the log.
|
||||
*/
|
||||
function readLogRecords(bytes: Uint8Array): Uint8Array[] {
|
||||
const records: Uint8Array[] = [];
|
||||
let pending: Uint8Array[] | null = null;
|
||||
let offset = 0;
|
||||
while (offset + LOG_HEADER_SIZE <= bytes.length) {
|
||||
const blockRemaining = LOG_BLOCK_SIZE - (offset % LOG_BLOCK_SIZE);
|
||||
if (blockRemaining < LOG_HEADER_SIZE) {
|
||||
offset += blockRemaining;
|
||||
continue;
|
||||
}
|
||||
const length = bytes[offset + 4]! | (bytes[offset + 5]! << 8);
|
||||
const type = bytes[offset + 6]!;
|
||||
const end = offset + LOG_HEADER_SIZE + length;
|
||||
const fitsBlock = LOG_HEADER_SIZE + length <= blockRemaining;
|
||||
if (fitsBlock && end > bytes.length) break;
|
||||
const typeAndPayload = bytes.subarray(offset + 6, end);
|
||||
if (
|
||||
type === 0 ||
|
||||
!fitsBlock ||
|
||||
crc32c(typeAndPayload) !== unmaskCrc(readUint32(bytes, offset))
|
||||
) {
|
||||
offset += blockRemaining;
|
||||
pending = null;
|
||||
continue;
|
||||
}
|
||||
const payload = typeAndPayload.subarray(1);
|
||||
offset = end;
|
||||
if (type === 1) {
|
||||
records.push(payload);
|
||||
pending = null;
|
||||
} else if (type === 2) {
|
||||
pending = [payload];
|
||||
} else if (type === 3 && pending) {
|
||||
pending.push(payload);
|
||||
} else if (type === 4 && pending) {
|
||||
pending.push(payload);
|
||||
const total = pending.reduce((sum, part) => sum + part.length, 0);
|
||||
const record = new Uint8Array(total);
|
||||
let position = 0;
|
||||
for (const part of pending) {
|
||||
record.set(part, position);
|
||||
position += part.length;
|
||||
}
|
||||
records.push(record);
|
||||
pending = null;
|
||||
} else {
|
||||
pending = null;
|
||||
}
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
interface LiveFiles {
|
||||
readonly tables: ReadonlyArray<number>;
|
||||
readonly logNumber: number;
|
||||
readonly previousLogNumber: number;
|
||||
}
|
||||
|
||||
/** Replays MANIFEST version edits to find the live table files and log. */
|
||||
function readManifest(bytes: Uint8Array): LiveFiles {
|
||||
const tables = new Set<number>();
|
||||
let logNumber = 0;
|
||||
let previousLogNumber = 0;
|
||||
// LevelDB refuses to open a MANIFEST missing any of these, and so do we.
|
||||
const required = new Set([2, 3, 4]);
|
||||
for (const record of readLogRecords(bytes)) {
|
||||
const reader = new Reader(record);
|
||||
while (!reader.done) {
|
||||
const tag = reader.varint();
|
||||
required.delete(tag);
|
||||
switch (tag) {
|
||||
case 1: // comparator
|
||||
reader.lengthPrefixed();
|
||||
break;
|
||||
case 2:
|
||||
logNumber = reader.varint();
|
||||
break;
|
||||
case 3: // next file number
|
||||
case 4: // last sequence
|
||||
reader.varint();
|
||||
break;
|
||||
case 5: // compaction pointer
|
||||
reader.varint();
|
||||
reader.lengthPrefixed();
|
||||
break;
|
||||
case 6: // deleted file
|
||||
reader.varint();
|
||||
tables.delete(reader.varint());
|
||||
break;
|
||||
case 7: {
|
||||
reader.varint();
|
||||
tables.add(reader.varint());
|
||||
reader.varint();
|
||||
reader.lengthPrefixed();
|
||||
reader.lengthPrefixed();
|
||||
break;
|
||||
}
|
||||
case 9:
|
||||
previousLogNumber = reader.varint();
|
||||
break;
|
||||
default:
|
||||
fail(`unknown manifest tag ${tag}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (required.size > 0) fail("incomplete manifest");
|
||||
return { tables: [...tables], logNumber, previousLogNumber };
|
||||
}
|
||||
|
||||
interface VersionedEntry {
|
||||
readonly sequence: number;
|
||||
/** `null` marks a deletion. */
|
||||
readonly value: Uint8Array | null;
|
||||
}
|
||||
|
||||
type EntryMap = Map<string, { readonly key: Uint8Array; readonly entry: VersionedEntry }>;
|
||||
|
||||
const keyId = decodeLatin1;
|
||||
|
||||
function record(entries: EntryMap, key: Uint8Array, entry: VersionedEntry) {
|
||||
const id = keyId(key);
|
||||
const existing = entries.get(id);
|
||||
if (!existing || existing.entry.sequence < entry.sequence) entries.set(id, { key, entry });
|
||||
}
|
||||
|
||||
/** Applies one write-ahead log record (a WriteBatch). */
|
||||
function readWriteBatch(entries: EntryMap, batch: Uint8Array) {
|
||||
if (batch.length < 12) fail("write batch too short");
|
||||
// The sequence is a little-endian uint64; real values stay far below 2^53.
|
||||
const sequence = readUint32(batch, 0) + readUint32(batch, 4) * 0x100000000;
|
||||
const count = readUint32(batch, 8);
|
||||
const reader = new Reader(batch, 12);
|
||||
for (let index = 0; index < count; index++) {
|
||||
const type = reader.byte();
|
||||
const key = reader.lengthPrefixed();
|
||||
if (type === 1) {
|
||||
record(entries, key, { sequence: sequence + index, value: reader.lengthPrefixed() });
|
||||
} else if (type === 0) {
|
||||
record(entries, key, { sequence: sequence + index, value: null });
|
||||
} else {
|
||||
fail(`unknown write batch record type ${type}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function readBlock(table: Uint8Array, reader: Reader): Uint8Array {
|
||||
const offset = reader.varint();
|
||||
const size = reader.varint();
|
||||
if (offset + size + BLOCK_TRAILER_SIZE > table.length) fail("block handle out of range");
|
||||
const contents = table.subarray(offset, offset + size);
|
||||
const compression = table[offset + size]!;
|
||||
const checksum = unmaskCrc(readUint32(table, offset + size + 1));
|
||||
if (crc32c(table.subarray(offset, offset + size + 1)) !== checksum) fail("block checksum");
|
||||
if (compression === 0) return contents;
|
||||
if (compression === 1) return decompressSnappy(contents);
|
||||
return fail(`unsupported block compression ${compression}`);
|
||||
}
|
||||
|
||||
function* blockEntries(block: Uint8Array): Generator<[Uint8Array, Uint8Array]> {
|
||||
if (block.length < 4) fail("block too short");
|
||||
const restartCount = readUint32(block, block.length - 4);
|
||||
const limit = block.length - 4 - restartCount * 4;
|
||||
if (limit < 0) fail("restart array out of range");
|
||||
const reader = new Reader(block.subarray(0, limit));
|
||||
let key = new Uint8Array(0);
|
||||
while (!reader.done) {
|
||||
const shared = reader.varint();
|
||||
const unshared = reader.varint();
|
||||
const valueLength = reader.varint();
|
||||
if (shared > key.length) fail("block key prefix out of range");
|
||||
const nextKey = new Uint8Array(shared + unshared);
|
||||
nextKey.set(key.subarray(0, shared));
|
||||
nextKey.set(reader.take(unshared), shared);
|
||||
key = nextKey;
|
||||
yield [key, reader.take(valueLength)];
|
||||
}
|
||||
}
|
||||
|
||||
/** Applies every entry in one sorted table (`.ldb`/`.sst`) file. */
|
||||
function readTable(entries: EntryMap, table: Uint8Array) {
|
||||
if (table.length < TABLE_FOOTER_SIZE) fail("table too short");
|
||||
const footer = new Reader(table, table.length - TABLE_FOOTER_SIZE);
|
||||
footer.varint();
|
||||
footer.varint();
|
||||
const index = readBlock(table, footer);
|
||||
for (const [, handle] of blockEntries(index)) {
|
||||
const block = readBlock(table, new Reader(handle));
|
||||
for (const [internalKey, value] of blockEntries(block)) {
|
||||
if (internalKey.length < 8) fail("internal key too short");
|
||||
const trailerOffset = internalKey.length - 8;
|
||||
const trailer =
|
||||
readUint32(internalKey, trailerOffset) +
|
||||
readUint32(internalKey, trailerOffset + 4) * 0x100000000;
|
||||
const type = trailer % 256;
|
||||
const sequence = Math.floor(trailer / 256);
|
||||
const key = internalKey.subarray(0, trailerOffset);
|
||||
record(entries, key, { sequence, value: type === 1 ? value : null });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Chromium prefixes each stored string with 0 (UTF-16LE) or 1 (Latin-1). */
|
||||
function decodeChromiumString(bytes: Uint8Array): string | null {
|
||||
if (bytes.length === 0) return null;
|
||||
const body = bytes.subarray(1);
|
||||
if (bytes[0] === 1) return decodeLatin1(body);
|
||||
if (bytes[0] === 0 && body.length % 2 === 0) return textDecoderUtf16.decode(body);
|
||||
return null;
|
||||
}
|
||||
|
||||
export class ChromiumLocalStorageReadError extends Schema.TaggedError<ChromiumLocalStorageReadError>()(
|
||||
"ChromiumLocalStorageReadError",
|
||||
{
|
||||
directory: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Could not read Chromium Local Storage at ${this.directory}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the localStorage items one origin (for example `t3code://app`) had
|
||||
* in the profile, or an empty map when the profile never stored any.
|
||||
*/
|
||||
export const readChromiumLocalStorage = Effect.fn("desktop.chromiumLocalStorage.read")(function* (
|
||||
directory: string,
|
||||
origin: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const readFile = (name: string) => fs.readFile(path.join(directory, name));
|
||||
const wrap = Effect.mapError(
|
||||
(cause: PlatformError.PlatformError | LevelDbFormatError) =>
|
||||
new ChromiumLocalStorageReadError({ directory, cause }),
|
||||
);
|
||||
const decode = <A>(run: () => A) =>
|
||||
Effect.try({
|
||||
try: run,
|
||||
catch: (cause) =>
|
||||
isLevelDbFormatError(cause) ? cause : new LevelDbFormatError({ detail: String(cause) }),
|
||||
});
|
||||
|
||||
const current = textDecoderUtf8.decode(yield* readFile("CURRENT").pipe(wrap)).trim();
|
||||
if (!/^MANIFEST-\d+$/.test(current)) {
|
||||
return yield* new ChromiumLocalStorageReadError({
|
||||
directory,
|
||||
cause: new LevelDbFormatError({ detail: "bad CURRENT" }),
|
||||
});
|
||||
}
|
||||
const manifest = yield* readFile(current).pipe(wrap);
|
||||
const live = yield* decode(() => readManifest(manifest)).pipe(wrap);
|
||||
const logs = (yield* fs.readDirectory(directory).pipe(wrap))
|
||||
.map((name) => /^(\d+)\.log$/.exec(name))
|
||||
// The logs LevelDB's own recovery replays.
|
||||
.filter((match) => {
|
||||
const number = Number(match?.[1]);
|
||||
return number >= live.logNumber || number === live.previousLogNumber;
|
||||
})
|
||||
.map((match) => match![0]);
|
||||
|
||||
const entries: EntryMap = new Map();
|
||||
for (const number of live.tables) {
|
||||
const name = String(number).padStart(6, "0");
|
||||
// Newer LevelDB names tables .ldb; older databases may still hold .sst files.
|
||||
const bytes = yield* readFile(`${name}.ldb`).pipe(
|
||||
Effect.catchIf(
|
||||
(error) => error.reason._tag === "NotFound",
|
||||
() => readFile(`${name}.sst`),
|
||||
),
|
||||
wrap,
|
||||
);
|
||||
yield* decode(() => readTable(entries, bytes)).pipe(wrap);
|
||||
}
|
||||
for (const name of logs) {
|
||||
const bytes = yield* readFile(name).pipe(wrap);
|
||||
yield* decode(() => {
|
||||
for (const batch of readLogRecords(bytes)) readWriteBatch(entries, batch);
|
||||
}).pipe(wrap);
|
||||
}
|
||||
|
||||
// A flush while another process has the database open can move entries
|
||||
// from a log we read into a table our MANIFEST copy predates. Fail so the
|
||||
// caller retries rather than import a snapshot missing those entries.
|
||||
const currentAfter = textDecoderUtf8.decode(yield* readFile("CURRENT").pipe(wrap)).trim();
|
||||
const manifestAfter = yield* fs.stat(path.join(directory, current)).pipe(wrap);
|
||||
if (currentAfter !== current || Number(manifestAfter.size) !== manifest.length) {
|
||||
return yield* new ChromiumLocalStorageReadError({
|
||||
directory,
|
||||
cause: new LevelDbFormatError({ detail: "database changed while reading" }),
|
||||
});
|
||||
}
|
||||
|
||||
const prefix = `_${origin}\u0000`;
|
||||
const items = new Map<string, string>();
|
||||
for (const [id, { key: rawKey, entry }] of entries) {
|
||||
if (!id.startsWith(prefix) || entry.value === null) continue;
|
||||
const key = decodeChromiumString(rawKey.subarray(prefix.length));
|
||||
const value = decodeChromiumString(entry.value);
|
||||
if (key !== null && value !== null) items.set(key, value);
|
||||
}
|
||||
return items;
|
||||
});
|
||||
@@ -70,6 +70,10 @@ import {
|
||||
} from "./methods/snapShot.ts";
|
||||
import * as PreviewIpc from "./methods/preview.ts";
|
||||
import * as AppActivationIpc from "./methods/appActivation.ts";
|
||||
import {
|
||||
completeLegacyLocalStorage,
|
||||
takeLegacyLocalStorage,
|
||||
} from "./methods/legacyLocalStorage.ts";
|
||||
import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./methods/wsl.ts";
|
||||
|
||||
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
|
||||
@@ -80,6 +84,8 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(AppActivationIpc.setReady);
|
||||
yield* ipc.handle(AppActivationIpc.complete);
|
||||
|
||||
yield* ipc.handleSync(takeLegacyLocalStorage);
|
||||
yield* ipc.handle(completeLegacyLocalStorage);
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getSystemLocale);
|
||||
yield* ipc.handleSync(getWindowFullscreenState);
|
||||
|
||||
@@ -119,3 +119,5 @@ export const PREVIEW_RECORDING_INPUT_CHANNEL = "desktop:preview-recording-input"
|
||||
|
||||
export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider-auth-callback";
|
||||
export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback";
|
||||
export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage";
|
||||
export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage";
|
||||
@@ -0,0 +1,30 @@
|
||||
import * as Electron from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DesktopLegacyLocalStorage from "../../app/DesktopLegacyLocalStorage.ts";
|
||||
import * as IpcChannels from "../channels.ts";
|
||||
import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
|
||||
|
||||
export const takeLegacyLocalStorage = makeSyncIpcMethod({
|
||||
channel: IpcChannels.TAKE_LEGACY_LOCAL_STORAGE_CHANNEL,
|
||||
result: Schema.NullOr(Schema.Record(Schema.String, Schema.String)),
|
||||
handler: Effect.fn("desktop.ipc.legacyLocalStorage.take")(function* () {
|
||||
const legacy = yield* DesktopLegacyLocalStorage.DesktopLegacyLocalStorage;
|
||||
return Option.getOrNull(yield* legacy.take);
|
||||
}),
|
||||
});
|
||||
|
||||
export const completeLegacyLocalStorage = makeIpcMethod({
|
||||
channel: IpcChannels.COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.legacyLocalStorage.complete")(function* (_, event) {
|
||||
const legacy = yield* DesktopLegacyLocalStorage.DesktopLegacyLocalStorage;
|
||||
// Chromium writes localStorage to disk lazily; persist the merge before
|
||||
// the marker stops later launches from retrying it.
|
||||
if (event) Electron.webContents.fromId(event.sender.id)?.session.flushStorageData();
|
||||
yield* legacy.complete;
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import { mergeLegacyLocalStorage } from "./legacyLocalStorageMerge.ts";
|
||||
|
||||
const memoryStorage = (initial: Record<string, string> = {}) => {
|
||||
const items = new Map(Object.entries(initial));
|
||||
return {
|
||||
items,
|
||||
getItem: (key: string) => items.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => void items.set(key, value),
|
||||
};
|
||||
};
|
||||
|
||||
const stash = (...ids: string[]) =>
|
||||
JSON.stringify({
|
||||
version: 2,
|
||||
state: { entries: ids.map((id) => ({ id, prompt: `prompt ${id}` })) },
|
||||
});
|
||||
|
||||
const drafts = (version: number, threadKey: string, prompt: string) =>
|
||||
JSON.stringify({
|
||||
version,
|
||||
state: {
|
||||
draftsByThreadKey: { [threadKey]: { prompt } },
|
||||
draftThreadsByThreadKey: {},
|
||||
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
|
||||
},
|
||||
});
|
||||
|
||||
describe("mergeLegacyLocalStorage", () => {
|
||||
it("copies V1 keys into an empty profile, except the per-install client id", () => {
|
||||
const storage = memoryStorage();
|
||||
mergeLegacyLocalStorage(storage, {
|
||||
"t3code:theme": "dark",
|
||||
"t3code:prompt-stash:v2": stash("a"),
|
||||
"t3.backgroundActivity.clientId": "v1-client",
|
||||
});
|
||||
assert.equal(storage.getItem("t3code:theme"), "dark");
|
||||
assert.equal(storage.getItem("t3code:prompt-stash:v2"), stash("a"));
|
||||
assert.equal(storage.getItem("t3.backgroundActivity.clientId"), null);
|
||||
});
|
||||
|
||||
it("keeps V2 values for plain keys", () => {
|
||||
const storage = memoryStorage({ "t3code:theme": "light" });
|
||||
mergeLegacyLocalStorage(storage, { "t3code:theme": "dark" });
|
||||
assert.equal(storage.getItem("t3code:theme"), "light");
|
||||
});
|
||||
|
||||
it("appends V1 stash entries after V2's without duplicating ids", () => {
|
||||
const storage = memoryStorage({ "t3code:prompt-stash:v2": stash("new", "shared") });
|
||||
mergeLegacyLocalStorage(storage, { "t3code:prompt-stash:v2": stash("shared", "old") });
|
||||
const ids = JSON.parse(storage.getItem("t3code:prompt-stash:v2")!).state.entries.map(
|
||||
(entry: { id: string }) => entry.id,
|
||||
);
|
||||
assert.deepStrictEqual(ids, ["new", "shared", "old"]);
|
||||
});
|
||||
|
||||
it("adds V1 drafts for other threads and keeps V2's draft for the same thread", () => {
|
||||
const storage = memoryStorage({
|
||||
"t3code:composer-drafts:v1": drafts(9, "env:shared", "v2 text"),
|
||||
});
|
||||
const legacy = JSON.parse(drafts(9, "env:shared", "v1 text"));
|
||||
legacy.state.draftsByThreadKey["env:old"] = { prompt: "v1 only" };
|
||||
mergeLegacyLocalStorage(storage, { "t3code:composer-drafts:v1": JSON.stringify(legacy) });
|
||||
const merged = JSON.parse(storage.getItem("t3code:composer-drafts:v1")!);
|
||||
assert.equal(merged.state.draftsByThreadKey["env:shared"].prompt, "v2 text");
|
||||
assert.equal(merged.state.draftsByThreadKey["env:old"].prompt, "v1 only");
|
||||
});
|
||||
|
||||
it("leaves V2 drafts alone when the stored shapes differ in version", () => {
|
||||
const current = drafts(10, "env:a", "v2");
|
||||
const storage = memoryStorage({ "t3code:composer-drafts:v1": current });
|
||||
mergeLegacyLocalStorage(storage, { "t3code:composer-drafts:v1": drafts(9, "env:b", "v1") });
|
||||
assert.equal(storage.getItem("t3code:composer-drafts:v1"), current);
|
||||
});
|
||||
|
||||
it("caps the merged stash at the store's entry limit, dropping the oldest V1 entries", () => {
|
||||
const v2Ids = Array.from({ length: 15 }, (_, index) => `v2-${index}`);
|
||||
const v1Ids = Array.from({ length: 10 }, (_, index) => `v1-${index}`);
|
||||
const storage = memoryStorage({ "t3code:prompt-stash:v2": stash(...v2Ids) });
|
||||
mergeLegacyLocalStorage(storage, { "t3code:prompt-stash:v2": stash(...v1Ids) });
|
||||
const ids = JSON.parse(storage.getItem("t3code:prompt-stash:v2")!).state.entries.map(
|
||||
(entry: { id: string }) => entry.id,
|
||||
);
|
||||
assert.deepStrictEqual(ids, [...v2Ids, ...v1Ids.slice(0, 5)]);
|
||||
});
|
||||
|
||||
it("keeps importing other keys after one write fails, and reports the failure", () => {
|
||||
const storage = memoryStorage();
|
||||
const setItem = storage.setItem;
|
||||
storage.setItem = (key, value) => {
|
||||
if (key === "t3code:theme") throw new DOMException("full", "QuotaExceededError");
|
||||
setItem(key, value);
|
||||
};
|
||||
const complete = mergeLegacyLocalStorage(storage, {
|
||||
"t3code:theme": "dark",
|
||||
"t3code:last-editor": "zed",
|
||||
});
|
||||
assert.equal(storage.getItem("t3code:last-editor"), "zed");
|
||||
assert.isFalse(complete);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Merges V1 profile localStorage items into the V2 profile. Runs in the preload
|
||||
* before the app reads storage, and never overwrites what V2 already holds: a
|
||||
* key V2 has written keeps V2's value, except that stashed prompts and unsent
|
||||
* drafts are merged entry by entry so neither side's are lost.
|
||||
*/
|
||||
|
||||
interface MergeStorage {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
}
|
||||
|
||||
const PROMPT_STASH_KEY = "t3code:prompt-stash:v2";
|
||||
const COMPOSER_DRAFTS_KEY = "t3code:composer-drafts:v1";
|
||||
const NOT_IMPORTED_KEYS = new Set([
|
||||
// Identifies one running install to the server; two apps must not share it.
|
||||
"t3.backgroundActivity.clientId",
|
||||
// Resumes a permission setup V1 left mid-flow; V2 would redirect to it on boot.
|
||||
"t3code:snap-shot-setup-resume:v1",
|
||||
]);
|
||||
/** Matches MAX_STASH_ENTRIES in apps/web/src/promptStashStore.ts. */
|
||||
const MAX_STASH_ENTRIES = 20;
|
||||
const DRAFT_RECORD_FIELDS = [
|
||||
"draftsByThreadKey",
|
||||
"draftThreadsByThreadKey",
|
||||
"logicalProjectDraftThreadKeyByLogicalProjectKey",
|
||||
] as const;
|
||||
|
||||
type JsonObject = Record<string, unknown>;
|
||||
|
||||
const isObject = (value: unknown): value is JsonObject =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
function parseObject(raw: string): JsonObject | null {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** V2 entries first, then V1 entries V2 does not already have, up to the stash cap. */
|
||||
function mergePromptStash(current: JsonObject, legacy: JsonObject): JsonObject | null {
|
||||
const currentEntries = isObject(current.state) ? current.state.entries : null;
|
||||
const legacyEntries = isObject(legacy.state) ? legacy.state.entries : null;
|
||||
if (!Array.isArray(currentEntries) || !Array.isArray(legacyEntries)) return null;
|
||||
if (current.version !== legacy.version) return null;
|
||||
const ids = new Set(currentEntries.map((entry) => (isObject(entry) ? entry.id : undefined)));
|
||||
const added = legacyEntries.filter((entry) => isObject(entry) && !ids.has(entry.id));
|
||||
const state = isObject(current.state) ? current.state : {};
|
||||
return {
|
||||
...current,
|
||||
state: { ...state, entries: [...currentEntries, ...added].slice(0, MAX_STASH_ENTRIES) },
|
||||
};
|
||||
}
|
||||
|
||||
/** Adds V1 drafts for threads V2 has no draft for. Shapes must share a version. */
|
||||
function mergeComposerDrafts(current: JsonObject, legacy: JsonObject): JsonObject | null {
|
||||
if (current.version !== legacy.version) return null;
|
||||
if (!isObject(current.state) || !isObject(legacy.state)) return null;
|
||||
const state: JsonObject = { ...current.state };
|
||||
for (const field of DRAFT_RECORD_FIELDS) {
|
||||
const currentRecord = state[field];
|
||||
const legacyRecord = legacy.state[field];
|
||||
if (!isObject(currentRecord) || !isObject(legacyRecord)) return null;
|
||||
state[field] = { ...legacyRecord, ...currentRecord };
|
||||
}
|
||||
return { ...current, state };
|
||||
}
|
||||
|
||||
const isMergedKey = (key: string) => key === PROMPT_STASH_KEY || key === COMPOSER_DRAFTS_KEY;
|
||||
|
||||
function mergeValue(key: string, current: string, legacy: string): string | null {
|
||||
const merge =
|
||||
key === PROMPT_STASH_KEY
|
||||
? mergePromptStash
|
||||
: key === COMPOSER_DRAFTS_KEY
|
||||
? mergeComposerDrafts
|
||||
: null;
|
||||
if (merge === null) return null;
|
||||
const currentObject = parseObject(current);
|
||||
const legacyObject = parseObject(legacy);
|
||||
if (currentObject === null || legacyObject === null) return null;
|
||||
const merged = merge(currentObject, legacyObject);
|
||||
return merged === null ? null : JSON.stringify(merged);
|
||||
}
|
||||
|
||||
/** Returns false when a write failed, so the caller can retry on a later launch. */
|
||||
export function mergeLegacyLocalStorage(
|
||||
storage: MergeStorage,
|
||||
legacyItems: Readonly<Record<string, string>>,
|
||||
): boolean {
|
||||
let complete = true;
|
||||
// Stash and drafts first, so a full quota costs layout state rather than prompts.
|
||||
const keys = Object.keys(legacyItems).sort(
|
||||
(left, right) => Number(isMergedKey(right)) - Number(isMergedKey(left)),
|
||||
);
|
||||
for (const key of keys) {
|
||||
if (NOT_IMPORTED_KEYS.has(key)) continue;
|
||||
const legacy = legacyItems[key]!;
|
||||
const current = storage.getItem(key);
|
||||
const next = current === null ? legacy : mergeValue(key, current, legacy);
|
||||
if (next === null || next === current) continue;
|
||||
try {
|
||||
storage.setItem(key, next);
|
||||
} catch {
|
||||
// Over quota: skip this key rather than abandon the rest.
|
||||
complete = false;
|
||||
}
|
||||
}
|
||||
return complete;
|
||||
}
|
||||
@@ -60,6 +60,7 @@ import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
import * as DesktopState from "./app/DesktopState.ts";
|
||||
import * as DesktopLegacyLocalStorage from "./app/DesktopLegacyLocalStorage.ts";
|
||||
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
|
||||
import * as BrowserImport from "./preview/BrowserImport/BrowserImport.ts";
|
||||
@@ -140,6 +141,7 @@ const desktopFoundationLayer = Layer.mergeAll(
|
||||
MacPermissions.layer,
|
||||
DesktopState.layer,
|
||||
DesktopShutdown.layer,
|
||||
DesktopLegacyLocalStorage.layer,
|
||||
DesktopAppSettings.layer,
|
||||
DesktopClientSettings.layer,
|
||||
DesktopConnectionCatalogStore.layer.pipe(Layer.provideMerge(DesktopSavedEnvironments.layer)),
|
||||
|
||||
@@ -10,6 +10,7 @@ import { exposeClerkBridge } from "@clerk/electron/preload";
|
||||
import { contextBridge, ipcRenderer, webFrame, webUtils } from "electron";
|
||||
|
||||
import * as IpcChannels from "./ipc/channels.ts";
|
||||
import { mergeLegacyLocalStorage } from "./legacyLocalStorageMerge.ts";
|
||||
|
||||
const SNAP_SHOT_EVENT_TYPES = new Set([
|
||||
"requested",
|
||||
@@ -30,6 +31,18 @@ function isSnapShotEvent(value: unknown): value is DesktopSnapShotEvent {
|
||||
|
||||
exposeClerkBridge({ passkeys: true });
|
||||
|
||||
// Runs before any app script reads localStorage. See DesktopLegacyLocalStorage.
|
||||
try {
|
||||
const legacyItems: unknown = ipcRenderer.sendSync(IpcChannels.TAKE_LEGACY_LOCAL_STORAGE_CHANNEL);
|
||||
if (typeof legacyItems === "object" && legacyItems !== null) {
|
||||
if (mergeLegacyLocalStorage(window.localStorage, legacyItems as Record<string, string>)) {
|
||||
void ipcRenderer.invoke(IpcChannels.COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Best effort: the app still starts on the V2 profile's own storage.
|
||||
}
|
||||
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Electron exposes the client platform in its sandboxed preload process.
|
||||
const clientPlatform = process.platform;
|
||||
|
||||
|
||||
@@ -10,7 +10,9 @@ and changes in either version do not sync to the other. Settings, attachments, a
|
||||
remain shared.
|
||||
|
||||
The V2 desktop app uses a separate browser profile, so browser cookies and caches do not carry
|
||||
over from V1. You may need to sign in again to websites opened inside the app.
|
||||
over from V1. You may need to sign in again to websites opened inside the app. On its first launch,
|
||||
the V2 desktop app copies stashed prompts, unsent drafts, layout, and theme from V1. Anything you
|
||||
change in V2 afterwards stays in V2.
|
||||
|
||||
The migrated thread keeps its title, project, provider and model selection, permission and
|
||||
interaction modes, branch or worktree, archive state, settlement state, snooze and pin state, and
|
||||
|
||||
Reference in new issue
Block a user