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
142 changes: 142 additions & 0 deletions src/choiceExecutor.dateScope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import realMoment from "moment";
import { App } from "obsidian";
import type QuickAdd from "./main";
import type IChoice from "./types/choices/IChoice";
import type { IChoiceExecutor } from "./IChoiceExecutor";
import { TemplateChoice } from "./types/choices/TemplateChoice";
import { MacroChoice } from "./types/choices/MacroChoice";
import { NestedChoiceCommand } from "./types/macros/QuickCommands/NestedChoiceCommand";
import { ChoiceAbortError } from "./errors/ChoiceAbortError";

vi.mock("./gui/choiceList/ChoiceView.svelte", () => ({}));
vi.mock("./gui/GlobalVariables/GlobalVariablesView.svelte", () => ({}));
vi.mock("./main", () => ({ __esModule: true, default: class QuickAddMock {} }));
vi.mock("./quickAddSettingsTab", () => ({ DEFAULT_SETTINGS: {}, QuickAddSettingsTab: class {} }));
vi.mock("./settingsStore", () => ({
settingsStore: { getState: () => ({ onePageInputEnabled: false, ai: {}, disableOnlineFeatures: true }) },
}));
vi.mock("./utils/frontmatterPropertyLinks", () => ({ getFocusedPropertyTarget: () => null }));
vi.mock("./utils/fileOpening", async (importOriginal) => ({
...await importOriginal<Record<string, unknown>>(),
getOpenFileOriginLeaf: () => null,
}));
const runTemplate = vi.fn<(executor: IChoiceExecutor, choice: IChoice) => Promise<void>>();
vi.mock("./engine/TemplateChoiceEngine", () => ({
TemplateChoiceEngine: class {
constructor(_app: unknown, _plugin: unknown, private choice: IChoice, private executor: IChoiceExecutor) {}
async run() { await runTemplate(this.executor, this.choice); }
},
}));

const { ChoiceExecutor } = await import("./choiceExecutor");
const { QuickAddApi } = await import("./quickAddApi");
const originalMoment = window.moment;
beforeAll(() => { window.moment = realMoment; });
afterAll(() => { window.moment = originalMoment; });

function executor() {
return new ChoiceExecutor(new App(), {} as QuickAdd);
}

describe("ChoiceExecutor date scope", () => {
const day = (date: Date | undefined) => realMoment(date).format("YYYY-MM-DD");

function datedTemplate(name: string, dateOrigin?: IChoice["dateOrigin"]) {
const choice = new TemplateChoice(name);
choice.dateOrigin = dateOrigin;
return choice;
}

beforeEach(() => { runTemplate.mockReset(); });

function recordDays() {
const days: Record<string, string> = {};
runTemplate.mockImplementation(async (active, choice) => { days[choice.name] = day(active.clocks?.date); });
return days;
}

it("gives each nested Template in a macro its own variable day", async () => {
const runner = executor();
const days = recordDays();
const macro = new MacroChoice("Macro");
macro.macro.commands = [
new NestedChoiceCommand(datedTemplate("Yesterday", { kind: "variable", name: "yesterday" })),
new NestedChoiceCommand(datedTemplate("Tomorrow", { kind: "variable", name: "tomorrow" })),
];
runner.variables.set("yesterday", "2026-01-02");
runner.variables.set("tomorrow", "2026-01-04");

await runner.execute(macro);

expect(days).toEqual({ Yesterday: "2026-01-02", Tomorrow: "2026-01-04" });
});

it("hands a macro's own day to every nested Template", async () => {
const runner = executor();
const days = recordDays();
const macro = new MacroChoice("Macro");
macro.dateOrigin = { kind: "variable", name: "day" };
macro.macro.commands = [
new NestedChoiceCommand(datedTemplate("First")),
new NestedChoiceCommand(datedTemplate("Second")),
];
runner.variables.set("day", "2026-01-02");

await runner.execute(macro);

expect(days).toEqual({ First: "2026-01-02", Second: "2026-01-02" });
});

it("gives each executeChoice call its own day and keeps it out of the caller", async () => {
const runner = executor();
const days = recordDays();
const choices = [
datedTemplate("Today template"),
datedTemplate("Variable template", { kind: "variable", name: "day" }),
];
const plugin = { getChoiceByName: (name: string) => choices.find((c) => c.name === name) } as unknown as QuickAdd;
const api = QuickAddApi.GetApi(new App(), plugin, runner);
const caller = datedTemplate("Caller");
runTemplate.mockImplementation(async (active, choice) => {
if (choice.name !== "Caller") {
days[`${choice.name} ${Object.keys(days).length}`] = day(active.clocks?.date);
return;
}
await api.executeChoice("Today template", {}, { date: "2026-01-02" });
await api.executeChoice("Today template", {}, { date: "2026-01-03" });
await api.executeChoice("Variable template", { day: "2026-01-04" });
await api.executeChoice("Variable template", { day: "2026-01-05" });
days.Caller = active.clocks?.date === undefined ? "today" : day(active.clocks.date);
});

await runner.execute(caller);

expect(days).toEqual({
"Today template 0": "2026-01-02",
"Today template 1": "2026-01-03",
"Variable template 2": "2026-01-04",
"Variable template 3": "2026-01-05",
Caller: "today",
});
});

it("keeps the caller's day when an executeChoice call fails", async () => {
const runner = executor();
const failing = datedTemplate("Failing");
const plugin = { getChoiceByName: () => failing } as unknown as QuickAdd;
const api = QuickAddApi.GetApi(new App(), plugin, runner);
const caller = datedTemplate("Caller", { kind: "variable", name: "callerDay" });
runner.variables.set("callerDay", "2026-01-10");
let callerDay: string | undefined;
runTemplate.mockImplementation(async (active, choice) => {
if (choice.name === "Failing") throw new ChoiceAbortError("failed");
await expect(api.executeChoice("Failing", {}, { date: "2026-01-02" })).rejects.toThrow("failed");
callerDay = day(active.clocks?.date);
});

await runner.execute(caller);

expect(callerDay).toBe("2026-01-10");
});
});
20 changes: 13 additions & 7 deletions src/choiceExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@ export class ChoiceExecutor implements IChoiceExecutor {
this.triggerContextOverride = this.triggerContext;
}

private beginExecutionContext(): void {
/** Returns the enclosing choice's clocks for {@link endExecutionContext} to restore. */
private beginExecutionContext(): RunClocks | undefined {
const enclosingClocks = this.clocks;
if (this.executionDepth === 0) {
this.focusedProperty =
this.focusedPropertyOverride !== undefined
Expand Down Expand Up @@ -135,11 +137,15 @@ export class ChoiceExecutor implements IChoiceExecutor {
};
}
this.executionDepth++;
return enclosingClocks;
}

private endExecutionContext(): void {
private endExecutionContext(enclosingClocks: RunClocks | undefined): void {
this.executionDepth = Math.max(0, this.executionDepth - 1);
if (this.executionDepth === 0) {
if (this.executionDepth > 0) {
// A choice's Which day covers the choice and what it runs, not the steps after it.
this.clocks = enclosingClocks;
} else {
this.focusedProperty = null;
this.triggerContext = null;
// A note named with setCurrentFile belongs to the run it was named for,
Expand Down Expand Up @@ -168,7 +174,7 @@ export class ChoiceExecutor implements IChoiceExecutor {
// enclosing executeWithOutcome(): snapshot and restore pendingResult so the nested
// choice's recorded result never leaks into the outer choice's reported outcome.
const savedResult = this.pendingResult;
this.beginExecutionContext();
const enclosingClocks = this.beginExecutionContext();
const originLeaf = getOpenFileOriginLeaf(this.app);
const promptDraftStore = InputPromptDraftStore.getInstance();
const draftScope = promptDraftStore.beginExecutionScope();
Expand Down Expand Up @@ -218,7 +224,7 @@ export class ChoiceExecutor implements IChoiceExecutor {
throw error;
} finally {
this.pendingResult = savedResult;
this.endExecutionContext();
this.endExecutionContext(enclosingClocks);
}
}

Expand Down Expand Up @@ -259,7 +265,7 @@ export class ChoiceExecutor implements IChoiceExecutor {
): Promise<ChoiceOutcome> {
this.pendingAbort = null;
this.pendingResult = null;
this.beginExecutionContext();
const enclosingClocks = this.beginExecutionContext();
const originLeaf = getOpenFileOriginLeaf(this.app);
const promptDraftStore = InputPromptDraftStore.getInstance();
const draftScope = promptDraftStore.beginExecutionScope();
Expand Down Expand Up @@ -310,7 +316,7 @@ export class ChoiceExecutor implements IChoiceExecutor {
reason: error instanceof Error ? error.message : String(error),
};
} finally {
this.endExecutionContext();
this.endExecutionContext(enclosingClocks);
}
}

Expand Down
25 changes: 16 additions & 9 deletions src/gui/suggesters/choiceSuggester.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1020,15 +1020,22 @@ describe("ChoiceSuggester", () => {
expect(completion).toHaveBeenCalledWith();
});

it("holds Shift to pick a day on a Today choice", () => {
const suggester = makeSuggester(rootChoices);
suggester.onChooseItem(
topNote,
new MouseEvent("click", { shiftKey: true }),
);
expect(executor.pickDate).toBe(true);
expect(executed).toEqual([topNote]);
});
it.each([false, true])(
"holds Shift to pick a day for the chosen run only (enclosing pickDate: %s)",
async (enclosing) => {
let pickDateDuringRun: boolean | undefined;
executor.pickDate = enclosing;
executor.executeWithFocusedProperty = async () => { pickDateDuringRun = executor.pickDate; };
const suggester = makeSuggester(rootChoices);
suggester.onChooseItem(
topNote,
new MouseEvent("click", { shiftKey: true }),
);
await flushMicrotasks();
expect(pickDateDuringRun).toBe(true);
expect(executor.pickDate).toBe(enclosing);
},
);

it("rejects with the leaf's own error instance", async () => {
const leafError = new Error("leaf blew up");
Expand Down
7 changes: 6 additions & 1 deletion src/gui/suggesters/choiceSuggester.ts
Original file line number Diff line number Diff line change
Expand Up @@ -536,17 +536,22 @@ export default class ChoiceSuggester extends FuzzySuggestModal<IChoice> {
// leaf inherits the executor's still-live context, which holds the same
// values this level was handed. Falls back to execute() only for stub
// executors without the method.
const enclosingPickDate = this.choiceExecutor.pickDate;
if ("shiftKey" in evt && evt.shiftKey) {
this.choiceExecutor.pickDate = true;
}
const execute = this.choiceExecutor.executeWithFocusedProperty
const run = this.choiceExecutor.executeWithFocusedProperty
? this.choiceExecutor.executeWithFocusedProperty(
item,
this.focusedProperty,
this.triggerContext,
this.ancestry,
)
: this.choiceExecutor.execute(item, this.ancestry);
// Shift picks a day for this choice, not for the Macro steps after it.
const execute = run.finally(() => {
this.choiceExecutor.pickDate = enclosingPickDate;
});
this.settleCompletion(execute, `Could not run "${item.name}"`);
}
}
Expand Down
8 changes: 5 additions & 3 deletions src/quickAddApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1007,12 +1007,14 @@ describe("executeChoice", () => {
expect(executor.execute).toHaveBeenCalled();
});

it("treats date ask as pickDate and still executes", async () => {
it("treats date ask as pickDate for that call only", async () => {
const executor = makeChoiceExecutor();
let pickDateDuringRun: boolean | undefined;
executor.execute.mockImplementation(async () => { pickDateDuringRun = executor.pickDate; });
const { api } = getApi(makeApp(), makePlugin(), executor);
await api.executeChoice("C", {}, { date: "ask" });
expect(executor.execute).toHaveBeenCalled();
expect(executor.pickDate).toBe(true);
expect(pickDateDuringRun).toBe(true);
expect(executor.pickDate).toBe(false);
expect(executor.clocks).toBeUndefined();
});

Expand Down
9 changes: 8 additions & 1 deletion src/quickAddApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ export class QuickAddApi {
return;
}

const { clocks, pickDate } = choiceExecutor;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
if (!applyInvocationDate(choiceExecutor, options?.date)) {
reportError(
new Error(`Could not parse date origin '${String(options?.date)}'`),
Expand All @@ -125,7 +126,13 @@ export class QuickAddApi {
// cancelled sub-choice and carries on must not lose them. The cost is
// the long-standing quirk that variables seeded into a cancelled call
// linger until the next completed one.
await choiceExecutor.execute(choice, chain);
try {
await choiceExecutor.execute(choice, chain);
} finally {
// options.date is this call's day, not the calling script's.
choiceExecutor.clocks = clocks;
choiceExecutor.pickDate = pickDate;
}
const abort = choiceExecutor.consumeAbortSignal?.();
choiceExecutor.variables.clear();
restoreDateVariableFormats(choiceExecutor.variables, new Map());
Expand Down
Loading
Loading