From 0e2517ad6f23013e885c0a08588eb7a5b24336af Mon Sep 17 00:00:00 2001 From: Yang Zhang Date: Fri, 2 Oct 2026 18:31:19 -0700 Subject: [PATCH 1/3] fix(workflow-form): let a card change its operator's siblings the way the panel does, so the HuggingFace task change persists on the form An exposed HuggingFace model picker on the Form View offered a task selector that could not persist: the card wrote back only the property it was bound to, under the binding's id, and the operator's other properties were a read-only copy with no controls. Changing the task on the form switched the model list but saved nothing, so a reader could pick a model for a task the operator does not run. The Form View is another way to show the canvas, so a card now behaves like the operator property panel for the property it exposes. The field keeps the property's own key; the operator's other properties ride along as plain controls on the card's form and in its model, so a widget that reads or writes a sibling by key (the HuggingFace picker writes task and resets the task-scoped fields) finds the same controls as on the panel; and the card writes back everything that differs from the operator in one edit (FormBindingService.writeProperties), the bound property and the siblings a widget changed. An empty string and an absent property count as the same value, so formly's blank for a property the operator never had is not written on every build. Two more things the two views needed to agree, found with both open on one workflow: the form held every rebuild while a closed dropdown kept the focus (its search box counted as typing), so a change made on the canvas never showed until the reader clicked elsewhere -- a dropdown is typing only while its list is open; and the HuggingFace selector on the canvas kept showing the task it was built with when the form (or a co-editor) changed it -- it now follows its field's model on every check, as a local pick is followed (the panel hides the schema's task field, so there is no control to listen to). Closes #8762 Co-Authored-By: Claude Fable 5.1 --- .../hugging-face.component.spec.ts | 323 ++++++++++++++++- .../hugging-face/hugging-face.component.ts | 71 +++- .../workflow-form.component.spec.ts | 334 ++++++++++++++++-- .../workflow-form/workflow-form.component.ts | 107 +++++- .../workflow-form.rendered.spec.ts | 38 ++ .../workflow-form.spec-harness.ts | 1 + .../form-binding/form-binding.service.spec.ts | 18 + .../form-binding/form-binding.service.ts | 16 +- 8 files changed, 858 insertions(+), 50 deletions(-) diff --git a/frontend/src/app/workspace/component/hugging-face/hugging-face.component.spec.ts b/frontend/src/app/workspace/component/hugging-face/hugging-face.component.spec.ts index da53a0f20ec..a22f1e93943 100644 --- a/frontend/src/app/workspace/component/hugging-face/hugging-face.component.spec.ts +++ b/frontend/src/app/workspace/component/hugging-face/hugging-face.component.spec.ts @@ -20,7 +20,7 @@ import { ComponentFixture, TestBed, discardPeriodicTasks, fakeAsync, tick } from "@angular/core/testing"; import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; import { By } from "@angular/platform-browser"; -import { FormControl, FormGroup } from "@angular/forms"; +import { FormControl, FormGroup, UntypedFormGroup } from "@angular/forms"; import { FieldTypeConfig } from "@ngx-formly/core"; import { Subject } from "rxjs"; import { AppSettings } from "../../../common/app-setting"; @@ -224,6 +224,70 @@ describe("HuggingFaceComponent (TestBed)", () => { flushIconRequests(); } + // ── On a Form View card ── + // The card keys the bound field `modelId` and carries the operator's other properties as plain + // controls and in the model; nothing else is built. A task change must reach the card's form the + // way it reaches the panel's, since the card writes back what changed on its form and model. + describe("on a Form View card", () => { + const taskScopedKeys = [ + "task", + "promptColumn", + "imageInput", + "audioInput", + "inputImageColumn", + "inputAudioColumn", + "candidateLabels", + "sentencesColumn", + "contextColumn", + "systemPrompt", + "maxNewTokens", + "temperature", + ]; + + function formCard(task: string, modelId: string) { + const model: Record = { task, modelId, promptColumn: "prompt" }; + const formGroup = new UntypedFormGroup({ modelId: new FormControl(modelId) }); + for (const key of taskScopedKeys) { + formGroup.addControl(key, new FormControl(model[key] ?? null)); + } + const field = { + key: "modelId", + formControl: formGroup.get("modelId")!, + form: formGroup, + model, + props: {}, + parent: { fieldGroup: [] }, + options: buildFormlyOptions(), + } as unknown as FieldTypeConfig; + return { field, formGroup, model }; + } + + it("writes a task change to the card's form and resets the model with it, as on the panel", () => { + const { field, formGroup, model } = formCard("image-classification", "google/vit-base-patch16-224"); + component.field = field; + fixture.detectChanges(); + flushIconRequests(); + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + http.expectOne(req => req.url.startsWith(`${API}/huggingface/models`)).flush(buildModels(2)); + flushIconRequests(); + const emissions: unknown[] = []; + formGroup.valueChanges.subscribe(value => emissions.push(value)); + + component.onTaskSelected("text-generation"); + http.expectOne(req => req.url.startsWith(`${API}/huggingface/models`)).flush(buildModels(2, "qwen")); + flushIconRequests(); + + expect(model.task).toBe("text-generation"); + expect(formGroup.get("task")!.value).toBe("text-generation"); + // The task-scoped fields are reset for the new task, the model's own value included. + expect(model.modelId).toBe(""); + expect(formGroup.get("modelId")!.value).toBe(""); + expect(model.promptColumn).toBe(""); + // The card's form heard it; that is what the card's write-back listens to. + expect(emissions.length).toBeGreaterThan(0); + }); + }); + // ── Creation ── it("should create the component", () => { @@ -238,6 +302,143 @@ describe("HuggingFaceComponent (TestBed)", () => { // ── Task loading ── + // The task can change under the widget: a co-editor on the canvas, or the Form View, writes the + // operator, and the change arrives on this field's model (the panel hands formly a fresh model; + // the schema's own task field is hidden there, so no control carries it). The selector used to + // keep showing the task it was built with, and its model list with it. + describe("following a task change that arrives on the model", () => { + it("shows the new task and loads its models", () => { + const { field } = buildFieldWithFormGroup("image-classification"); + component.field = field; + fixture.detectChanges(); + flushIconRequests(); + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + http.expectOne(req => req.url.startsWith(`${API}/huggingface/models`)).flush(buildModels(2)); + flushIconRequests(); + + (field.model as Record)["task"] = "text-generation"; + fixture.detectChanges(); + + const reload = http.expectOne(req => req.url.startsWith(`${API}/huggingface/models`)); + expect(reload.request.url).toContain("task=text-generation"); + reload.flush(buildModels(2, "qwen")); + expect(component.selectedTaskTag).toBe("text-generation"); + }); + + // A slow first fetch of one task can land after the widget has moved on: a task whose models + // are already cached is shown at once, by a path that returns before the request still out is + // cancelled (Copilot on #8839). Whatever comes back for a task the widget has left is cached + // for the next asker and not shown here. + it("ignores a response for a task it has already left", () => { + const { field } = buildFieldWithFormGroup("text-generation"); + component.field = field; + fixture.detectChanges(); + flushIconRequests(); + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + // text-generation is cached from here on. + http.expectOne(req => req.url.includes("task=text-generation")).flush(buildModels(2, "qwen")); + flushIconRequests(); + + // Away to a task that has to be fetched: its request is still out. + (field.model as Record)["task"] = "image-classification"; + fixture.detectChanges(); + const slow = http.expectOne(req => req.url.includes("task=image-classification")); + + // Back to the cached task, which is shown at once and leaves the request out. + (field.model as Record)["task"] = "text-generation"; + fixture.detectChanges(); + flushIconRequests(); + expect(component.selectedTaskTag).toBe("text-generation"); + const shown = component.pagedModels; + + // The left task's response lands last; it must not paint over the task now shown. + slow.flush(buildModels(3, "resnet")); + flushIconRequests(); + + expect(component.selectedTaskTag).toBe("text-generation"); + expect(component.pagedModels).toBe(shown); + expect(component.pagedModels.every(model => !model.id.includes("resnet"))).toBe(true); + }); + + it("ignores a failure for a task it has already left", () => { + const { field } = buildFieldWithFormGroup("text-generation"); + component.field = field; + fixture.detectChanges(); + flushIconRequests(); + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + http.expectOne(req => req.url.includes("task=text-generation")).flush(buildModels(2, "qwen")); + flushIconRequests(); + + (field.model as Record)["task"] = "image-classification"; + fixture.detectChanges(); + const slow = http.expectOne(req => req.url.includes("task=image-classification")); + + (field.model as Record)["task"] = "text-generation"; + fixture.detectChanges(); + flushIconRequests(); + + slow.error(new ProgressEvent("error")); + flushIconRequests(); + + // The error belongs to the task that was left; the one on show is fine. + expect(component.errorMessage).toBeNull(); + expect(component.pagedModels.length).toBe(2); + }); + + // A load that waits on another instance's request polls for it; that poll belongs to the task + // it was started for, and the next load stops it whichever path the next load takes. + it("stops a poll left from an earlier task", () => { + const { field } = buildFieldWithFormGroup("text-generation"); + component.field = field; + fixture.detectChanges(); + flushIconRequests(); + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + // text-generation is cached; its request is no longer in flight. + http.expectOne(req => req.url.includes("task=text-generation")).flush(buildModels(2, "qwen")); + flushIconRequests(); + + // A task whose request stays out: it is now the in-flight one. + (field.model as Record)["task"] = "image-classification"; + fixture.detectChanges(); + const slow = http.expectOne(req => req.url.includes("task=image-classification")); + + // Asking for it again waits on that request instead of firing a second one: a poll. + (field.model as Record)["task"] = "text-generation"; + fixture.detectChanges(); + (field.model as Record)["task"] = "image-classification"; + fixture.detectChanges(); + http.expectNone(req => req.url.includes("task=image-classification")); + expect((component as any).modelPollInterval).not.toBeNull(); + + // Moving to the cached task stops that poll, by a path that returns before the in-flight one. + (field.model as Record)["task"] = "text-generation"; + fixture.detectChanges(); + flushIconRequests(); + + expect((component as any).modelPollInterval).toBeNull(); + slow.flush(buildModels(3, "resnet")); + flushIconRequests(); + expect(component.selectedTaskTag).toBe("text-generation"); + }); + + it("does nothing for the task it already shows, or for a blank", () => { + const { field } = buildFieldWithFormGroup("image-classification"); + component.field = field; + fixture.detectChanges(); + flushIconRequests(); + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + http.expectOne(req => req.url.startsWith(`${API}/huggingface/models`)).flush(buildModels(2)); + flushIconRequests(); + + fixture.detectChanges(); + (field.model as Record)["task"] = ""; + fixture.detectChanges(); + + http.expectNone(req => req.url.startsWith(`${API}/huggingface/models`)); + expect(component.selectedTaskTag).toBe("image-classification"); + }); + }); + describe("task loading", () => { it("should fetch tasks from the API on init", () => { const { field } = buildFieldWithFormGroup(); @@ -611,6 +812,64 @@ describe("HuggingFaceComponent (TestBed)", () => { expect(component.searchLoading).toBe(false); })); + // A task change clears the search but cannot cancel one already out: switchMap only drops a + // search the next search replaces (Copilot on #8839). + it("ignores search results for a task it has already left", fakeAsync(() => { + const { field } = buildFieldWithFormGroup("text-generation"); + component.field = field; + fixture.detectChanges(); + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + http + .expectOne(req => req.url.includes("task=text-generation")) + .flush(buildModels(5), { headers: { "X-Texera-Truncated": "true" } }); + + component.onSearchInput("special-model"); + tick(300); + const search = http.expectOne(req => req.url.includes("search=special-model")); + + // The task changes while that search is out, and its own models arrive. + (field.model as Record)["task"] = "image-classification"; + fixture.detectChanges(); + http.expectOne(req => req.url.includes("task=image-classification")).flush(buildModels(2, "resnet")); + expect(component.selectedTaskTag).toBe("image-classification"); + + // The search was made for the task being left, so it is cancelled rather than left to come + // back and be judged (Copilot). What it would have shown never reaches the list. + expect(search.cancelled).toBe(true); + expect(component.pagedModels.every(model => !model.id.includes("special-model"))).toBe(true); + })); + + // The search ends with the task it was made for: its answer is dropped for being the other + // task's, so nothing else would turn the spinner off and the widget would read as searching + // for an empty string (Copilot on #8839). + it("stops showing a search when the task changes under one that is still out", fakeAsync(() => { + const { field } = buildFieldWithFormGroup("text-generation"); + component.field = field; + fixture.detectChanges(); + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + http + .expectOne(req => req.url.includes("task=text-generation")) + .flush(buildModels(5), { headers: { "X-Texera-Truncated": "true" } }); + + component.onSearchInput("special-model"); + tick(300); + const search = http.expectOne(req => req.url.includes("search=special-model")); + expect(component.searchLoading).toBe(true); + expect(component.isSearching).toBe(true); + + (field.model as Record)["task"] = "image-classification"; + fixture.detectChanges(); + http.expectOne(req => req.url.includes("task=image-classification")).flush(buildModels(2, "resnet")); + + expect(component.searchText).toBe(""); + expect(component.searchLoading).toBe(false); + expect(component.isSearching).toBe(false); + + // Nothing is left out to turn the spinner back on: the request went with the task. + expect(search.cancelled).toBe(true); + expect(component.pagedModels.every(model => !model.id.includes("special-model"))).toBe(true); + })); + it("should reset pagination to page 0 on search", () => { initComponent("text-generation", buildModels(120)); @@ -1018,6 +1277,68 @@ describe("HuggingFaceComponent (TestBed)", () => { expect(component.pagedModels.length).toBe(2); expect(component.pagedModels[0].id).toBe("result-2a"); })); + + // A query typed and then overtaken by a task change: without dropping the search subscription + // it sat in the 300 ms debounce, went out under the new task, and came back past the task guard + // -- filtering the new task's list under a search box the task change had emptied (Copilot). + it("drops a query still in the debounce when the task changes under it", fakeAsync(() => { + const { field } = buildFieldWithFormGroup("text-generation"); + component.field = field; + fixture.detectChanges(); + flushIconRequests(); + + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + http + .expectOne(req => req.url.includes("task=text-generation")) + .flush(buildModels(5), { headers: { "X-Texera-Truncated": "true" } }); + flushIconRequests(); + + component.onSearchInput("bert"); + tick(100); // still inside the debounce + + (field.model as Record)["task"] = "image-classification"; + fixture.detectChanges(); + http + .expectOne(req => req.url.includes("task=image-classification")) + .flush(buildModels(3, "img"), { headers: { "X-Texera-Truncated": "true" } }); + flushIconRequests(); + + tick(500); // past what was left of the debounce + + http.expectNone(req => req.url.includes("search=bert")); + expect(component.searchText).toBe(""); + expect(component.isSearching).toBe(false); + expect(component.pagedModels.length).toBe(3); + })); + + it("still searches after a task change, under the task now shown", fakeAsync(() => { + const { field } = buildFieldWithFormGroup("text-generation"); + component.field = field; + fixture.detectChanges(); + flushIconRequests(); + + http.expectOne(`${API}/huggingface/tasks`).flush(buildTaskResponse()); + http + .expectOne(req => req.url.includes("task=text-generation")) + .flush(buildModels(5), { headers: { "X-Texera-Truncated": "true" } }); + flushIconRequests(); + + (field.model as Record)["task"] = "image-classification"; + fixture.detectChanges(); + http + .expectOne(req => req.url.includes("task=image-classification")) + .flush(buildModels(3, "img"), { headers: { "X-Texera-Truncated": "true" } }); + flushIconRequests(); + + component.onSearchInput("vit"); + tick(300); + + const search = http.expectOne(req => req.url.includes("search=vit")); + expect(search.request.url).toContain("task=image-classification"); + search.flush([{ id: "google/vit", label: "google/vit" }]); + + expect(component.pagedModels.map(m => m.id)).toEqual(["google/vit"]); + })); }); // ── getCurrentTaskTag fallbacks ── diff --git a/frontend/src/app/workspace/component/hugging-face/hugging-face.component.ts b/frontend/src/app/workspace/component/hugging-face/hugging-face.component.ts index 4925656425c..9529ed957be 100644 --- a/frontend/src/app/workspace/component/hugging-face/hugging-face.component.ts +++ b/frontend/src/app/workspace/component/hugging-face/hugging-face.component.ts @@ -17,7 +17,7 @@ * under the License. */ -import { Component, OnInit, OnDestroy, ChangeDetectorRef } from "@angular/core"; +import { Component, OnInit, OnDestroy, ChangeDetectorRef, DoCheck } from "@angular/core"; import { CommonModule } from "@angular/common"; import { FormsModule } from "@angular/forms"; import { FieldType, FieldTypeConfig, FormlyModule } from "@ngx-formly/core"; @@ -129,7 +129,7 @@ export function invalidateHuggingFaceModelCache(): void { FormlyModule, ], }) -export class HuggingFaceComponent extends FieldType implements OnInit, OnDestroy { +export class HuggingFaceComponent extends FieldType implements OnInit, OnDestroy, DoCheck { private readonly taskScopedKeys = [ "modelId", "promptColumn", @@ -173,6 +173,8 @@ export class HuggingFaceComponent extends FieldType implements private searchSubscription: Subscription | null = null; private readonly destroy$ = new Subject(); + /** Set once ngOnInit has read the model's task, which is what ngDoCheck then follows. */ + private initialized = false; private subscription: Subscription | null = null; private taskPollInterval: ReturnType | null = null; private modelPollInterval: ReturnType | null = null; @@ -188,6 +190,7 @@ export class HuggingFaceComponent extends FieldType implements ngOnInit(): void { const savedTag = this.getCurrentTaskTag(); this.selectedTaskTag = savedTag ?? this.selectedTaskTag; + this.initialized = true; this.syncTaskSelection(this.selectedTaskTag, false); this.loadTasks(); this.loadAllModels(); @@ -200,6 +203,26 @@ export class HuggingFaceComponent extends FieldType implements ); } + /** + * The task can change under this widget: a co-editor's edit, or the Form View's, lands on the + * operator and from there on this field's model (the panel hands formly a fresh model object; the + * form card is rebuilt). The selector shows this widget's own state, and on the panel the schema's + * `task` field is hidden, so there is no control to listen to: the model is checked on every + * change detection instead, and the selector follows it as a local pick is followed -- show the + * task, load its models -- rather than keeping what it showed when it was built. + */ + ngDoCheck(): void { + const tag = this.model?.task; + if (!this.initialized || typeof tag !== "string" || !tag || tag === this.selectedTaskTag) { + return; + } + this.selectedTaskTag = tag; + // A task change ends any search, including one still out: its answer is dropped for being the + // other task's, so it is not the one to turn the spinner off (Copilot on #8839). + this.resetSearch(); + this.loadAllModels(); + } + ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); @@ -314,8 +337,7 @@ export class HuggingFaceComponent extends FieldType implements this.snapshotTaskState(previousTask); this.syncTaskSelection(tag, true); this.restoreTaskState(tag); - this.searchText = ""; - this.filteredModels = null; + this.resetSearch(); this.loadAllModels(); } @@ -328,6 +350,17 @@ export class HuggingFaceComponent extends FieldType implements */ private loadAllModels(): void { const tag = this.selectedTaskTag || "text-generation"; + // Nothing a load produces is applied once the widget has moved to another task: the fast paths + // below return before the previous request is cancelled, so a slow first fetch of one task could + // land after a cached task was already shown and paint its models under the other task's name + // (Copilot on #8839; also reachable on main by picking a second task while the first loads). + const stillShowing = () => tag === (this.selectedTaskTag || "text-generation"); + // A poll left over from an earlier task belongs to that task, whichever path this load takes: + // the fast paths below return before the in-flight path's own clear would run. + if (this.modelPollInterval !== null) { + clearInterval(this.modelPollInterval); + this.modelPollInterval = null; + } this.loading = false; this.errorMessage = null; @@ -352,7 +385,6 @@ export class HuggingFaceComponent extends FieldType implements // Another instance is already fetching this task — wait for it if (inFlightByTag.has(tag)) { this.loading = true; - if (this.modelPollInterval !== null) clearInterval(this.modelPollInterval); const poll = setInterval(() => { if (allModelsByTag.has(tag) || errorByTag.has(tag)) { clearInterval(poll); @@ -407,6 +439,11 @@ export class HuggingFaceComponent extends FieldType implements truncatedByTag.add(tag); } allModelsByTag.set(tag, models); + // The cache is filled for whoever asks next; this widget shows it only if it is still on + // that task. + if (!stillShowing()) { + return; + } this.loading = false; this.truncated = truncatedByTag.has(tag); this.allModels = models; @@ -416,6 +453,9 @@ export class HuggingFaceComponent extends FieldType implements console.error(`Failed to load HuggingFace models for task '${tag}':`, err); const msg = "Failed to load models. Click retry to try again."; errorByTag.set(tag, msg); + if (!stillShowing()) { + return; + } this.loading = false; this.errorMessage = msg; this.cdr.detectChanges(); @@ -490,6 +530,9 @@ export class HuggingFaceComponent extends FieldType implements .subscribe({ next: models => { if (models === null) return; + // Whatever arrives here was asked for under the task still shown: switchMap drops a search + // the next search replaces, and a task change drops this whole subscription (resetSearch), + // taking the request with it. So there is no stale answer left to recognise. this.searchLoading = false; this.filteredModels = models; this.goToPage(0); @@ -517,10 +560,26 @@ export class HuggingFaceComponent extends FieldType implements } clearSearch(): void { + this.resetSearch(); + this.goToPage(0); + } + + /** + * Forget the search: the text, the results it filtered to, the spinner it was waiting on, and the + * query itself. + * + * The subscription is dropped and remade rather than left alone, which drops both a query still + * sitting in the debounce and a request already out. Clearing the first three alone left a typed + * query queued: 300 ms later it went out under whichever task the widget had by then, and the + * answer passed the task guard and filtered the list under a search box the reset had emptied + * (Copilot on #8839). + */ + private resetSearch(): void { this.searchText = ""; this.filteredModels = null; this.searchLoading = false; - this.goToPage(0); + this.searchSubscription?.unsubscribe(); + this.setupServerSearch(); } get isSearching(): boolean { diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts index 8b2975dacef..d3c83bf0c8b 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts @@ -896,13 +896,15 @@ describe("WorkflowFormComponent", () => { (component as any).readConfig(); }; - it("renders a healthy input as a real formly field keyed by its binding id", () => { + it("renders a healthy input as a real formly field keyed by its property, as the panel does", () => { build(formViewWorkflow).ngOnInit(); renderOne("n_hvg"); expect(component.rendered).toHaveLength(1); - expect(component.rendered[0].fields[0].key).toBe(component.rendered[0].resolved.binding.id); + // The property's own key, not the binding's: a widget that reaches itself or a sibling by key + // (the HuggingFace picker resetting `modelId` on a task change) finds the same keys here. + expect(component.rendered[0].fields[0].key).toBe("n_hvg"); }); it("renders nothing for an input whose operator is no longer on the graph", () => { @@ -978,7 +980,7 @@ describe("WorkflowFormComponent", () => { expect(component.rendered[0].fields[0].type).toBe("inputautocomplete"); }); - it("seeds the field model with the operator's other properties as read-only context", () => { + it("seeds the field model with the operator's other properties, as controls too, like the panel", () => { build(formViewWorkflow).ngOnInit(); h.hasOperatorIds.add("op-1"); // A HuggingFace operator whose model picker (modelId) needs the sibling `task` to work. @@ -994,8 +996,145 @@ describe("WorkflowFormComponent", () => { const card = component.rendered[0]; // The sibling context is present (so the widget reads the right task) ... expect(card.model.task).toBe("image-classification"); - // ... alongside this input's own value, keyed by the binding id, which is what writes back. - expect(card.model[card.resolved.binding.id]).toBe("seed"); + // ... alongside this input's own value, under the property's own key, as on the panel. + expect(card.model["modelId"]).toBe("seed"); + // The siblings ride along as controls too, so the widget finds `task` on the card's form the + // way it finds it on the panel's. + expect(card.form.get("task")?.value).toBe("image-classification"); + }); + + // A widget may change a sibling the way it does on the panel (the HuggingFace picker writes + // `task` and resets the task-scoped fields on a task change); the card writes it back with the + // bound value, as one edit, the way the panel does. + it("writes back a sibling a widget changed, along with the bound value", () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "HuggingFace", + operatorProperties: { task: "image-classification", modelId: "seed" }, + }); + renderOne("modelId"); + const card = component.rendered[0]; + vi.useFakeTimers(); + + // The widget's task change, as it makes it: the sibling through its control, its own value + // reset in the model (a dirtied control, so the blank is an edit, not formly's build default). + card.form.get("task")!.setValue("text-generation"); + card.model["modelId"] = ""; + card.form.markAsDirty(); + vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); + vi.useRealTimers(); + + expect(formBindingService.writeProperties).toHaveBeenCalledWith("op-1", { task: "text-generation", modelId: "" }); + }); + + // The patch is what this card changed since it was built, not every difference from the + // operator as it is now: a sibling someone else changed in the meantime is not this card's to + // send back, or the older value would land on top of the newer one (Copilot on #8839). + it("writes only what this card changed, leaving a sibling someone else changed alone", () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "HuggingFace", + operatorProperties: { task: "image-classification", modelId: "seed" }, + }); + renderOne("modelId"); + const card = component.rendered[0]; + vi.useFakeTimers(); + + // The canvas, a co-editor or another card changes the sibling after this card was built. + h.graphOperators[0].operatorProperties = { task: "text-generation", modelId: "seed" }; + // This card changes only its own value. + card.model["modelId"] = "gpt2"; + card.form.markAsDirty(); + card.form.get("task")!.updateValueAndValidity(); + vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); + vi.useRealTimers(); + + expect(formBindingService.writeProperties).toHaveBeenCalledWith("op-1", { modelId: "gpt2" }); + }); + + it("advances its baseline after a write, so a second edit sends only the second change", () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "HuggingFace", + operatorProperties: { task: "image-classification", modelId: "seed" }, + }); + renderOne("modelId"); + const card = component.rendered[0]; + vi.useFakeTimers(); + + card.form.get("task")!.setValue("text-generation"); + card.form.markAsDirty(); + vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); + expect(formBindingService.writeProperties).toHaveBeenLastCalledWith("op-1", { task: "text-generation" }); + + card.model["modelId"] = "gpt2"; + card.form.get("task")!.updateValueAndValidity(); + vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); + vi.useRealTimers(); + + // The task it already wrote is not sent again. + expect(formBindingService.writeProperties).toHaveBeenLastCalledWith("op-1", { modelId: "gpt2" }); + expect(formBindingService.writeProperties).toHaveBeenCalledTimes(2); + }); + + // The schema may declare a property the operator has no value for yet; the widget still finds a + // control for it, empty, and nothing is written for it unless something changes it. + it("gives a schema property without a value an empty control, and leaves it out of a write-back", () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "HuggingFace", + operatorProperties: { task: "image-classification", modelId: "seed" }, + }); + (component as any).dynamicSchemaService = { + getDynamicSchema: () => ({ jsonSchema: { properties: { modelId: {}, task: {}, hfApiToken: {} } } }), + }; + renderOne("modelId"); + const card = component.rendered[0]; + expect(card.form.get("hfApiToken")?.value).toBeNull(); + vi.useFakeTimers(); + + card.form.get("task")!.setValue("text-generation"); + vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); + vi.useRealTimers(); + + expect(formBindingService.writeProperties).toHaveBeenCalledWith("op-1", { task: "text-generation" }); + }); + + it("lands a sibling control's change in the model, which is what is written back", () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "HuggingFace", + operatorProperties: { task: "image-classification", modelId: "seed" }, + }); + renderOne("modelId"); + const card = component.rendered[0]; + + card.form.get("task")!.setValue("text-generation"); + + expect(card.model.task).toBe("text-generation"); + }); + + it("writes nothing when a sibling control re-emits an unchanged value", () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "HuggingFace", + operatorProperties: { task: "image-classification", modelId: "seed" }, + }); + renderOne("modelId"); + const card = component.rendered[0]; + vi.useFakeTimers(); + + card.form.get("task")!.setValue("image-classification"); + vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); + vi.useRealTimers(); + + expect(formBindingService.writeProperties).not.toHaveBeenCalled(); }); it("prefers the per-instance schema, falling back to the static one when it is unavailable", () => { @@ -1058,7 +1197,7 @@ describe("WorkflowFormComponent", () => { build(formViewWorkflow).ngOnInit(); renderOne("n_hvg"); const card = component.rendered[0]; - const key = card.resolved.binding.id; + const key = card.resolved.binding.propertyKey; vi.useFakeTimers(); card.model[key] = "typed"; @@ -1067,7 +1206,7 @@ describe("WorkflowFormComponent", () => { vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); vi.useRealTimers(); - expect(formBindingService.writeValue).toHaveBeenCalled(); + expect(formBindingService.writeProperties).toHaveBeenCalled(); }); it("keeps a still-set value when a control emits an absent value before an edit", () => { @@ -1088,10 +1227,10 @@ describe("WorkflowFormComponent", () => { it("ignores an unchanged form emission", () => { build(formViewWorkflow).ngOnInit(); - formBindingService.readValue.mockReturnValue("seed"); + h.graphOperators.push({ operatorID: "op-1", operatorProperties: { n_hvg: "seed" } }); renderOne("n_hvg"); const card = component.rendered[0]; - const key = card.resolved.binding.id; + const key = card.resolved.binding.propertyKey; vi.useFakeTimers(); card.model[key] = "seed"; @@ -1099,15 +1238,15 @@ describe("WorkflowFormComponent", () => { vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); vi.useRealTimers(); - expect(formBindingService.writeValue).not.toHaveBeenCalled(); + expect(formBindingService.writeProperties).not.toHaveBeenCalled(); }); it("keeps a still-set value when formly emits a blank before an edit", () => { build(formViewWorkflow).ngOnInit(); - formBindingService.readValue.mockReturnValue("seed"); + h.graphOperators.push({ operatorID: "op-1", operatorProperties: { n_hvg: "seed" } }); renderOne("n_hvg"); const card = component.rendered[0]; - const key = card.resolved.binding.id; + const key = card.resolved.binding.propertyKey; vi.useFakeTimers(); card.model[key] = ""; @@ -1115,14 +1254,52 @@ describe("WorkflowFormComponent", () => { vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); vi.useRealTimers(); - expect(formBindingService.writeValue).not.toHaveBeenCalled(); + expect(formBindingService.writeProperties).not.toHaveBeenCalled(); + }); + + // formly fills a blank for a string the operator never had; writing that back on every build + // put an empty property on the operator that the canvas's own form had left out. + it("writes nothing when formly's blank meets a property the operator never had", () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ operatorID: "op-1", operatorProperties: { other: 1 } }); + renderOne("n_hvg"); + const card = component.rendered[0]; + vi.useFakeTimers(); + + card.model["n_hvg"] = ""; + card.form.addControl("n_hvg", new FormControl("")); + vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); + vi.useRealTimers(); + + expect(formBindingService.writeProperties).not.toHaveBeenCalled(); + }); + + // A widget clearing a task-scoped sibling the operator never had writes a blank where there was + // nothing: to an operator those are the same, so nothing is sent. + it("takes a blank for a property the operator never had as no change", () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "HuggingFace", + operatorProperties: { modelId: "seed", task: "image-classification" }, + }); + renderOne("modelId"); + const card = component.rendered[0]; + vi.useFakeTimers(); + + card.model["promptColumn"] = ""; + card.form.get("task")!.updateValueAndValidity(); + vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); + vi.useRealTimers(); + + expect(formBindingService.writeProperties).not.toHaveBeenCalled(); }); it("refreshes the card's snapshot after a write-back", () => { build(formViewWorkflow).ngOnInit(); renderOne("n_hvg"); const card = component.rendered[0]; - const key = card.resolved.binding.id; + const key = card.resolved.binding.propertyKey; // The re-read after a write returns the new value on the same binding. formBindingService.resolveFields.mockReturnValue([resolved("n_hvg", "n_hvg", { value: "typed" })]); vi.useFakeTimers(); @@ -1141,7 +1318,7 @@ describe("WorkflowFormComponent", () => { renderOne("n_hvg"); const card = component.rendered[0]; const before = card.resolved; - const key = card.resolved.binding.id; + const key = card.resolved.binding.propertyKey; // The write succeeds, but the following resolve returns nothing for this binding. formBindingService.resolveFields.mockReturnValue([]); vi.useFakeTimers(); @@ -1152,7 +1329,7 @@ describe("WorkflowFormComponent", () => { vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); vi.useRealTimers(); - expect(formBindingService.writeValue).toHaveBeenCalled(); + expect(formBindingService.writeProperties).toHaveBeenCalled(); expect(component.rendered[0].resolved).toBe(before); }); @@ -1684,11 +1861,30 @@ describe("WorkflowFormComponent", () => { expect(rebuild).not.toHaveBeenCalled(); }); + // A binding's id is its own, not the property it writes to, and a card's model is the operator's + // properties keyed by property (so a widget reaching a sibling finds the panel's keys). Reading + // the card's value under the id found nothing and read every card as out of step. + it("compares a card's value under the property it is bound to, not under the binding's id", async () => { + build(formViewWorkflow).ngOnInit(); + h.hasOperatorIds.add("op-1"); + formBindingService.resolveFields.mockReturnValue([ + resolved("field-7", "HVG count", { + binding: { id: "field-7", operatorID: "op-1", propertyKey: "n_hvg", displayName: "HVG count" }, + value: "2000", + }), + ]); + formBindingService.readValue.mockReturnValue("2000"); + (component as any).readConfig(); + + expect(component.rendered[0].model["n_hvg"]).toBe("2000"); + expect((component as any).cardsNeedRebuild()).toBe(false); + }); + it("does not rebuild for the card's own edit still on its way to the operator, nor once it is written", () => { build(formViewWorkflow).ngOnInit(); renderCard("n_hvg", "2000"); const card = component.rendered[0]; - const key = card.resolved.binding.id; + const key = card.resolved.binding.propertyKey; vi.useFakeTimers(); // The first change marks the edit pending; the operator still holds the old value. @@ -1701,7 +1897,9 @@ describe("WorkflowFormComponent", () => { // Written after the debounce: the operator now holds it, so the two agree. vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); vi.useRealTimers(); - expect(formBindingService.writeValue).toHaveBeenCalledWith(card.resolved.binding, "2500"); + expect(formBindingService.writeProperties).toHaveBeenCalledWith(card.resolved.binding.operatorID, { + [key]: "2500", + }); expect(card.pendingWrite).toBe(false); formBindingService.readValue.mockReturnValue("2500"); expect((component as any).cardsNeedRebuild()).toBe(false); @@ -1711,20 +1909,22 @@ describe("WorkflowFormComponent", () => { build(formViewWorkflow).ngOnInit(); renderCard("n_hvg", "2000"); const card = component.rendered[0]; - const key = card.resolved.binding.id; + const key = card.resolved.binding.propertyKey; vi.useFakeTimers(); card.model[key] = "2500"; card.form.addControl(key, new FormControl("2500")); card.form.markAsDirty(); - expect(formBindingService.writeValue).not.toHaveBeenCalled(); + expect(formBindingService.writeProperties).not.toHaveBeenCalled(); // A rebuild from any source (a step renamed, the definition edited) before the debounce fires. (component as any).readConfig(); vi.advanceTimersByTime(FORM_DEBOUNCE_TIME_MS + 50); vi.useRealTimers(); - expect(formBindingService.writeValue).toHaveBeenCalledTimes(1); - expect(formBindingService.writeValue).toHaveBeenCalledWith(card.resolved.binding, "2500"); + expect(formBindingService.writeProperties).toHaveBeenCalledTimes(1); + expect(formBindingService.writeProperties).toHaveBeenCalledWith(card.resolved.binding.operatorID, { + [key]: "2500", + }); expect(card.pendingWrite).toBe(false); }); @@ -1750,6 +1950,74 @@ describe("WorkflowFormComponent", () => { expect(rebuild).toHaveBeenCalledTimes(1); }); + // Closing an nz-select leaves the focus in its search box, so no focusout fires: a rebuild held + // while the list was open would have waited for an unrelated event (Copilot on #8839). + it("runs a held rebuild on a click, which is what closing a dropdown gives it", async () => { + build(formViewWorkflow).ngOnInit(); + // A compilation that changed a card's schema, so there is a rebuild to hold in the first place. + renderCard("n_hvg", "2000"); + changeSchema(); + const typing = vi.spyOn(component as any, "isTypingInTheForm").mockReturnValue(true); + const rebuild = vi.spyOn(component as any, "readConfig"); + + h.compilationChanged.next("Succeeded"); + await new Promise(r => setTimeout(r, FORM_DEBOUNCE_TIME_MS + 50)); + expect(rebuild).not.toHaveBeenCalled(); + + // The click that closed the list; by the time the re-check runs, it is no longer open. + typing.mockReturnValue(false); + component.onInteraction(); + await new Promise(r => setTimeout(r, 10)); + + expect(rebuild).toHaveBeenCalledTimes(1); + }); + + // Accepting an option with Enter both changes the form and closes the list, so the keyup runs + // the held rebuild straight away -- before the card's debounced write-back has fired. The + // rebuild writes that pending edit first (see buildForm), so the selection reaches the operator + // instead of being cancelled with the card's subscription (Copilot). + it("writes a selection made while a rebuild was held, rather than losing it to the rebuild", async () => { + build(formViewWorkflow).ngOnInit(); + renderCard("n_hvg", "2000"); + changeSchema(); + const typing = vi.spyOn(component as any, "isTypingInTheForm").mockReturnValue(true); + + h.compilationChanged.next("Succeeded"); + await new Promise(r => setTimeout(r, FORM_DEBOUNCE_TIME_MS + 50)); + + // The option accepted with Enter, its write-back not yet due. + const card = component.rendered[0]; + const key = card.resolved.binding.propertyKey; + card.model[key] = "2500"; + card.form.addControl(key, new FormControl("2500")); + card.form.markAsDirty(); + expect(card.pendingWrite).toBe(true); + + // The same keypress closed the list, so the held rebuild runs now. + typing.mockReturnValue(false); + component.onInteraction(); + await new Promise(r => setTimeout(r, 10)); + + expect(formBindingService.writeProperties).toHaveBeenCalledWith(card.resolved.binding.operatorID, { + [key]: "2500", + }); + }); + + it("leaves a click alone while the list is still open, so a filter being typed is not thrown away", async () => { + build(formViewWorkflow).ngOnInit(); + renderCard("n_hvg", "2000"); + changeSchema(); + vi.spyOn(component as any, "isTypingInTheForm").mockReturnValue(true); + const rebuild = vi.spyOn(component as any, "readConfig"); + + h.compilationChanged.next("Succeeded"); + await new Promise(r => setTimeout(r, FORM_DEBOUNCE_TIME_MS + 50)); + component.onInteraction(); + await new Promise(r => setTimeout(r, 10)); + + expect(rebuild).not.toHaveBeenCalled(); + }); + it("holds a rebuild while someone is typing and runs it once the focus leaves", async () => { build(formViewWorkflow).ngOnInit(); renderCard("n_hvg", "2000"); @@ -1864,6 +2132,28 @@ describe("WorkflowFormComponent", () => { document.body.removeChild(input); }); + // A dropdown (nz-select) leaves the focus on its search box after a pick. Counted as typing, + // every rebuild was held while the box kept the focus, so a change made on the canvas never + // reached the form until the reader clicked elsewhere. Typing it is only while the list is open. + it("does not count a closed dropdown's focused search box as typing, but an open one's", () => { + build(formViewWorkflow).ngOnInit(); + const dropdown = document.createElement("div"); + dropdown.className = "ant-select ant-select-single"; + const search = document.createElement("input"); + search.className = "ant-select-selection-search-input"; + dropdown.appendChild(search); + document.body.appendChild(dropdown); + (component as any).host = { nativeElement: { contains: () => true, querySelector: () => null } }; + search.focus(); + + expect((component as any).isTypingInTheForm()).toBe(false); + + dropdown.classList.add("ant-select-open"); + expect((component as any).isTypingInTheForm()).toBe(true); + + document.body.removeChild(dropdown); + }); + it("reports no typing when the focus is outside the page", () => { build(formViewWorkflow).ngOnInit(); (component as any).host = { nativeElement: { contains: () => false, querySelector: () => null } }; diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts index 39baf058f60..b2ac7b8c632 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts @@ -19,7 +19,7 @@ import { ChangeDetectorRef, Component, ElementRef, HostListener, OnDestroy, OnInit } from "@angular/core"; import { CommonModule, DatePipe } from "@angular/common"; -import { AbstractControl, FormArray, FormGroup, FormsModule, ReactiveFormsModule } from "@angular/forms"; +import { AbstractControl, FormArray, FormControl, FormGroup, FormsModule, ReactiveFormsModule } from "@angular/forms"; import { FormlyFieldConfig, FormlyModule } from "@ngx-formly/core"; import { FormlyJsonschema } from "@ngx-formly/core/json-schema"; import { ActivatedRoute, Router } from "@angular/router"; @@ -563,6 +563,32 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { */ @HostListener("focusout") public onFocusOut(): void { + this.flushHeldRebuild(); + } + + /** + * A click or a key also ends a hold, because a focus change is not the only thing that does: + * closing an nz-select leaves the focus in its search box (ng-zorro re-focuses it), so no focusout + * fires, and a rebuild held while the list was open would have waited for an unrelated event + * (Copilot on #8839). The same later() re-check as below decides it after the current tick, by + * when the dropdown has lost its open class. + * + * The click is listened for on the document, not on this host. A dropdown's options are drawn in + * the CDK's overlay container, a sibling of the whole app rather than a descendant of this page, + * so the click that picks one -- or that picks the option already chosen, which changes no value + * and moves no focus -- never bubbles through here (Copilot). A click anywhere else ends the hold + * for the same reason a focusout does: the reader is no longer typing into the card. The handler + * returns at once unless a rebuild is actually held. Keys stay on the host: what is typed goes + * into controls this page owns (nz-select keeps its search box in the trigger, not the overlay), + * and a document-wide key listener would run on every keystroke in the workspace. + */ + @HostListener("document:click") + @HostListener("keyup") + public onInteraction(): void { + this.flushHeldRebuild(); + } + + private flushHeldRebuild(): void { if (this.rebuildDeferred) { this.later(() => { if (this.rebuildDeferred) { @@ -744,6 +770,13 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { if (!active || !this.host.nativeElement.contains(active)) { return false; } + // A dropdown (nz-select) keeps the focus on its search box after a pick. That is typing only + // while the list is open and a filter can be typed; a closed dropdown that merely holds the + // focus held every rebuild, so a change made elsewhere (the canvas, a co-editor) never showed. + const dropdown = active.closest(".ant-select"); + if (dropdown) { + return dropdown.classList.contains("ant-select-open"); + } if (active.tagName === "INPUT") { return !NON_TEXT_INPUT_TYPES.has((active as HTMLInputElement).type); } @@ -918,8 +951,11 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { if (card.pendingWrite) { return false; } + // Keyed by the property, not the binding id: a card's model is the operator's properties and + // the field keeps the property's own key, so that a widget reaching a sibling finds the same + // keys it does on the panel (see renderField). return !sameValue( - card.model[binding.id], + card.model[binding.propertyKey], this.formBindingService.readValue(binding.operatorID, binding.propertyKey) ); }); @@ -1006,22 +1042,44 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { // The schema's own title ("Attributes", "Limit", "File") -- the reader's title when unnamed. // Falls back to this, not the lower-camel key ("fileName"), which would read inconsistently. const schemaLabel = (source.props?.label as string) || binding.propertyKey; - field.key = binding.id; + // The field keeps the property's own key, as on the operator property panel: a widget that + // reaches a sibling or itself by key (the HuggingFace picker resets `modelId` and its + // task-scoped siblings on a task change) must find the same controls and model keys here. field.props = { ...(field.props ?? {}), label: binding.displayName || schemaLabel, }; const form = new FormGroup({}); - // Seed the model with the operator's other properties as read-only context, not just this - // input's own value: some custom widgets read a sibling to decide what to show -- the - // HuggingFace model picker reads `task` to load the right models and label the field. Only - // this binding's value is ever written back (see below); the context is never persisted, and - // it is cloned so a widget that mutates it cannot reach through to the real operator. + // The card's model is the operator's properties, as the panel's is: the exposed value, and + // every other property as context a widget may read or change -- the HuggingFace model picker + // reads `task` to load the right models and, when the task is changed, resets the task-scoped + // siblings as it does on the panel. The copy is cloned so nothing reaches through to the real + // operator; what changes is written back below, as one edit, the way the panel writes. const model: Record = { ...cloneDeep(operator?.operatorProperties ?? {}), - [binding.id]: cloneDeep(resolved.value), + [binding.propertyKey]: cloneDeep(resolved.value), }; + // The other properties ride along as plain controls (formly builds only the exposed field), so + // a widget finds its siblings on the card's form exactly as on the panel's -- the HuggingFace + // picker writes `task` through its control, which is also what announces the change -- and a + // control-level write lands in the model, which is what is written back. + // What the card was built from, kept apart from the live model: the patch is what this card + // changed since then, not every difference from the operator as it is now. Diffing against the + // operator would have sent a sibling this card never touched but someone else had changed in + // the meantime -- the canvas, a co-editor, or another card on the same operator -- putting the + // stale value back over the newer one (Copilot on #8839). Advanced by every write below. + let baseline: Record = cloneDeep(model); + const schemaKeys = Object.keys((schema as { properties?: Record }).properties ?? {}); + const siblingKeys = [...new Set([...schemaKeys, ...Object.keys(model)])].filter(key => key !== binding.propertyKey); + for (const key of siblingKeys) { + const control = new FormControl(model[key] ?? null); + control.valueChanges.pipe(takeUntil(this.formsRebuilt), untilDestroyed(this)).subscribe(value => { + model[key] = value; + }); + form.addControl(key, control); + } + const card: RenderedField = { resolved, fields: [field], @@ -1034,20 +1092,33 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { if (this.canEdit) { card.flushWrite = () => { card.pendingWrite = false; - // Formly emits the schema's empty default while building the control, before any edit; - // writing that back silently wiped the operator's real value (both views edit one - // workflow). So only accept a dirtied form, or a value that differs from the operator's - // without being emptier (some controls set values without marking dirty). - const next = model[binding.id]; - const current = this.formBindingService.readValue(binding.operatorID, binding.propertyKey); + // What this card changed since it was built is written back: the bound property, and the + // siblings a widget changed with it. Formly emits the schema's empty default for the bound + // control while building it, before any edit; writing that back silently wiped the + // operator's real value (both views edit one workflow). So the bound property is taken + // only from a dirtied form, or when it differs without being emptier (some controls set + // values without marking dirty). const isEmpty = (v: unknown) => v === undefined || v === null || v === ""; - const unchanged = JSON.stringify(next ?? null) === JSON.stringify(current ?? null); - if (unchanged || (!form.dirty && isEmpty(next) && !isEmpty(current))) { + // An empty string and an absent property mean the same to an operator, and formly fills a + // blank for a string the operator never had: neither is a change of the other. + const asJson = (value: unknown) => JSON.stringify(value === "" ? null : value ?? null); + const differs = (key: string) => asJson(model[key]) !== asJson(baseline[key]); + const bound = binding.propertyKey; + const blankBeforeEdit = !form.dirty && isEmpty(model[bound]) && !isEmpty(baseline[bound]); + const patch = Object.fromEntries( + Object.keys(model) + .filter(key => differs(key) && !(key === bound && blankBeforeEdit)) + .map(key => [key, model[key]]) + ); + if (Object.keys(patch).length === 0) { return; } // Write straight onto the operator (the same edit the canvas makes) and refresh this // card's snapshot, which the template reads. - this.formBindingService.writeValue(binding, next); + this.formBindingService.writeProperties(binding.operatorID, patch); + // The card has caught up with what it just sent; anything else on the operator stays + // someone else's, and only a rebuild re-seeds this card with it. + baseline = { ...baseline, ...cloneDeep(patch) }; this.parameters = this.formBindingService.resolveFields(); const refreshed = this.parameters.find(p => p.binding.id === binding.id); if (refreshed) { diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.rendered.spec.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.rendered.spec.ts index 100205864a1..9cd08cfb8b0 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.rendered.spec.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.rendered.spec.ts @@ -329,6 +329,44 @@ describe("WorkflowFormComponent (rendered template)", () => { expect(spy).toHaveBeenCalled(); }); + // Closing an nz-select leaves the focus in its search box, so no focusout fires inside the page: + // a rebuild held while the list was open is flushed by the click itself (Copilot on #8839). The + // host binding is what makes that true, so it is exercised through a real event on the host. + it("flushes a held rebuild when a click reaches the page, not only on focusout", async () => { + fixture.detectChanges(); + finishLoad(); + const spy = vi.spyOn(fixture.componentInstance, "onInteraction"); + + fixture.nativeElement.dispatchEvent(new MouseEvent("click", { bubbles: true })); + fixture.nativeElement.dispatchEvent(new KeyboardEvent("keyup", { bubbles: true })); + + expect(spy).toHaveBeenCalledTimes(2); + }); + + // The options of a dropdown are drawn in the CDK's overlay container, outside this page, so the + // click that picks one never bubbles through the host. Picking the option already chosen changes + // no value and moves no focus either, so nothing else would end the hold (Copilot on #8839). + it("flushes a held rebuild when the click lands in a dropdown's overlay, outside the page", async () => { + fixture.detectChanges(); + finishLoad(); + const spy = vi.spyOn(fixture.componentInstance, "onInteraction"); + + const overlay = document.createElement("div"); + overlay.className = "cdk-overlay-container"; + const option = document.createElement("div"); + option.className = "ant-select-item-option"; + overlay.appendChild(option); + document.body.appendChild(overlay); + try { + expect(fixture.nativeElement.contains(option)).toBe(false); + option.dispatchEvent(new MouseEvent("click", { bubbles: true })); + } finally { + overlay.remove(); + } + + expect(spy).toHaveBeenCalledTimes(1); + }); + it("switches to the operator canvas when the Canvas control is clicked", () => { fixture.detectChanges(); finishLoad(); diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.spec-harness.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.spec-harness.ts index 0bce6e34ff9..c64a44e8eb6 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.spec-harness.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.spec-harness.ts @@ -205,6 +205,7 @@ export function setupHarness() { resolveFields: vi.fn().mockReturnValue([]), readValue: vi.fn().mockReturnValue(undefined), writeValue: vi.fn(), + writeProperties: vi.fn(), // A result card's friendly label; the mock returns the operator's display name or its id. operatorLabel: (op: any) => op?.customDisplayName ?? op?.operatorType ?? op?.operatorID, // Author-mode writes. Spied so a test can assert the edit was made without needing a real diff --git a/frontend/src/app/workspace/service/form-binding/form-binding.service.spec.ts b/frontend/src/app/workspace/service/form-binding/form-binding.service.spec.ts index cd32c277957..16c42f916fe 100644 --- a/frontend/src/app/workspace/service/form-binding/form-binding.service.spec.ts +++ b/frontend/src/app/workspace/service/form-binding/form-binding.service.spec.ts @@ -101,6 +101,24 @@ describe("FormBindingService", () => { expect(workflowActionService.getTexeraGraph().getOperator(scanId).operatorProperties["keep"]).toBe("me"); }); + + // A card's widget may change siblings along with the bound property, as it does on the panel; + // they land in one edit, over the operator's current properties. + it("writes several properties at once, over the current ones", () => { + workflowActionService.setOperatorProperty(scanId, { tableName: "twitter", keep: "me", limit: 5 }); + + service.writeProperties(scanId, { tableName: "reddit", limit: 10 }); + + expect(workflowActionService.getTexeraGraph().getOperator(scanId).operatorProperties).toEqual({ + tableName: "reddit", + keep: "me", + limit: 10, + }); + }); + + it("writing several properties to a missing operator is a no-op", () => { + expect(() => service.writeProperties("gone", { x: 1 })).not.toThrow(); + }); }); describe("resolving against the live graph", () => { diff --git a/frontend/src/app/workspace/service/form-binding/form-binding.service.ts b/frontend/src/app/workspace/service/form-binding/form-binding.service.ts index 2b55ab78048..df70fefdb79 100644 --- a/frontend/src/app/workspace/service/form-binding/form-binding.service.ts +++ b/frontend/src/app/workspace/service/form-binding/form-binding.service.ts @@ -209,13 +209,23 @@ export class FormBindingService { * why a run started from either one behaves identically. */ public writeValue(binding: FormFieldBinding, value: unknown): void { - const operator = this.getOperator(binding.operatorID); + this.writeProperties(binding.operatorID, { [binding.propertyKey]: value }); + } + + /** + * Write several properties of one operator at once, over its current ones: what a card's widget + * changed, which is the bound property and whatever siblings it touches the way it does on the + * operator property panel (the HuggingFace picker resets the task-scoped fields on a task + * change). One edit, as the panel makes one. + */ + public writeProperties(operatorID: string, patch: Record): void { + const operator = this.getOperator(operatorID); if (!operator) { return; } - this.workflowActionService.setOperatorProperty(binding.operatorID, { + this.workflowActionService.setOperatorProperty(operatorID, { ...operator.operatorProperties, - [binding.propertyKey]: value, + ...patch, }); } From f4ea02e8027bc2255844e6f9867292dcf7258fdf Mon Sep 17 00:00:00 2001 From: Yang Zhang Date: Mon, 2 Nov 2026 01:54:26 -0800 Subject: [PATCH 2/3] fix(workflow-form): queue one re-check per burst of keys while a rebuild is held, not one per key (review) Copilot on #8839: with a rebuild held, every keyup scheduled its own later() callback. A flushQueued flag makes the re-check single-flight, cleared when the callback runs so the next hold gets its own; a spec asserts five interactions queue one and run the held rebuild once, and that a later hold is re-checked again. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01FVvP3ttj22f9LB4p9u2anY --- .../workflow-form.component.spec.ts | 36 +++++++++++++++++++ .../workflow-form/workflow-form.component.ts | 19 ++++++---- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts index d3c83bf0c8b..50d2d1a90bd 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts @@ -2018,6 +2018,42 @@ describe("WorkflowFormComponent", () => { expect(rebuild).not.toHaveBeenCalled(); }); + // Typing into a card while a rebuild is held is a keyup per character, each of which asks for + // the same re-check (Copilot on #8839): one is queued for the burst, and it runs once. + it("queues one re-check for a burst of keys while a rebuild is held, not one per key", async () => { + build(formViewWorkflow).ngOnInit(); + renderCard("n_hvg", "2000"); + changeSchema(); + const typing = vi.spyOn(component as any, "isTypingInTheForm").mockReturnValue(true); + const rebuild = vi.spyOn(component as any, "readConfig"); + const queued = vi.spyOn(component as any, "later"); + const burst = (keys: number) => { + const before = queued.mock.calls.length; + for (let i = 0; i < keys; i++) { + component.onInteraction(); + } + return queued.mock.calls.length - before; + }; + + h.compilationChanged.next("Succeeded"); + await new Promise(r => setTimeout(r, FORM_DEBOUNCE_TIME_MS + 50)); + expect(burst(5)).toBe(1); + + // The last key closed the list: the one re-check runs the held rebuild, once. + typing.mockReturnValue(false); + await new Promise(r => setTimeout(r, 10)); + expect(rebuild).toHaveBeenCalledTimes(1); + + // With nothing held a key queues nothing, and the next hold gets a re-check of its own. + expect(burst(1)).toBe(0); + typing.mockReturnValue(true); + h.formBindingChanged.next(undefined); + expect(burst(3)).toBe(1); + typing.mockReturnValue(false); + await new Promise(r => setTimeout(r, 10)); + expect(rebuild).toHaveBeenCalledTimes(2); + }); + it("holds a rebuild while someone is typing and runs it once the focus leaves", async () => { build(formViewWorkflow).ngOnInit(); renderCard("n_hvg", "2000"); diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts index b2ac7b8c632..88d90860527 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts @@ -267,6 +267,8 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { private dirtySinceLastEnqueue = false; /** A rebuild of the inputs that arrived while the reader was typing, held until the typing ends. */ private rebuildDeferred = false; + /** A re-check of that hold is already queued: a burst of keys queues one, not one per key. */ + private flushQueued = false; /** Set while this page makes a presentation write, so the write's own announcement does not rebuild * the form under the control that took it (see reflectLocally). */ private reflectingLocally = false; @@ -589,13 +591,18 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { } private flushHeldRebuild(): void { - if (this.rebuildDeferred) { - this.later(() => { - if (this.rebuildDeferred) { - this.rebuildFormOrDefer(true); - } - }, 0); + // Typing into a card with a rebuild held is a keyup per character, each asking for this same + // re-check: one callback per burst, where every keystroke used to queue its own (Copilot). + if (!this.rebuildDeferred || this.flushQueued) { + return; } + this.flushQueued = true; + this.later(() => { + this.flushQueued = false; + if (this.rebuildDeferred) { + this.rebuildFormOrDefer(true); + } + }, 0); } private load(wid: number): void { From 99c7f3b5afeeb07d7169f0d46a01d6c3486d25a7 Mon Sep 17 00:00:00 2001 From: Yang Zhang Date: Fri, 27 Nov 2026 19:46:21 -0800 Subject: [PATCH 3/3] fix(workflow-form): advance a card's context key with its own write Review fix on #8839 (kunwp1). After a card wrote a sibling, its context key still described the operator as it was when the card was built, so the compilation the write triggered rebuilt the card: the HuggingFace picker was recreated and lost the state it keeps per task, and switching the task back blanked the model as a first visit does, where the panel's picker (which survives) restored it. The key now advances with the baseline, so only someone else's change rebuilds the card. It sorts keys at every level, since the shared model updates a nested object key by key and keeps its stored order, which would otherwise read back as a change. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01FVvP3ttj22f9LB4p9u2anY --- .../workflow-form.component.spec.ts | 38 +++++++++++++++++++ .../workflow-form/workflow-form.component.ts | 32 +++++++++++++--- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts index 50d2d1a90bd..7e4f7b70e28 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.spec.ts @@ -1715,6 +1715,44 @@ describe("WorkflowFormComponent", () => { expect(rebuild).toHaveBeenCalledTimes(1); }); + // The sibling a card itself wrote is not a change to its context: the HuggingFace picker writes + // `task`, and the compilation that write triggers rebuilt the card -- recreating the picker, + // which keeps its per-task state on the instance, so switching the task back blanked the model + // as a first visit does, where the panel's picker (which survives) restored it (kunwp1). The + // context key advances with the baseline, so only someone else's change counts. + it("keeps the card when the sibling that changed is the one it just wrote", async () => { + build(formViewWorkflow).ngOnInit(); + h.graphOperators.push({ + operatorID: "op-1", + operatorType: "HuggingFace", + operatorProperties: { modelId: "seed", task: "image-classification" }, + }); + // The write lands on the operator, as the real one does. + formBindingService.writeProperties.mockImplementation((_id: string, patch: Record) => { + h.graphOperators[0].operatorProperties = { ...h.graphOperators[0].operatorProperties, ...patch }; + }); + renderCard("modelId", "seed"); + const card = component.rendered[0]; + const rebuild = vi.spyOn(component as any, "readConfig"); + + card.form.get("task")!.setValue("text-generation"); + card.form.markAsDirty(); + // The debounced write runs ... + await new Promise(r => setTimeout(r, FORM_DEBOUNCE_TIME_MS + 50)); + expect(formBindingService.writeProperties).toHaveBeenCalledWith("op-1", { task: "text-generation" }); + // ... and the compilation it triggers comes back. + await compiled(); + + expect(rebuild).not.toHaveBeenCalled(); + expect(component.rendered[0]).toBe(card); + + // A sibling someone else changes afterwards still counts. + h.graphOperators[0].operatorProperties = { ...h.graphOperators[0].operatorProperties, task: "summarization" }; + await compiled(); + + expect(rebuild).toHaveBeenCalledTimes(1); + }); + // Two inputs from one step: each card's own property is the other card's sibling, so counting // bound properties as context would make one card's edit rebuild the other -- and with it the // card being edited, which is the churn this PR exists to stop (Copilot). diff --git a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts index 88d90860527..1866a119fae 100644 --- a/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts +++ b/frontend/src/app/workspace/component/workflow-form/workflow-form.component.ts @@ -973,15 +973,26 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { } /** - * The operator's properties other than the one a card is bound to, serialized with the keys - * sorted so a rewrite that only reorders them is not a change. This is the context the card is - * seeded with (see renderField): a widget reads a sibling to decide what to show, and nothing - * but a rebuild re-seeds it, so the card goes stale when the canvas or a co-editor changes one. + * The operator's properties other than the one a card is bound to, as the context key they make + * (see contextKeyOf). This is the context the card is seeded with (see renderField): a widget + * reads a sibling to decide what to show, and nothing but a rebuild re-seeds it, so the card goes + * stale when the canvas or a co-editor changes one. */ private contextKeyFor(operatorID: string): string { const graph = this.workflowActionService.getTexeraGraph(); // getOperator throws for an operator that is gone, so it is only safe behind hasOperator. const properties = graph.hasOperator(operatorID) ? graph.getOperator(operatorID)?.operatorProperties ?? {} : {}; + return this.contextKeyOf(operatorID, properties); + } + + /** + * The context key `properties` make for a card of this operator: the properties other than those + * an input is bound to, serialized with the keys sorted at every level, so a rewrite that only + * reorders them is not a change. Every level, because the shared model updates a nested object + * key by key and keeps its stored order, so a sibling written in another order reads back + * reordered. + */ + private contextKeyOf(operatorID: string, properties: Record): string { // Every property an input is bound to is left out, this card's own and any other card's on the // same operator: each is compared against the card that shows it, one by one. Counting them as // context too would make one card's edit a change to every other card of that operator, and a @@ -990,10 +1001,15 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { const bound = new Set( this.parameters.filter(field => field.binding.operatorID === operatorID).map(field => field.binding.propertyKey) ); + const byKey = ([a]: [string, unknown], [b]: [string, unknown]) => a.localeCompare(b); return JSON.stringify( Object.entries(properties) .filter(([key]) => !bound.has(key)) - .sort(([a], [b]) => a.localeCompare(b)) + .sort(byKey), + (_key, value: unknown) => + value !== null && typeof value === "object" && !Array.isArray(value) + ? Object.fromEntries(Object.entries(value as Record).sort(byKey)) + : value ); } @@ -1131,6 +1147,12 @@ export class WorkflowFormComponent implements OnInit, OnDestroy { if (refreshed) { card.resolved = refreshed; } + // The context key advances with the baseline: a sibling this card just wrote (the HuggingFace + // picker's `task`) is not a change to its context. Left at what the card was built from, the + // compilation the write triggers rebuilt the card, recreating the picker and losing the state + // it keeps per task, so switching back blanked the model as a first visit does, where the + // panel's picker, which survives, restored it (kunwp1). Only someone else's change rebuilds now. + card.contextKey = this.contextKeyOf(binding.operatorID, baseline); }; // The card holds an unwritten edit from the first change until the debounced write below has // run (or a rebuild has flushed it, see buildForm).