Adds prettier 3.9.8 (exact) with a shared config (single quotes, 120 columns, trailing commas), .prettierignore, .editorconfig and the `format` / `format:check` scripts, then formats all TypeScript, JavaScript, CSS, JSON and YAML sources. Purely mechanical: no behaviour change. Typecheck passes, the vitest suite and the 74 IDE node tests produce the same results as before (socket-binding tests still cannot run inside this sandbox). Previously the longest source line was ~3000 characters; reviewing the following semantic changes now produces readable diffs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
307 lines
11 KiB
JavaScript
307 lines
11 KiB
JavaScript
const { FrontendApplicationContribution, ApplicationShell, OpenerService, open } = require('@theia/core/lib/browser');
|
|
const {
|
|
CommandContribution,
|
|
MessageService,
|
|
QuickInputService,
|
|
UntitledResourceResolver,
|
|
URI,
|
|
} = require('@theia/core');
|
|
const { EditorManager } = require('@theia/editor/lib/browser');
|
|
const { WorkspaceService } = require('@theia/workspace/lib/browser');
|
|
const { WebSocketConnectionProvider } = require('@theia/core/lib/browser/messaging/ws-connection-provider');
|
|
const { StatusBar, StatusBarAlignment } = require('@theia/core/lib/browser/status-bar/status-bar');
|
|
const { DiffUris } = require('@theia/core/lib/browser/diff-uris');
|
|
const { DraftStore } = require('./drafts.cjs');
|
|
const Service = Symbol('WishForgeFrontendCoordination');
|
|
const vector = documents =>
|
|
JSON.stringify(
|
|
documents.map(d => ({ uri: d.uri, version: d.version, dirty: d.dirty })).sort((a, b) => a.uri.localeCompare(b.uri)),
|
|
);
|
|
|
|
class FrontendCoordination {
|
|
constructor(services) {
|
|
Object.assign(this, services);
|
|
this.drafts = new DraftStore(window.indexedDB);
|
|
this.tracked = new Map();
|
|
this.frozen = new Map();
|
|
this.controller = false;
|
|
this.busy = false;
|
|
this.draftWarning = false;
|
|
}
|
|
documents() {
|
|
const documents = new Map();
|
|
for (const widget of this.editors.all) {
|
|
const doc = {
|
|
uri: widget.editor.uri.toString(),
|
|
version: widget.editor.document.version,
|
|
dirty: widget.editor.document.dirty,
|
|
};
|
|
const previous = documents.get(doc.uri);
|
|
if (previous && previous.version !== doc.version) throw new Error('Conflicting editor versions for one document');
|
|
documents.set(doc.uri, { ...doc, dirty: doc.dirty || previous?.dirty === true });
|
|
}
|
|
return [...documents.values()];
|
|
}
|
|
async onStart() {
|
|
this.rpc = this.connection.createProxy('/services/wishforge-coordination', {
|
|
prepareSnapshot: () => this.prepareSnapshot(),
|
|
confirmSnapshot: docs => this.confirmSnapshot(docs),
|
|
releaseSnapshot: () => this.releaseSnapshot(),
|
|
debugGranted: () => {
|
|
this.controller = true;
|
|
return this.heartbeat();
|
|
},
|
|
});
|
|
this.rpc.onDidCloseConnection?.(() => {
|
|
this.releaseSnapshot();
|
|
this.controller = false;
|
|
});
|
|
this.editors.onCreated(widget => this.track(widget));
|
|
for (const widget of this.editors.all) this.track(widget);
|
|
await this.heartbeat();
|
|
this.timer = setInterval(() => this.heartbeat(), 5000);
|
|
window.addEventListener('pagehide', () => {
|
|
for (const widget of this.editors.all) this.persistDraft(widget);
|
|
});
|
|
}
|
|
async heartbeat() {
|
|
try {
|
|
this.identity = await this.rpc.register(this.documents());
|
|
this.scope = `${this.identity.workspaceId}/${this.identity.actorId}`;
|
|
if (this.controller) await this.rpc.acquireDebug();
|
|
const state = await this.rpc.status();
|
|
this.status.setElement('wishforge-coordination', {
|
|
text: `$(cloud-upload) Saved r${state.revision}${this.controller ? ' · Debug control' : ''}`,
|
|
alignment: StatusBarAlignment.RIGHT,
|
|
priority: 5,
|
|
tooltip: 'WishForge coordinated snapshot and draft recovery',
|
|
command: 'wishforge.snapshot',
|
|
});
|
|
if (!this.recoveryNotified) {
|
|
this.recoveryNotified = true;
|
|
const saved = await this.drafts.list(this.scope);
|
|
if (saved.length)
|
|
this.messages.info(
|
|
`${saved.length} unconfirmed draft(s) are available. Use WishForge: Recover Unsaved Draft to compare them with saved files.`,
|
|
);
|
|
}
|
|
} catch {
|
|
this.controller = false;
|
|
this.status.setElement('wishforge-coordination', {
|
|
text: '$(warning) Coordination unavailable',
|
|
alignment: StatusBarAlignment.RIGHT,
|
|
priority: 5,
|
|
tooltip: 'Snapshots and debug control require authenticated workspace coordination.',
|
|
});
|
|
}
|
|
}
|
|
pathFor(widget) {
|
|
const current = widget.editor.uri;
|
|
for (const root of this.workspace.tryGetRoots()) {
|
|
const prefix = root.resource.path.toString().replace(/\/$/, '') + '/';
|
|
if (current.scheme === root.resource.scheme && current.path.toString().startsWith(prefix))
|
|
return current.path.toString().slice(prefix.length);
|
|
}
|
|
return undefined;
|
|
}
|
|
track(widget) {
|
|
if (this.tracked.has(widget)) return;
|
|
const state = {
|
|
id: window.crypto.randomUUID(),
|
|
baseText: widget.editor.document.getText(),
|
|
wasDirty: widget.editor.document.dirty,
|
|
};
|
|
this.tracked.set(widget, state);
|
|
const change = () => {
|
|
if (!state.timer)
|
|
state.timer = setTimeout(() => {
|
|
state.timer = undefined;
|
|
this.persistDraft(widget);
|
|
}, 120);
|
|
this.rpc?.register(this.documents()).catch(() => {});
|
|
};
|
|
widget.editor.document.onContentChanged(change);
|
|
widget.editor.document.onDirtyChanged(change);
|
|
if (this.busy) this.freeze(widget);
|
|
}
|
|
async persistDraft(widget) {
|
|
const state = this.tracked.get(widget);
|
|
if (!state || !this.scope) return;
|
|
const doc = widget.editor.document;
|
|
const relative = this.pathFor(widget);
|
|
if (!relative) return;
|
|
try {
|
|
if (doc.dirty) {
|
|
state.wasDirty = true;
|
|
await this.drafts.put({
|
|
id: state.id,
|
|
scope: this.scope,
|
|
path: relative,
|
|
uri: widget.editor.uri.toString(),
|
|
text: doc.getText(),
|
|
baseText: state.baseText,
|
|
version: doc.version,
|
|
updatedAt: Date.now(),
|
|
});
|
|
} else if (state.wasDirty) {
|
|
await this.drafts.remove(state.id);
|
|
state.baseText = doc.getText();
|
|
state.wasDirty = false;
|
|
}
|
|
} catch (error) {
|
|
if (!this.draftWarning) {
|
|
this.draftWarning = true;
|
|
this.messages.warn(`Draft recovery storage unavailable: ${error.message}`);
|
|
}
|
|
}
|
|
}
|
|
freeze(widget) {
|
|
if (this.frozen.has(widget)) return;
|
|
const control = widget.editor.getControl?.();
|
|
if (!control?.updateOptions) throw new Error('This editor cannot be frozen for a coordinated snapshot');
|
|
const previous = control.getRawOptions?.().readOnly ?? widget.editor.readOnly ?? false;
|
|
this.frozen.set(widget, { control, previous });
|
|
control.updateOptions({ readOnly: true });
|
|
}
|
|
async prepareSnapshot() {
|
|
if (this.busy) throw new Error('Editor is already participating in a save barrier');
|
|
this.busy = true;
|
|
for (const w of this.editors.all) this.freeze(w);
|
|
try {
|
|
await this.shell.saveAll();
|
|
const docs = this.documents();
|
|
if (docs.some(doc => doc.dirty)) throw new Error('Unconfirmed or unsaved documents prevent the snapshot');
|
|
return docs;
|
|
} catch (error) {
|
|
this.releaseSnapshot();
|
|
throw error;
|
|
}
|
|
}
|
|
confirmSnapshot(expected) {
|
|
const docs = this.documents();
|
|
if (!this.busy || vector(docs) !== vector(expected) || docs.some(doc => doc.dirty))
|
|
throw new Error('Document versions changed during the save barrier');
|
|
return docs;
|
|
}
|
|
releaseSnapshot() {
|
|
for (const { control, previous } of this.frozen.values()) control.updateOptions({ readOnly: previous });
|
|
this.frozen.clear();
|
|
this.busy = false;
|
|
return true;
|
|
}
|
|
registerCommands(commands) {
|
|
commands.registerCommand(
|
|
{ id: 'wishforge.snapshot', label: 'Create Verified Workspace Snapshot', category: 'WishForge' },
|
|
{
|
|
execute: async () => {
|
|
try {
|
|
const snapshot = await this.rpc.snapshot();
|
|
await this.heartbeat();
|
|
this.messages.info(`Saved workspace revision ${snapshot.revision} (${snapshot.digest.slice(0, 12)}).`);
|
|
} catch (error) {
|
|
this.messages.error(`Snapshot refused: ${error.message}`);
|
|
}
|
|
},
|
|
},
|
|
);
|
|
commands.registerCommand(
|
|
{ id: 'wishforge.recover-draft', label: 'Recover Unsaved Draft', category: 'WishForge' },
|
|
{ execute: () => this.recover() },
|
|
);
|
|
commands.registerCommand(
|
|
{ id: 'wishforge.debug-acquire', label: 'Acquire Debug Control', category: 'WishForge' },
|
|
{
|
|
execute: async () => {
|
|
try {
|
|
await this.rpc.acquireDebug();
|
|
this.controller = true;
|
|
await this.heartbeat();
|
|
this.messages.info('Debug control acquired for this client.');
|
|
} catch (error) {
|
|
this.messages.error(error.message);
|
|
}
|
|
},
|
|
},
|
|
);
|
|
commands.registerCommand(
|
|
{ id: 'wishforge.debug-release', label: 'Release Debug Control', category: 'WishForge' },
|
|
{
|
|
execute: async () => {
|
|
await this.rpc.releaseDebug();
|
|
this.controller = false;
|
|
await this.heartbeat();
|
|
},
|
|
},
|
|
);
|
|
commands.registerCommand(
|
|
{ id: 'wishforge.debug-transfer', label: 'Transfer Debug Control', category: 'WishForge' },
|
|
{
|
|
execute: async () => {
|
|
try {
|
|
const peers = (await this.rpc.peers()).filter(p => p.clientId !== this.identity?.clientId);
|
|
const picked = await this.quick.pick(
|
|
peers.map(p => ({ label: p.actorId, description: p.clientId, value: p.clientId })),
|
|
{ title: 'Transfer control to a connected workspace client' },
|
|
);
|
|
if (picked) {
|
|
await this.rpc.transferDebug(picked.value);
|
|
this.controller = false;
|
|
await this.heartbeat();
|
|
}
|
|
} catch (error) {
|
|
this.messages.error(error.message);
|
|
}
|
|
},
|
|
},
|
|
);
|
|
}
|
|
async recover() {
|
|
try {
|
|
if (!this.scope) throw new Error('Authenticated workspace identity unavailable');
|
|
const records = await this.drafts.list(this.scope);
|
|
const picked = await this.quick.pick(
|
|
records.map(record => ({
|
|
label: record.path,
|
|
description: new Date(record.updatedAt).toLocaleString(),
|
|
record,
|
|
})),
|
|
{ title: 'Compare an unconfirmed draft with the saved file' },
|
|
);
|
|
if (!picked) return;
|
|
const draft = picked.record;
|
|
const saved = await this.rpc.readSaved(draft.path);
|
|
const resource = await this.untitled.createUntitledResource(draft.text, draft.path.split('.').at(-1));
|
|
const left = new URI('mem-txt-readonly:/Saved-file').withQuery(saved.content);
|
|
await open(this.opener, DiffUris.encode(left, resource.uri, `Saved ↔ recovered ${draft.path}`));
|
|
this.messages.info(
|
|
saved.content === draft.baseText
|
|
? 'Draft opened as an unsaved recovery copy. Review and Save As to apply it.'
|
|
: 'The saved file changed after this draft. Review the comparison before applying the recovery copy.',
|
|
);
|
|
} catch (error) {
|
|
this.messages.error(`Draft recovery: ${error.message}`);
|
|
}
|
|
}
|
|
}
|
|
function bindCoordination(bind) {
|
|
bind(Service)
|
|
.toDynamicValue(
|
|
ctx =>
|
|
new FrontendCoordination({
|
|
editors: ctx.container.get(EditorManager),
|
|
workspace: ctx.container.get(WorkspaceService),
|
|
shell: ctx.container.get(ApplicationShell),
|
|
messages: ctx.container.get(MessageService),
|
|
quick: ctx.container.get(QuickInputService),
|
|
untitled: ctx.container.get(UntitledResourceResolver),
|
|
opener: ctx.container.get(OpenerService),
|
|
connection: ctx.container.get(WebSocketConnectionProvider),
|
|
status: ctx.container.get(StatusBar),
|
|
}),
|
|
)
|
|
.inSingletonScope();
|
|
bind(FrontendApplicationContribution).toService(Service);
|
|
bind(CommandContribution).toService(Service);
|
|
}
|
|
module.exports = { bindCoordination, FrontendCoordination };
|