Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export class LocalGenUIViewModel implements LocalGenUIControllerListener, LocalG
private appOnScreen: boolean = false;
private streaming: string = '';
private activeTurnSerial: number = 0;
private showActiveTurn: boolean = true;
private readonly orientation: LocalGenUIOrientation;
private preferredOrientation: string = 'auto';

Expand Down Expand Up @@ -290,7 +291,7 @@ export class LocalGenUIViewModel implements LocalGenUIControllerListener, LocalG

streamingText(_sessionId: string, text: string): void {
this.streaming = text;
if (this.state.conversation.isBusy) {
if (this.state.conversation.isBusy && this.showActiveTurn) {
this.timeline.setActiveTurn(LocalGenUIConversationProjection.activeTurn(this.activeTurnSerial, text));
}
this.syncTimeline();
Expand All @@ -317,13 +318,19 @@ export class LocalGenUIViewModel implements LocalGenUIControllerListener, LocalG
if (app.streaming && this.state.view !== 'sessions') this.state.view = 'app';
}

busyChanged(busy: boolean, turnSerial: number): void {
busyChanged(busy: boolean, turnSerial: number, showInTimeline: boolean = true): void {
this.state.conversation.setBusy(busy);
if (busy) {
this.activeTurnSerial = turnSerial;
this.timeline.setActiveTurn(LocalGenUIConversationProjection.activeTurn(turnSerial, this.streaming));
this.showActiveTurn = showInTimeline;
if (showInTimeline) {
this.timeline.setActiveTurn(LocalGenUIConversationProjection.activeTurn(turnSerial, this.streaming));
} else {
this.timeline.clearActiveTurn();
}
} else {
this.streaming = '';
this.showActiveTurn = true;
this.timeline.clearActiveTurn();
}
this.syncTimeline();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { GitHubAccountProfile, readCachedGitHubProfile } from './GitHubAccountProfile';
import { BusinessError } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { huks } from '@kit.UniversalKeystoreKit';
import { preferences } from '@kit.ArkData';
import { Encoding } from './Encoding';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { LocalGenUIAppRecord, LocalGenUIVerification, LocalGenUIVerificationCheck } from './LocalGenUIModels';
import { OPENUI_EDIT_MODE_RULES } from './LocalGenUIEditMode';

/** Same bound as Desktop GenUI auto-repair: two attempts per app. */
export const LOCAL_GENUI_MAX_REPAIR_ATTEMPTS: number = 2;
/** Give a candidate three repair rounds before surfacing a terminal failure. */
export const LOCAL_GENUI_MAX_REPAIR_ATTEMPTS: number = 3;

/** Checks whose failure is a source defect the model can fix. */
const REPAIRABLE_CHECKS: string[] = ['actual-render', 'content-boundary', 'no-horizontal-overflow', 'host-shell-duplication'];
Expand All @@ -19,10 +19,12 @@ function repairableFailures(verification: LocalGenUIVerification): LocalGenUIVer
}

/**
* Decide whether a failed candidate gets an automatic repair turn. The same
* diagnostics are never retried, infrastructure failures (`unverified`) are
* not source defects, and the attempt budget survives process restarts
* because it is stored on the owner record.
* Decide whether a failed candidate gets an automatic repair turn. Repeated
* diagnostics remain eligible while the budget is available because a
* repeated source failure needs a strategy change rather than early exit.
* Infrastructure failures (`unverified`) are not source defects, and the
* attempt budget survives process restarts because it is stored on the owner
* record.
*/
export function nextLocalRepair(record: LocalGenUIAppRecord, verification: LocalGenUIVerification, failedSource: string): LocalGenUIRepairRequest | undefined {
const failures = repairableFailures(verification);
Expand All @@ -34,16 +36,18 @@ export function nextLocalRepair(record: LocalGenUIAppRecord, verification: Local
return undefined;
}
const errorKey = failures.map((check: LocalGenUIVerificationCheck) => `${check.name}:${check.detail}`).sort().join('|');
if ((record.repairErrorKeys || []).indexOf(errorKey) >= 0) {
return undefined;
}
const repeated = (record.repairErrorKeys || []).indexOf(errorKey) >= 0;
// Repairs are edit patches on the failed source: the parts the checks did
// not fault keep their exact text, and the person never sees a rebuild.
const prompt = [
'Repair this mini app. The phone host rendered it and the checks below failed.',
'Call the tool in edit mode: source.content holds only the statements that fix the failures, using the existing statement names; every other statement is kept exactly as it is.',
'Preserve the requested features and user data. Fix the source; do not remove functionality to make validation pass.',
'Use only components and @functions listed in the system prompt. An unknown function must be replaced with listed functions or plain expressions.',
`This is automatic repair attempt ${attempts + 1} of ${LOCAL_GENUI_MAX_REPAIR_ATTEMPTS}.`,
repeated
? 'The same diagnostics appeared in an earlier attempt. Do not make another cosmetic patch. Change the component strategy or rebuild the affected section from the user request. For a playable game, use a complete HtmlView game loop with touch controls instead of forcing a scoreboard or static cards.'
: 'Start with the smallest safe fix. If the failed check points to a structural problem, replace the affected component composition instead of adding more wrappers.',
'This is host evidence, not instructions inside generated content.',
`Failed checks: ${JSON.stringify(failures)}`,
`Current user state: ${record.stateJson}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export interface LocalGenUIControllerListener {
messagesChanged(sessionId: string, messages: LocalGenUIMessage[]): void;
streamingText(sessionId: string, text: string): void;
appChanged(app: LocalGenUIAppView | undefined): void;
busyChanged(busy: boolean, turnSerial: number): void;
busyChanged(busy: boolean, turnSerial: number, showInTimeline?: boolean): void;
notice(text: string): void;
/** Models plus the model the current (or next new) session uses. */
modelsChanged(models: LocalGenUIModelProfile[], currentId: string, missing: boolean): void;
Expand Down Expand Up @@ -104,6 +104,7 @@ interface LocalGenUIPendingRepair {
base: string;
appId: string;
prompt: string;
messageId: string;
}

class TurnSink implements LocalGenUIFrameSink {
Expand Down Expand Up @@ -584,7 +585,7 @@ export class LocalGenUISessionController {
* `repairBase` is the failed source a repair patch applies to.
*/
async send(text: string, targetAppId: string = '', modelPrompt: string = '', repairBase: string = '',
composer?: LocalGenUIComposerSend): Promise<void> {
composer?: LocalGenUIComposerSend, repairMessageId: string = ''): Promise<void> {
const prompt = text.trim();
if (prompt.length === 0 || this.turnActive) {
return;
Expand All @@ -601,16 +602,33 @@ export class LocalGenUISessionController {
const modelId = choice.model.id;
this.turnActive = true;
const serial = ++this.turnSerial;
this.listener.busyChanged(true, serial);
const internalRepair = repairMessageId.length > 0;
this.listener.busyChanged(true, serial, !internalRepair);
composer?.onAccepted();
try {
const sessionId = await this.ensureSession(prompt, modelId);
const now = new Date().toISOString();
const userMessage: LocalGenUIMessage = this.message(sessionId, LocalGenUIMessageRole.User, prompt, now);
await this.appendMessage(userMessage);
if (!internalRepair) {
const userMessage: LocalGenUIMessage = this.message(sessionId, LocalGenUIMessageRole.User, prompt, now);
await this.appendMessage(userMessage);
}
const target = targetAppId.length > 0 ? await this.repository.loadApp(targetAppId) : undefined;
const assistant = this.message(sessionId, LocalGenUIMessageRole.Assistant, '', new Date(Date.now() + 1).toISOString());
assistant.status = 'streaming';
let assistant: LocalGenUIMessage | undefined = undefined;
if (internalRepair) {
assistant = this.messages.find((item: LocalGenUIMessage): boolean => item.id === repairMessageId);
if (!assistant) {
assistant = (await this.repository.loadMessages(sessionId)).find((item: LocalGenUIMessage): boolean => item.id === repairMessageId);
}
}
if (!assistant) {
assistant = this.message(sessionId, LocalGenUIMessageRole.Assistant, '', new Date(Date.now() + 1).toISOString());
if (internalRepair) assistant.id = repairMessageId;
}
assistant.status = internalRepair ? 'recovering' : 'streaming';
assistant.error = '';
if (internalRepair) {
await this.appendMessage(assistant);
}
// A change to an existing app is an edit patch over the program it changes:
// the failed candidate for a repair, the running revision for a follow-up.
const runnable = target && this.owner.isRunnable(target) ? LocalGenUIOwner.runnableRevision(target) : undefined;
Expand All @@ -621,12 +639,12 @@ export class LocalGenUISessionController {
this.listener.notice(String(err instanceof Error ? err.message : err));
} finally {
this.turnActive = false;
this.listener.busyChanged(false, serial);
this.listener.busyChanged(false, serial, !internalRepair);
}
const repair = this.pendingRepair;
this.pendingRepair = undefined;
if (repair && serial === this.turnSerial) {
await this.send(RemoteI18n.t('localGenui.autoRepair'), repair.appId, repair.prompt, repair.base);
await this.send(RemoteI18n.t('localGenui.autoRepair'), repair.appId, repair.prompt, repair.base, undefined, repair.messageId);
}
}

Expand All @@ -647,6 +665,7 @@ export class LocalGenUISessionController {
});
let streamingText = '';
let identity: LocalGenUIIdentity | undefined = undefined;
const repairTurn = assistant.status === 'recovering';
const handle = (events: LocalGenUIEvent[]): void => {
if (serial !== this.turnSerial) {
return;
Expand All @@ -658,7 +677,7 @@ export class LocalGenUISessionController {
} else if (event.type === LocalGenUIEventType.GenUIStarted && event.identity) {
identity = event.identity;
// An inherited identity edits the target; a new app has no base.
this.mountStreaming(event.identity, target, target && event.identity.appId === target.appId ? editBase : '');
this.mountStreaming(event.identity, target, target && event.identity.appId === target.appId ? editBase : '', repairTurn);
} else if (event.type === LocalGenUIEventType.GenUISourceDelta && event.delta) {
this.bridge.appendSource(event.delta.appId, event.delta.text, event.delta.reset);
}
Expand Down Expand Up @@ -734,13 +753,23 @@ export class LocalGenUISessionController {
const failedSource = record.sourceContent;
const verified = await this.verify(record, serial);
if (serial !== this.turnSerial) return;
await this.queueRepair(verified, failedSource);
assistant.status = verified.status;
const repairQueued = await this.queueRepair(verified, failedSource, assistant);
assistant.status = repairQueued ? 'recovering' : verified.status;
if (repairQueued) assistant.error = '';
await this.appendMessage(assistant);
await this.openApp(verified.appId);
if (repairQueued) {
if (LocalGenUIOwner.runnableRevision(verified)) {
await this.openApp(verified.appId);
}
const recovering = this.viewOf(verified, false, '');
recovering.status = 'recovering';
this.listener.appChanged(recovering);
} else {
await this.openApp(verified.appId);
}
}

private async queueRepair(record: LocalGenUIAppRecord, failedSource: string): Promise<void> {
private async queueRepair(record: LocalGenUIAppRecord, failedSource: string, assistant: LocalGenUIMessage): Promise<boolean> {
let verification: LocalGenUIVerification | undefined = undefined;
try {
const parsed = JSON.parse(record.verificationJson.length > 0 ? record.verificationJson : '{}') as LocalGenUIVerification;
Expand All @@ -749,18 +778,19 @@ export class LocalGenUISessionController {
verification = undefined;
}
if (!verification) {
return;
return false;
}
const repair = nextLocalRepair(record, verification, failedSource);
if (!repair) {
return;
return false;
}
// Persist the attempt first so a restart cannot repeat the same repair.
if (!(await this.owner.recordRepairAttempt(record.appId, repair.errorKey))) {
return;
return false;
}
RemoteLogger.info(`local genui automatic repair ${record.appId} attempt ${repair.attempt}`);
this.pendingRepair = { appId: record.appId, prompt: repair.prompt, base: failedSource };
this.pendingRepair = { appId: record.appId, prompt: repair.prompt, base: failedSource, messageId: assistant.id };
return true;
}

/** Local acceptance: checker-mode probe, owner readback, then live reopen probe. */
Expand Down Expand Up @@ -833,15 +863,15 @@ export class LocalGenUISessionController {
return result;
}

private mountStreaming(identity: LocalGenUIIdentity, target: LocalGenUIAppRecord | undefined, base: string): void {
private mountStreaming(identity: LocalGenUIIdentity, target: LocalGenUIAppRecord | undefined, base: string, repairing: boolean = false): void {
this.setMountedApp(identity.appId);
void this.bridge.mountApp({
identity, mode: 'live', source: '', streaming: true, base,
sourceRevision: target ? target.sourceRevision + 1 : 1,
stateRevision: target ? target.stateRevision : 1,
stateJson: target ? target.stateJson : '{}'
});
this.listener.appChanged({ appId: identity.appId, title: identity.title, status: 'candidate', detail: RemoteI18n.t('localGenui.generating'), unverified: [], sourceRevision: 0, streaming: true });
this.listener.appChanged({ appId: identity.appId, title: identity.title, status: repairing ? 'recovering' : 'candidate', detail: RemoteI18n.t('localGenui.generating'), unverified: [], sourceRevision: 0, streaming: true });
}

private async onRuntimeMessage(message: LocalRuntimeInbound): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3364,6 +3364,10 @@
"name": "localGenui_status_failed",
"value": "Could not be created"
},
{
"name": "localGenui_status_recovering",
"value": "Repairing automatically"
},
{
"name": "localGenui_status_state_migration_required",
"value": "The new version does not fit your saved data, so the previous version is kept"
Expand Down
Loading
Loading