Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🗂️ feat: Scope Scheduled Chats to Chat Projects (#15056)
Danny Avila8c14f034321d
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.jsindex 5b6fb7dab6..cb56912c60 100644--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js@@ -856,9 +856,14 @@ describe('ResumableAgentController resume metadata', () => {}),}),);+ // `scheduledFor` identifies the OCCURRENCE, matching the resume path: the run row+ // is reserved before this loopback request is dispatched, so a pin introduced while+ // it sat queued must not be validated in place of the destination the envelope was+ // already built with.expect(mockIsScheduleLive).toHaveBeenCalledWith('schedule-1', 7, {automatic: true,policy: true,+ scheduledFor: '2026-08-17T12:00:00.000Z',});expect(initializeClient).not.toHaveBeenCalled();expect(res.status).toHaveBeenCalledWith(409);diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.jsindex c38fa9cc9d..8fa406d7d6 100644--- a/api/server/controllers/agents/__tests__/resume.spec.js+++ b/api/server/controllers/agents/__tests__/resume.spec.js@@ -351,9 +351,13 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {expect(res.status).toBe(409);expect(res.body).toMatchObject({ code: 'SCHEDULE_NO_LONGER_ACTIVE' });+ // `scheduledFor` identifies the OCCURRENCE: a later fire can redirect the+ // schedule while this run sits paused, so the policy recheck validates the+ // destination this run recorded rather than the schedule's current one.expect(mockIsScheduleLive).toHaveBeenCalledWith('schedule-1', 4, {automatic: true,policy: true,+ scheduledFor,});expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith(CONVO_ID, {expectedCreatedAt: 1000,diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.jsindex 5c99383180..c6b9892e8f 100644--- a/api/server/controllers/agents/request.js+++ b/api/server/controllers/agents/request.js@@ -1087,6 +1087,11 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit!(await isScheduleLive(scheduleId, scheduleConfigRevision, {automatic: req._isManualScheduledFire !== true,policy: true,+ // The occurrence's OWN recorded scope, exactly as the resume path passes it.+ // The run row is reserved before this loopback request is dispatched, so a pin+ // introduced while the request sat queued must not be validated in place of the+ // destination this occurrence's envelope was already built with.+ scheduledFor,}))) {throw Object.assign(new Error('This scheduled occurrence is no longer active'), {diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.jsindex ea14afcb0e..b2a4f450f1 100644--- a/api/server/controllers/agents/resume.js+++ b/api/server/controllers/agents/resume.js@@ -601,6 +601,10 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)!(await isScheduleLive(scheduleId, job.metadata?.scheduleConfigRevision, {automatic: job.metadata?.scheduleManual !== true,policy: true,+ // Re-validate the destination THIS occurrence recorded, not the schedule's+ // current one: a later fire can have redirected the schedule while this run sat+ // paused, and its conversation stays where it was filed.+ scheduledFor,}))) {let stopped = false;diff --git a/api/server/routes/schedules.js b/api/server/routes/schedules.jsindex b426710990..161629583c 100644--- a/api/server/routes/schedules.js+++ b/api/server/routes/schedules.js@@ -42,6 +42,10 @@ const handlers = createSchedulesHandlers({// the actual fire requires — otherwise a role without AGENTS:USE could schedule// runs the chat route rejects and walks toward auto-disable.canViewAgent: async (agentId, req) => (await resolveAgentFireAccess(agentId, req.user)) === 'ok',+ // Same scoped lookup the fire-time precheck uses, so a destination this write+ // accepts is one the next fire also accepts.+ canUseProject: async (projectId, userId) =>+ (await methods.getChatProject(userId, projectId)) != null,filterOwnedFileIds: async (fileIds, userId) => {const files = await methods.getFiles({ file_id: { $in: fileIds }, user: userId }, null, {file_id: 1,diff --git a/api/server/services/Schedules/index.js b/api/server/services/Schedules/index.jsindex 72f76fa7dc..1671c7ce2d 100644--- a/api/server/services/Schedules/index.js+++ b/api/server/services/Schedules/index.js@@ -52,6 +52,9 @@ function getService() {// deferred Retry-After) or a dead-letter apart from a genuinely orphaned run.getTriggerDelivery: getAgentTriggerDelivery,resolveAgentFireAccess,+ // Chat projects are user-owned, so this scoped read is both the existence and the+ // authorization check the fire-time destination precheck needs.+ getChatProject: (userId, projectId) => methods.getChatProject(userId, projectId),// Reuse the merged trigger/deletion admission fence. A schedule fire and every// generic trigger now fail closed on the same durable principal state.isUserDeleting,diff --git a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx b/client/src/components/SidePanel/Schedules/ScheduleCard.tsxindex 03cad7310a..06884f0cc2 100644--- a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx+++ b/client/src/components/SidePanel/Schedules/ScheduleCard.tsx@@ -2,7 +2,7 @@ import { useId, useRef, useMemo, useState, useCallback } from 'react';import * as Ariakit from '@ariakit/react';import { useNavigate } from 'react-router-dom';import { Trans, useTranslation } from 'react-i18next';-import { Play, Trash, Pencil, Ellipsis } from 'lucide-react';+import { Play, Trash, Folder, Pencil, Ellipsis } from 'lucide-react';import { PermissionTypes, Permissions } from 'librechat-data-provider';import {Label,@@ -30,6 +30,9 @@ import { describeCadence } from './cadence';interface ScheduleCardProps {schedule: TSchedule;+ /** Resolved by the panel, which holds ONE project-name lookup for the whole list —+ * deriving it per card is O(schedules x projects) on every project-list refresh. */+ projectName?: string | null;}type StatusTone = 'neutral' | 'success' | 'warning' | 'error';@@ -50,9 +53,11 @@ const DISABLED_REASON_LABELS: Record<ScheduleDisabledReason, TranslationKeys> =invalid_schedule: 'com_ui_schedule_disabled_invalid',permission_revoked: 'com_ui_schedule_disabled_permission_revoked',insufficient_balance: 'com_ui_schedule_disabled_insufficient_balance',+ project_deleted: 'com_ui_schedule_disabled_project_deleted',+ project_required: 'com_ui_schedule_disabled_project_required',};-export default function ScheduleCard({ schedule }: ScheduleCardProps) {+export default function ScheduleCard({ schedule, projectName }: ScheduleCardProps) {const localize = useLocalize();const navigate = useNavigate();const { i18n } = useTranslation();@@ -79,8 +84,18 @@ export default function ScheduleCard({ schedule }: ScheduleCardProps) {const agentName = mappedAgent?.name || fetchedAgent?.name || schedule.agent_id;const updateSchedule = useUpdateScheduleMutation({- onError: () => {- showToast({ message: localize('com_ui_error'), status: 'error' });+ /** Re-enabling re-validates the schedule's EFFECTIVE state — its stored agent, its+ * cadence against the current floor, and its project against the current policy —+ * so this switch is a real place to meet a 400. A generic failure toast would+ * leave the owner flipping a switch that keeps flipping back; point them at the+ * dialog, which is where the fixable settings are. */+ onError: (error, variables) => {+ const status = (error as { response?: { status?: number } } | undefined)?.response?.status;+ const blockedEnable = status === 400 && variables.payload.enabled === true;+ showToast({+ message: localize(blockedEnable ? 'com_ui_schedule_enable_blocked' : 'com_ui_error'),+ status: 'error',+ });},});const deleteSchedule = useDeleteScheduleMutation();@@ -211,6 +226,15 @@ export default function ScheduleCard({ schedule }: ScheduleCardProps) {<p className="mt-0.5 truncate text-xs text-text-secondary" title={agentName}>{agentName}</p>+ {projectName != null && projectName !== '' && (+ <p+ className="mt-0.5 flex items-center gap-1 truncate text-xs text-text-secondary"+ title={projectName}+ >+ <Folder className="size-3 shrink-0" aria-hidden="true" />+ <span className="truncate">{projectName}</span>+ </p>+ )}<p className="mt-1 text-sm text-text-primary">{cadenceText}</p>{nextRunText != null && <p className="mt-0.5 text-xs text-text-secondary">{nextRunText}</p>}{(statusChip != null || schedule.disabledReason != null) && (diff --git a/client/src/components/SidePanel/Schedules/ScheduleDialog.tsx b/client/src/components/SidePanel/Schedules/ScheduleDialog.tsxindex 4a5fc8289a..6983e89276 100644--- a/client/src/components/SidePanel/Schedules/ScheduleDialog.tsx+++ b/client/src/components/SidePanel/Schedules/ScheduleDialog.tsx@@ -1,5 +1,6 @@import { useMemo, useRef } from 'react';import { v4 } from 'uuid';+import { Folder } from 'lucide-react';import { useTranslation } from 'react-i18next';import { useForm, Controller } from 'react-hook-form';import { PermissionBits, scheduleFrequencies } from 'librechat-data-provider';@@ -25,11 +26,14 @@ import type {import type { TranslationKeys } from '~/hooks';import type { Meridiem } from './cadence';import {+ useProjectQuery,useListAgentsQuery,+ useSchedulesQuery,useCreateScheduleMutation,useUpdateScheduleMutation,} from '~/data-provider';import { to12Hour, to24Hour, describeCadence, formatScheduleDay } from './cadence';+import { useChatProjectPicker } from './useScheduleProjects';import { VariableEditor } from '~/components/Variables';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -45,6 +49,8 @@ type ScheduleFormValues = {name: string;prompt: string;agent_id: string;+ /** `''` means unscoped; the picker has no null option of its own. */+ chatProjectId: string;frequency: ScheduleFrequency;hour12: number;minute: number;@@ -69,6 +75,7 @@ const getDefaultValues = (schedule?: TSchedule): ScheduleFormValues => {name: '',prompt: '',agent_id: '',+ chatProjectId: '',frequency: 'daily',hour12: 9,minute: 0,@@ -81,6 +88,7 @@ const getDefaultValues = (schedule?: TSchedule): ScheduleFormValues => {name: schedule.name,prompt: schedule.prompt,agent_id: schedule.agent_id,+ chatProjectId: schedule.chatProjectId ?? '',frequency: schedule.cadence.frequency,hour12,minute: schedule.cadence.minute,@@ -155,6 +163,51 @@ export default function ScheduleDialog({[agents],);+ /** Reads the SAME cached list query the panel already holds, so the dialog needs no+ * request of its own — and so the form mirrors exactly the policy the write handler+ * enforces rather than a second, client-side interpretation of the config. */+ const { data: schedulesData } = useSchedulesQuery();+ const pinnedProjectId = schedulesData?.limits.projectId;+ const requireProject = schedulesData?.limits.requireProject === true;+ const {+ items: loadedProjectItems,+ namesById: projectNames,+ hasNextPage: hasMoreProjects,+ fetchNextPage: fetchMoreProjects,+ isFetchingNextPage: isFetchingMoreProjects,+ } = useChatProjectPicker(open);+ const selectedProjectId = watch('chatProjectId');++ /** Clearing the scope needs a real OPTION, not just the placeholder: with only live+ * projects in the list, a schedule that has one could never be set back to none, and+ * the server's `chatProjectId: null` clearing path would be unreachable from the UI.+ * Omitted when a project is mandatory — there is nothing valid to select. */+ const projectItems = useMemo(+ () =>+ requireProject+ ? loadedProjectItems+ : [+ {+ label: localize('com_ui_schedule_project_none'),+ value: '',+ icon: <Folder className="h-4 w-4 text-text-secondary" aria-hidden="true" />,+ },+ ...loadedProjectItems,+ ],+ [requireProject, loadedProjectItems, localize],+ );++ /** The stored (or pinned) project can sit outside the pages loaded so far, and the+ * combobox renders its PLACEHOLDER for an unknown name — telling the owner a scoped+ * schedule has no project. Read that one project directly instead. */+ const displayedProjectId = pinnedProjectId ?? (selectedProjectId || undefined);+ const isProjectPaged = displayedProjectId != null && projectNames.has(displayedProjectId);+ const { data: fetchedProject } = useProjectQuery(isProjectPaged ? undefined : displayedProjectId);+ const projectDisplayName = (projectId: string): string =>+ projectNames.get(projectId) ??+ (fetchedProject?._id === projectId ? fetchedProject.name : undefined) ??+ projectId;+const frequencyOptions = useMemo(() =>scheduleFrequencies.map((value) => ({@@ -272,6 +325,13 @@ export default function ScheduleDialog({...(dirtyFields.name ? { name: values.name.trim() } : {}),...(dirtyFields.prompt ? { prompt: values.prompt.trim() } : {}),...(dirtyFields.agent_id ? { agent_id: values.agent_id } : {}),+ // Explicit `null` is the only way to CLEAR the scope; omitting the field+ // leaves the stored project alone. Never sent while pinned — the server owns+ // the destination there, and echoing it back would only be a chance to+ // disagree with a pin that changed since the dialog opened.+ ...(dirtyFields.chatProjectId && pinnedProjectId == null+ ? { chatProjectId: values.chatProjectId || null }+ : {}),...(cadenceTouched ? { cadence } : {}),};// Nothing touched: a field-less PATCH is refused server-side (it would rotate@@ -299,6 +359,9 @@ export default function ScheduleDialog({name: values.name.trim(),prompt: values.prompt.trim(),agent_id: values.agent_id,+ ...(pinnedProjectId == null && values.chatProjectId+ ? { chatProjectId: values.chatProjectId }+ : {}),cadence: buildCadence(values),timezone,target: 'new' as const,@@ -336,66 +399,163 @@ export default function ScheduleDialog({showCloseButton={false}// The agent and time popovers cannot portal out of a focus-trapping dialog// (see below), so `overflow-visible` keeps them from being clipped. Only from- // `md` up: the two-column layout fits well inside 90vh there, while narrow+ // `md` up: the identity row fits well inside 90vh there, while narrow// viewports keep the template's scrolling so the footer stays reachable.+ //+ // THE BUDGET IS A CONTRACT: with scrolling off at `md`, anything that adds a+ // ROW here pushes the footer's submit button out of a 720px-tall viewport,+ // where it can never be scrolled back — the e2e edit spec times out clicking+ // Save. A new field belongs in an existing row (see the identity row below),+ // not stacked beneath one.className="w-11/12 md:max-w-3xl md:overflow-visible"main={<form id={FORM_ID} onSubmit={handleSubmit(onSubmit)} className="space-y-4">- <div className="grid gap-4 md:grid-cols-2">- <div className="space-y-2">- <Label htmlFor="schedule-name" className="text-sm font-medium text-text-primary">- {localize('com_ui_name')}- </Label>- <Input- id="schedule-name"- className="w-full"- placeholder={localize('com_ui_schedule_name_placeholder')}- aria-invalid={errors.name != null}- aria-describedby="schedule-name-message"- {...register('name', { required: localize('com_ui_field_required') })}- />- <FieldMessage id="schedule-name-message" message={errors.name?.message} />- </div>- <div className="space-y-2">- <Label htmlFor="schedule-agent" className="text-sm font-medium text-text-primary">- {localize('com_ui_agent')}- </Label>- <Controller- name="agent_id"- control={control}- rules={{ required: localize('com_ui_field_required') }}- render={({ field }) => (- <ControlCombobox- selectedValue={field.value}- displayValue={- agentItems.find((item) => item.value === field.value)?.label ?? ''+ {/* Identity row: what the schedule is, who runs it, where its chats land.+ Its caption is grouped with it rather than left to the form's own 4-unit+ rhythm, which would spend more vertical budget on the gap than the+ caption itself occupies. */}+ <div className="space-y-1.5">+ <div className="grid gap-4 md:grid-cols-3">+ <div className="space-y-2">+ <Label htmlFor="schedule-name" className="text-sm font-medium text-text-primary">+ {localize('com_ui_name')}+ </Label>+ <Input+ id="schedule-name"+ className="w-full"+ placeholder={localize('com_ui_schedule_name_placeholder')}+ aria-invalid={errors.name != null}+ aria-describedby="schedule-name-message"+ {...register('name', { required: localize('com_ui_field_required') })}+ />+ <FieldMessage id="schedule-name-message" message={errors.name?.message} />+ </div>+ <div className="space-y-2">+ <Label htmlFor="schedule-agent" className="text-sm font-medium text-text-primary">+ {localize('com_ui_agent')}+ </Label>+ <Controller+ name="agent_id"+ control={control}+ rules={{ required: localize('com_ui_field_required') }}+ render={({ field }) => (+ <ControlCombobox+ selectedValue={field.value}+ displayValue={+ agentItems.find((item) => item.value === field.value)?.label ?? ''+ }+ selectPlaceholder={localize('com_ui_select_agent')}+ searchPlaceholder={localize('com_agents_search_name')}+ setValue={field.onChange}+ onBlur={field.onBlur}+ items={agentItems}+ ariaLabel={localize('com_ui_agent')}+ ariaInvalid={errors.agent_id != null}+ ariaDescribedBy="schedule-agent-message"+ selectId="schedule-agent"+ isCollapsed={false}+ showCarat={true}+ placement="bottom-start"+ // Radix traps focus inside the dialog, so a popover portaled to+ // the body cannot be clicked, tabbed into, or typed in — and the+ // trap fighting Ariakit for focus locks the page up.+ portal={false}+ matchTriggerWidth={true}+ variant="field"+ />+ )}+ />+ <FieldMessage id="schedule-agent-message" message={errors.agent_id?.message} />+ </div>+ <div className="space-y-2">+ <Label+ htmlFor="schedule-project"+ className="text-sm font-medium text-text-primary"+ >+ {localize('com_ui_project')}+ </Label>+ {pinnedProjectId != null ? (+ /* Pinned by the operator: there is no choice to offer, so show the+ destination rather than a disabled control the user would keep+ trying to open. */+ <div+ id="schedule-project"+ data-testid="schedule-project-pinned"+ className="flex h-10 w-full items-center gap-2 rounded-xl border border-border-light bg-surface-secondary px-3 text-sm text-text-secondary"+ >+ <Folder className="h-4 w-4 shrink-0" aria-hidden="true" />+ <span className="truncate">{projectDisplayName(pinnedProjectId)}</span>+ </div>+ ) : (+ <Controller+ name="chatProjectId"+ control={control}+ // Only for a schedule this submit leaves ENABLED. The server waives+ // the requirement for a disabled row precisely so one auto-disabled+ // for `project_required` can still be renamed or tidied up; requiring+ // it here made that path unreachable, and an owner with no projects+ // at all could not edit the stopped schedule.+ rules={+ requireProject && (schedule == null || schedule.enabled)+ ? { required: localize('com_ui_field_required') }+ : undefined}- selectPlaceholder={localize('com_ui_select_agent')}- searchPlaceholder={localize('com_agents_search_name')}- setValue={field.onChange}- onBlur={field.onBlur}- items={agentItems}- ariaLabel={localize('com_ui_agent')}- ariaInvalid={errors.agent_id != null}- ariaDescribedBy="schedule-agent-message"- selectId="schedule-agent"- isCollapsed={false}- showCarat={true}- placement="bottom-start"- // Radix traps focus inside the dialog, so a popover portaled to- // the body cannot be clicked, tabbed into, or typed in — and the- // trap fighting Ariakit for focus locks the page up.- portal={false}- matchTriggerWidth={true}- variant="field"+ render={({ field }) => (+ <ControlCombobox+ selectedValue={field.value}+ // Never `''` for a real id: that renders the placeholder,+ // which reads as "No project" on a schedule that has one.+ displayValue={field.value ? projectDisplayName(field.value) : ''}+ selectPlaceholder={localize(+ requireProject+ ? 'com_ui_select_project'+ : 'com_ui_schedule_project_none',+ )}+ searchPlaceholder={localize('com_ui_search_projects')}+ setValue={field.onChange}+ onBlur={field.onBlur}+ items={projectItems}+ SelectIcon={+ <Folder className="h-4 w-4 text-text-secondary" aria-hidden="true" />+ }+ ariaLabel={localize('com_ui_project')}+ ariaInvalid={errors.chatProjectId != null}+ ariaDescribedBy="schedule-project-message"+ selectId="schedule-project"+ isCollapsed={false}+ showCarat={true}+ placement="bottom-start"+ /* Same focus-trap constraint as the agent picker above. */+ portal={false}+ matchTriggerWidth={true}+ variant="field"+ />+ )}/>)}- />- <FieldMessage id="schedule-agent-message" message={errors.agent_id?.message} />- <p className="text-xs text-text-secondary">- {localize('com_ui_schedule_target_new_chat')}- </p>+ <FieldMessage+ id="schedule-project-message"+ message={errors.chatProjectId?.message}+ />+ {pinnedProjectId == null && hasMoreProjects && (+ <Button+ type="button"+ variant="link"+ className="h-auto justify-start px-0 text-xs"+ onClick={() => fetchMoreProjects()}+ disabled={isFetchingMoreProjects}+ >+ {localize(isFetchingMoreProjects ? 'com_ui_loading' : 'com_ui_load_more')}+ </Button>+ )}+ </div></div>+ {/* Full width, not inside the agent cell: at a third of the dialog this+ sentence wraps an extra line, and the identity row is the tallest thing+ competing for the fixed height budget described on the template above. */}+ <p className="text-xs text-text-secondary">+ {localize('com_ui_schedule_target_new_chat')}+ </p></div><Controllerdiff --git a/client/src/components/SidePanel/Schedules/SchedulePanel.tsx b/client/src/components/SidePanel/Schedules/SchedulePanel.tsxindex 006eae48c3..333b770d73 100644--- a/client/src/components/SidePanel/Schedules/SchedulePanel.tsx+++ b/client/src/components/SidePanel/Schedules/SchedulePanel.tsx@@ -3,6 +3,7 @@ import { Plus } from 'lucide-react';import { Button, TooltipAnchor } from '@librechat/client';import { PermissionTypes, Permissions } from 'librechat-data-provider';import { PanelContent, PanelFooter } from '~/components/ui';+import { useChatProjectNames } from './useScheduleProjects';import ScheduleCardSkeleton from './ScheduleCardSkeleton';import { useSchedulesQuery } from '~/data-provider';import { useLocalize, useHasAccess } from '~/hooks';@@ -20,6 +21,12 @@ export default function SchedulePanel() {});const schedules = data?.schedules ?? [];+ /** ONE lookup for the whole list. Resolving a name inside each card would re-walk+ * every loaded project per card, per render. Skipped entirely until some schedule+ * actually has a scope, so an unscoped panel issues no project request at all. */+ const projectNames = useChatProjectNames(+ schedules.some((schedule) => schedule.chatProjectId != null),+ );const maxPerUser = data?.limits.maxPerUser;const atLimit = maxPerUser !== undefined && schedules.length >= maxPerUser;let panelContent: ReactNode;@@ -46,7 +53,16 @@ export default function SchedulePanel() {<div className="space-y-2" role="list" aria-label={localize('com_ui_schedules')}>{schedules.map((schedule) => (<div key={schedule.id} role="listitem">- <ScheduleCard schedule={schedule} />+ <ScheduleCard+ schedule={schedule}+ // The raw id is a poor label but an honest one: it only shows for a+ // project outside the loaded pages, and beats claiming no scope.+ projectName={+ schedule.chatProjectId != null+ ? (projectNames.get(schedule.chatProjectId) ?? schedule.chatProjectId)+ : null+ }+ /></div>))}</div>diff --git a/client/src/components/SidePanel/Schedules/__tests__/ScheduleDialog.spec.tsx b/client/src/components/SidePanel/Schedules/__tests__/ScheduleDialog.spec.tsxindex fd4bf0cc32..f79a3b0b5b 100644--- a/client/src/components/SidePanel/Schedules/__tests__/ScheduleDialog.spec.tsx+++ b/client/src/components/SidePanel/Schedules/__tests__/ScheduleDialog.spec.tsx@@ -3,6 +3,7 @@ import { ToastProvider } from '@librechat/client';import userEvent from '@testing-library/user-event';import { render, screen, waitFor, within } from '@testing-library/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { TSchedule } from 'librechat-data-provider';import type { ReactNode } from 'react';import ScheduleDialog from '../ScheduleDialog';@@ -18,18 +19,48 @@ jest.mock('react-i18next', () => ({const mockMutate = jest.fn();+/** Server-resolved schedule policy for the render under test. The dialog reads it from+ * the schedules list query, the same cache entry the panel populates. */+let mockLimits: { maxPerUser: number; requireProject: boolean; projectId?: string } = {+ maxPerUser: 10,+ requireProject: false,+};++/** A project the paged list has NOT loaded, resolved by its own by-id read. */+let mockFetchedProject: { _id: string; name: string } | undefined;+jest.mock('~/data-provider', () => ({+ useProjectQuery: (projectId?: string | null) => ({+ data: projectId != null && projectId !== '' ? mockFetchedProject : undefined,+ }),useListAgentsQuery: () => ({data: [{ id: 'agent-1', name: 'Research Agent' },{ id: 'agent-2', name: 'Digest Agent' },],}),+ useSchedulesQuery: () => ({ data: { schedules: [], limits: mockLimits } }),+ useProjectsInfiniteQuery: () => ({+ data: {+ pages: [+ {+ projects: [+ { _id: 'proj-1', name: 'Weekly Ops' },+ { _id: 'proj-2', name: 'Research' },+ ],+ nextCursor: null,+ },+ ],+ },+ fetchNextPage: jest.fn(),+ isFetchingNextPage: false,+ isLoading: false,+ }),useCreateScheduleMutation: () => ({ mutate: mockMutate, isLoading: false }),useUpdateScheduleMutation: () => ({ mutate: mockMutate, isLoading: false }),}));-const renderDialog = () => {+const renderDialog = (schedule?: Partial<TSchedule>) => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },});@@ -40,11 +71,47 @@ const renderDialog = () => {createElement(ToastProvider, null, children),);}- return render(<ScheduleDialog open={true} onOpenChange={jest.fn()} />, { wrapper: Wrapper });+ return render(+ <ScheduleDialog+ open={true}+ onOpenChange={jest.fn()}+ schedule={schedule as TSchedule | undefined}+ />,+ { wrapper: Wrapper },+ );+};++const storedSchedule = (over: Partial<TSchedule> = {}): Partial<TSchedule> => ({+ id: 'sched-1',+ name: 'Digest',+ prompt: 'Summarize',+ agent_id: 'agent-1',+ cadence: { frequency: 'daily', hour: 8, minute: 0 },+ timezone: 'America/New_York',+ target: 'new',+ enabled: true,+ configRevision: 3,+ runCount: 0,+ failureCount: 0,+ ...over,+});++/** Fills the two required text fields plus the agent, so a submit exercises the+ * project rules rather than unrelated validation. */+const fillRequiredFields = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.type(screen.getByPlaceholderText('com_ui_schedule_name_placeholder'), 'Digest');+ await user.type(screen.getByPlaceholderText('com_ui_schedule_prompt_placeholder'), 'Summarize');+ const dialog = screen.getByRole('dialog');+ await user.click(within(dialog).getByRole('combobox', { name: 'com_ui_agent' }));+ await user.click(await within(dialog).findByRole('option', { name: /Research Agent/ }));};describe('ScheduleDialog', () => {- afterEach(() => jest.clearAllMocks());+ afterEach(() => {+ jest.clearAllMocks();+ mockLimits = { maxPerUser: 10, requireProject: false };+ mockFetchedProject = undefined;+ });/*** The agent list must render INSIDE the dialog. Portaled to the body it lands@@ -147,4 +214,154 @@ describe('ScheduleDialog', () => {'com_ui_field_required',);});++ describe('project scope', () => {+ it('submits the chosen project so its runs are filed there', async () => {+ const user = userEvent.setup();+ renderDialog();+ await fillRequiredFields(user);++ await user.click(screen.getByRole('combobox', { name: 'com_ui_project' }));+ // Narrowed through the search field rather than picked from the open list: the+ // popover renders its options through a VIRTUALIZED renderer, which sizes its+ // window from a scroll height jsdom always reports as 0 and so materializes only+ // a couple of rows. Filtering to one match keeps the assertion about the dialog's+ // behaviour instead of the test environment's layout.+ await user.type(screen.getByPlaceholderText('com_ui_search_projects'), 'Weekly');+ await user.click(await screen.findByRole('option', { name: /Weekly Ops/ }));+ await user.click(screen.getByRole('button', { name: 'com_ui_create' }));++ expect(mockMutate).toHaveBeenCalledWith(expect.objectContaining({ chatProjectId: 'proj-1' }));+ });++ /** An unscoped schedule must not send `chatProjectId: ''` — the payload schema+ * refuses an empty string, so the create would 400 rather than file loose. */+ it('omits the field entirely when no project is chosen', async () => {+ const user = userEvent.setup();+ renderDialog();+ await fillRequiredFields(user);++ await user.click(screen.getByRole('button', { name: 'com_ui_create' }));++ expect(mockMutate).toHaveBeenCalledTimes(1);+ expect(mockMutate.mock.calls[0][0]).not.toHaveProperty('chatProjectId');+ });++ /** The server refuses an unscoped create under this policy; blocking it here keeps+ * the user from losing a filled-in form to a 400. */+ it('blocks submission when the deployment requires a project', async () => {+ mockLimits = { maxPerUser: 10, requireProject: true };+ const user = userEvent.setup();+ renderDialog();+ await fillRequiredFields(user);++ await user.click(screen.getByRole('button', { name: 'com_ui_create' }));++ expect(mockMutate).not.toHaveBeenCalled();+ expect(await screen.findByText('com_ui_field_required')).toBeInTheDocument();+ });++ /** The server accepts `chatProjectId: null` to clear a scope, but that path is only+ * reachable if the picker offers something to select — a placeholder cannot be+ * chosen, so without a real option a scoped schedule could never be unscoped. */+ it('can clear a stored project through a selectable No project option', async () => {+ const user = userEvent.setup();+ renderDialog(storedSchedule({ chatProjectId: 'proj-1' }));++ expect(screen.getByRole('combobox', { name: 'com_ui_project' })).toHaveTextContent(+ 'Weekly Ops',+ );+ await user.click(screen.getByRole('combobox', { name: 'com_ui_project' }));+ await user.click(await screen.findByRole('option', { name: /com_ui_schedule_project_none/ }));+ await user.click(screen.getByRole('button', { name: 'com_ui_save' }));++ expect(mockMutate).toHaveBeenCalledWith(+ expect.objectContaining({ payload: expect.objectContaining({ chatProjectId: null }) }),+ );+ });++ /** There is no "no project" to offer when one is mandatory. */+ it('offers no clearing option when a project is required', async () => {+ mockLimits = { maxPerUser: 10, requireProject: true };+ const user = userEvent.setup();+ renderDialog(storedSchedule({ chatProjectId: 'proj-1' }));++ await user.click(screen.getByRole('combobox', { name: 'com_ui_project' }));++ expect(+ screen.queryByRole('option', { name: /com_ui_schedule_project_none/ }),+ ).not.toBeInTheDocument();+ });++ /** A stored project outside the loaded page would otherwise render the placeholder —+ * telling the owner a scoped schedule has no project. */+ it('names a stored project the paged list has not loaded', async () => {+ mockFetchedProject = { _id: 'proj-999', name: 'Archived Ops' };+ renderDialog(storedSchedule({ chatProjectId: 'proj-999' }));++ const picker = screen.getByRole('combobox', { name: 'com_ui_project' });+ expect(picker).toHaveTextContent('Archived Ops');+ expect(picker).not.toHaveTextContent('com_ui_schedule_project_none');+ });++ /** Even with no name available, the id beats claiming the schedule is unscoped. */+ it('falls back to the stored id rather than showing the empty placeholder', async () => {+ renderDialog(storedSchedule({ chatProjectId: 'proj-999' }));++ expect(screen.getByRole('combobox', { name: 'com_ui_project' })).toHaveTextContent(+ 'proj-999',+ );+ });++ /** The server waives the requirement for an edit that leaves a schedule DISABLED,+ * so a row auto-disabled for `project_required` can still be renamed. Requiring a+ * project in the form made that unreachable — and an owner with no projects at all+ * could not edit the stopped schedule. */+ it('lets a disabled unscoped schedule be edited while a project is required', async () => {+ mockLimits = { maxPerUser: 10, requireProject: true };+ const user = userEvent.setup();+ renderDialog(storedSchedule({ enabled: false, chatProjectId: undefined }));++ await user.clear(screen.getByPlaceholderText('com_ui_schedule_name_placeholder'));+ await user.type(screen.getByPlaceholderText('com_ui_schedule_name_placeholder'), 'Renamed');+ await user.click(screen.getByRole('button', { name: 'com_ui_save' }));++ expect(mockMutate).toHaveBeenCalledWith(+ expect.objectContaining({ payload: expect.objectContaining({ name: 'Renamed' }) }),+ );+ });++ /** An ENABLED schedule still has to satisfy the requirement. */+ it('still requires a project when the edit leaves the schedule enabled', async () => {+ mockLimits = { maxPerUser: 10, requireProject: true };+ const user = userEvent.setup();+ renderDialog(storedSchedule({ enabled: true, chatProjectId: undefined }));++ await user.clear(screen.getByPlaceholderText('com_ui_schedule_name_placeholder'));+ await user.type(screen.getByPlaceholderText('com_ui_schedule_name_placeholder'), 'Renamed');+ await user.click(screen.getByRole('button', { name: 'com_ui_save' }));++ expect(mockMutate).not.toHaveBeenCalled();+ expect(await screen.findByText('com_ui_field_required')).toBeInTheDocument();+ });++ /** A pin is the server's decision. Offering a picker would only invite a choice+ * the write handler rejects, so the dialog shows the destination instead — and+ * sends nothing, leaving the pin authoritative even if it moved since the dialog+ * opened. */+ it('shows a pinned project as read-only and never sends it', async () => {+ mockLimits = { maxPerUser: 10, requireProject: true, projectId: 'proj-2' };+ const user = userEvent.setup();+ renderDialog();+ await fillRequiredFields(user);++ expect(screen.getByTestId('schedule-project-pinned')).toHaveTextContent('Research');+ expect(screen.queryByRole('combobox', { name: 'com_ui_project' })).not.toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: 'com_ui_create' }));++ expect(mockMutate).toHaveBeenCalledTimes(1);+ expect(mockMutate.mock.calls[0][0]).not.toHaveProperty('chatProjectId');+ });+ });});diff --git a/client/src/components/SidePanel/Schedules/useScheduleProjects.tsx b/client/src/components/SidePanel/Schedules/useScheduleProjects.tsxnew file mode 100644index 0000000000..0fa41a641f--- /dev/null+++ b/client/src/components/SidePanel/Schedules/useScheduleProjects.tsx@@ -0,0 +1,79 @@+import { useMemo } from 'react';+import { Folder } from 'lucide-react';+import type { TChatProject } from 'librechat-data-provider';+import type { OptionWithIcon } from '~/common';+import { useProjectsInfiniteQuery } from '~/data-provider';++/** Shared with `ProjectButton`, so every project surface reads one cached page set+ * instead of each card and dialog opening its own list. */+const PROJECT_LIST_PARAMS = {+ sortBy: 'name',+ sortDirection: 'asc',+ limit: 100,+} as const;++function useLoadedProjects(enabled: boolean) {+ const { data, fetchNextPage, isFetchingNextPage, isLoading } = useProjectsInfiniteQuery(+ PROJECT_LIST_PARAMS,+ { enabled },+ );+ const projects = useMemo<TChatProject[]>(+ () => data?.pages.flatMap((page) => page.projects) ?? [],+ [data?.pages],+ );+ const hasNextPage = data?.pages[data.pages.length - 1]?.nextCursor != null;+ return { projects, hasNextPage, fetchNextPage, isFetchingNextPage, isLoading };+}++/**+ * Name lookup ONLY, deliberately built without the picker's option list.+ *+ * Call this ONCE for a whole list of schedules, not per row: React Query shares the+ * request, but every hook instance still walks all loaded projects, and the picker+ * shape additionally allocates an icon element per project. Per-card that is+ * O(schedules x projects) of work — and a fresh React element per project per card —+ * on every render and every project-list refresh.+ */+export function useChatProjectNames(enabled = true): Map<string, string> {+ const { projects } = useLoadedProjects(enabled);+ return useMemo(() => {+ const names = new Map<string, string>();+ for (const project of projects) {+ names.set(project._id, project.name);+ }+ return names;+ }, [projects]);+}++export interface ChatProjectPicker {+ items: OptionWithIcon[];+ /** Names of the projects paged in so far; a stored id outside them needs its own read. */+ namesById: Map<string, string>;+ hasNextPage: boolean;+ fetchNextPage: () => void;+ isFetchingNextPage: boolean;+ isLoading: boolean;+}++/** Picker-shaped projects for the schedule dialog's single combobox. */+export function useChatProjectPicker(enabled = true): ChatProjectPicker {+ const { projects, hasNextPage, fetchNextPage, isFetchingNextPage, isLoading } =+ useLoadedProjects(enabled);++ /** One pass builds both the option list and the name lookup the display value reads. */+ const { items, namesById } = useMemo(() => {+ const options: OptionWithIcon[] = [];+ const names = new Map<string, string>();+ for (const project of projects) {+ names.set(project._id, project.name);+ options.push({+ label: project.name,+ value: project._id,+ icon: <Folder className="h-4 w-4 text-text-secondary" aria-hidden="true" />,+ });+ }+ return { items: options, namesById: names };+ }, [projects]);++ return { items, namesById, hasNextPage, fetchNextPage, isFetchingNextPage, isLoading };+}diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 84f9b5e46b..1c30d82868 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1702,6 +1702,7 @@"com_ui_privacy_policy_url": "Privacy Policy URL","com_ui_pro": "Pro","com_ui_production": "Production",+ "com_ui_project": "Project","com_ui_project_chat_count": "{{count}} chats","com_ui_project_chat_count_single": "1 chat","com_ui_project_count": "{{count}} projects",@@ -1864,8 +1865,11 @@"com_ui_schedule_disabled_insufficient_balance": "Disabled: insufficient balance","com_ui_schedule_disabled_invalid": "Disabled: invalid schedule","com_ui_schedule_disabled_permission_revoked": "Disabled: permission revoked",+ "com_ui_schedule_disabled_project_deleted": "Disabled: project unavailable",+ "com_ui_schedule_disabled_project_required": "Disabled: a project is required","com_ui_schedule_disabled_too_many_failures": "Disabled: too many failures","com_ui_schedule_edit": "Edit schedule",+ "com_ui_schedule_enable_blocked": "Couldn't enable this schedule. Open it to check its agent, project, and frequency.","com_ui_schedule_enabled": "Enabled","com_ui_schedule_frequency": "Frequency","com_ui_schedule_hour": "Hour",@@ -1881,6 +1885,7 @@"com_ui_schedule_next_run": "Next run {{time}}","com_ui_schedule_options": "Schedule options","com_ui_schedule_pm": "PM",+ "com_ui_schedule_project_none": "No project","com_ui_schedule_prompt_placeholder": "Summarize the top AI news from the last 24 hours and highlight anything worth acting on.","com_ui_schedule_run_now": "Run now","com_ui_schedule_run_now_started": "Run started",diff --git a/e2e/specs/mock/schedules-execution.spec.ts b/e2e/specs/mock/schedules-execution.spec.tsindex bfad84e4fb..f8ec1ab739 100644--- a/e2e/specs/mock/schedules-execution.spec.ts+++ b/e2e/specs/mock/schedules-execution.spec.ts@@ -226,7 +226,13 @@ test.describe('scheduled chat execution', () => {const renamed = `${name} edited`;await editDialog.locator('#schedule-name').fill(renamed);await editDialog.getByRole('radio', { name: 'Daily' }).click();- await editDialog.getByRole('button', { name: 'Save' }).click();+ // The dialog does not scroll at `md` and up, so its content has to fit the+ // viewport: a field that adds a ROW pushes Save out of a 720px-tall window with+ // no way to scroll it back. Asserted explicitly because the bare click below+ // reports that as a 2-minute timeout on a visible, enabled button.+ const save = editDialog.getByRole('button', { name: 'Save' });+ await expect(save).toBeInViewport();+ await save.click();await page.reload();await openSchedulesPanel(page);diff --git a/librechat.example.yaml b/librechat.example.yamlindex b6b4f3183c..2b7a484e99 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -207,6 +207,14 @@ interface:# minIntervalMinutes: 60# autoDisableAfterFailures: 5# fireConcurrency: 5+ # # Require every schedule to be filed under a chat project. Enforced on+ # # create/update AND at each fire, so turning it on stops (auto-disables)+ # # schedules that predate it rather than letting their runs land loose.+ # requireProject: false+ # # Pin every scheduled run to ONE chat project, ignoring the user's choice.+ # # Implies `requireProject`. Chat projects are user-owned, so a value set here+ # # only makes sense as a per-user or per-role config override.+ # # projectId: '000000000000000000000000'peoplePicker:users: truegroups: truediff --git a/packages/api/src/agents/triggers/envelope.spec.ts b/packages/api/src/agents/triggers/envelope.spec.tsindex 80c1980d73..4a19e37ae6 100644--- a/packages/api/src/agents/triggers/envelope.spec.ts+++ b/packages/api/src/agents/triggers/envelope.spec.ts@@ -245,6 +245,21 @@ describe('createAgentTriggerEnvelope', () => {run: { metadata: { callback: () => undefined } },} as unknown as CreateAgentTriggerEnvelopeInput),).toThrow('run.metadata.callback contains a non-JSON function value');+ // The destination project is host-controlled context, so it must survive the+ // envelope's sanitization intact and be rejected when it is not a string — a+ // silently dropped id would file a scheduled run outside the project the+ // schedule promised.+ const scoped = createAgentTriggerEnvelope({+ ...createFireInput(),+ run: { chatProjectId: 'project-1' },+ } as CreateAgentTriggerEnvelopeInput);+ expect(scoped.mode === 'fire' && scoped.run?.chatProjectId).toBe('project-1');+ expect(() =>+ createAgentTriggerEnvelope({+ ...createFireInput(),+ run: { chatProjectId: 42 },+ } as unknown as CreateAgentTriggerEnvelopeInput),+ ).toThrow('run.chatProjectId must be a non-empty string');});it('rejects non-JSON and circular event payloads', () => {diff --git a/packages/api/src/agents/triggers/envelope.ts b/packages/api/src/agents/triggers/envelope.tsindex c599df6b80..d6b4dcdbb7 100644--- a/packages/api/src/agents/triggers/envelope.ts+++ b/packages/api/src/agents/triggers/envelope.ts@@ -40,6 +40,9 @@ interface AgentTriggerTarget {export interface AgentFireRunContext {conversationId?: string;timezone?: string;+ /** Chat project the new conversation is filed under. Host-controlled like the+ * rest of this context — never sourced from the event payload. */+ chatProjectId?: string;files?: JsonValue[];metadata?: JsonValue;}@@ -198,6 +201,9 @@ function createFireRunContext(if (run.timezone != null) {context.timezone = requireString(run.timezone, 'run.timezone');}+ if (run.chatProjectId != null) {+ context.chatProjectId = requireString(run.chatProjectId, 'run.chatProjectId');+ }if (run.files != null) {if (!Array.isArray(run.files)) {throw error('run.files must be an array');diff --git a/packages/api/src/agents/triggers/host.spec.ts b/packages/api/src/agents/triggers/host.spec.tsindex cf97319b5d..7c820d4c44 100644--- a/packages/api/src/agents/triggers/host.spec.ts+++ b/packages/api/src/agents/triggers/host.spec.ts@@ -15,6 +15,7 @@ const createFireEnvelope = () =>run: {conversationId: 'scheduled-conversation-1',timezone: 'Europe/Paris',+ chatProjectId: 'project-1',files: [{ file_id: 'file-1' }],metadata: { manual: false },},@@ -172,6 +173,7 @@ describe('createAgentTriggerExecutionHost fire adapter', () => {metadata: { manual: false },},newConversationId: 'scheduled-conversation-1',+ chatProjectId: 'project-1',files: [{ file_id: 'file-1' }],timezone: 'Europe/Paris',});diff --git a/packages/api/src/agents/triggers/host.ts b/packages/api/src/agents/triggers/host.tsindex 869d326b86..55e7a317c0 100644--- a/packages/api/src/agents/triggers/host.ts+++ b/packages/api/src/agents/triggers/host.ts@@ -622,6 +622,7 @@ async function startRun(...(run?.conversationId != null && {newConversationId: run.conversationId,}),+ ...(run?.chatProjectId != null && { chatProjectId: run.chatProjectId }),...(run?.files != null && { files: run.files }),...(typeof timezone === 'string' && timezone.trim().length > 0? { timezone: timezone.trim() }diff --git a/packages/api/src/schedules/FOLLOWUPS.md b/packages/api/src/schedules/FOLLOWUPS.mdindex 4ebeee3368..cd5551cef9 100644--- a/packages/api/src/schedules/FOLLOWUPS.md+++ b/packages/api/src/schedules/FOLLOWUPS.md@@ -15,7 +15,26 @@ Scheduled chats remain experimental and default-off.which is written on pause, skip, or terminal outcomes, so the client's `started` chip isunreachable.- Add multi-day weekly, timezone, and attachment controls. The API supports these, but the dialog- does not.+ does not. NOTE: the dialog cannot scroll from `md` up (`md:overflow-visible` exists because the+ Ariakit popovers cannot portal out of the focus-trapping Radix dialog), so its content must fit+ the viewport — roughly 30px of slack remain at 1280x720. Each of these controls adds a row and+ will push the footer's Save button out of reach. Adding them needs the height problem solved+ first: give `ControlCombobox` the `portalElement` prop `Dropdown` already has, portal the+ popovers into the dialog content element, and let the form scroll again.++## Known gaps: project scope++- A project deleted inside the window between the resume controller's+ `isScheduleLive(..., { policy: true })` check and `claimScheduleResume` is not caught:+ deletion bumps no revision, so the lease fence cannot see it and the continuation+ starts against a conversation that was just unscoped. Sub-second, and self-correcting+ at the next fire (which auto-disables the schedule). Closing it needs a distinct+ policy conflict returned from the claim that the controller routes through+ abort-and-settle, rather than the bare 409 an `inactive` conflict produces today.+- The stored project converges on an operator pin only when the schedule actually+ FIRES. A schedule that has not fired since the pin moved still carries its old id,+ which the wire projection already papers over but a direct read of the row does not.+ Resume validation is unaffected — it reads the occurrence's own record.## Runtime scopediff --git a/packages/api/src/schedules/engine.spec.ts b/packages/api/src/schedules/engine.spec.tsindex ad841e3c16..ab8019cb3d 100644--- a/packages/api/src/schedules/engine.spec.ts+++ b/packages/api/src/schedules/engine.spec.ts@@ -10,6 +10,7 @@ const LIMITS: ScheduleLimits = {minIntervalMinutes: 60,autoDisableAfterFailures: 5,fireConcurrency: 5,+ requireProject: false,};/**diff --git a/packages/api/src/schedules/fire.spec.ts b/packages/api/src/schedules/fire.spec.tsindex 8284546901..39993730a9 100644--- a/packages/api/src/schedules/fire.spec.ts+++ b/packages/api/src/schedules/fire.spec.ts@@ -13,6 +13,7 @@ const LIMITS: ScheduleLimits = {minIntervalMinutes: 60,autoDisableAfterFailures: 5,fireConcurrency: 5,+ requireProject: false,};function makeSchedule(overrides: Partial<FireableSchedule> = {}): FireableSchedule {diff --git a/packages/api/src/schedules/fire.ts b/packages/api/src/schedules/fire.tsindex de23f83455..ba29863371 100644--- a/packages/api/src/schedules/fire.ts+++ b/packages/api/src/schedules/fire.ts@@ -11,6 +11,7 @@ import {import { AgentTriggerServiceUnavailableError } from '../agents/triggers/service';import { AgentTriggerDeliveryError } from '../agents/triggers/delivery';import { computeNextRunAt, cadenceIntervalMinutes } from './cadence';+import { resolveScheduleProjectId } from './types';/** Consecutive balance skips (pre-fire or mid-generation) before auto-disable. */export const BALANCE_SKIP_DISABLE_THRESHOLD: number = 5;@@ -51,6 +52,7 @@ function buildScheduleTriggerEnvelope(files: Awaited<ReturnType<ScheduleEngineDeps['resolveFiles']>>,conversationId: string,manual: boolean,+ chatProjectId?: string,): AgentTriggerEnvelope {const occurrenceId = buildFireClientRequestId(schedule.id, scheduledFor);const triggerFiles: JsonValue[] = files.map((file) => {@@ -84,6 +86,7 @@ function buildScheduleTriggerEnvelope(run: {conversationId,timezone: schedule.timezone,+ ...(chatProjectId != null && { chatProjectId }),...(triggerFiles.length > 0 && { files: triggerFiles }),metadata: {manual,@@ -303,6 +306,42 @@ export async function fireSchedule(return { fired: false, skipped: reason };}+ // Destination project, re-resolved under the OWNER's current policy: an operator+ // pin outranks the stored id, so tightening the config redirects (or stops) an+ // existing schedule instead of grandfathering where its runs land.+ const chatProjectId = resolveScheduleProjectId(ownerLimits, schedule.chatProjectId);+ if (ownerLimits.requireProject && chatProjectId == null) {+ // The requirement was raised after this schedule was created. Disable rather+ // than filing runs loose: the owner chose no project under the old policy, and+ // only they can say which one now applies.+ await methods.disableSchedule(schedule.id, 'project_required', claimToken);+ await advance();+ return { fired: false, skipped: 'project_required' as const };+ }+ if (chatProjectId != null && (await deps.projectAccess(chatProjectId, user)) !== 'ok') {+ // Gone, or pinned to a project this owner does not have. Either way the run+ // would be filed nowhere (saveConvo drops an unowned chatProjectId), so stop+ // instead of quietly widening the schedule's scope — same reasoning as+ // agent_deleted, and the same immediate disable so failures aren't burned.+ await methods.disableSchedule(schedule.id, 'project_deleted', claimToken);+ await advance();+ return { fired: false, skipped: 'project_deleted' as const };+ }+ // Converge the ROW on the destination this fire resolved — AFTER it has been+ // validated, so an unusable pin is never written. The pin outranks the stored id+ // here and the conversation this occurrence creates is filed under the RESOLVED+ // project, so leaving the row on its old value would make every later+ // re-validation (notably the resume boundary) check a project the conversation was+ // never filed under. Best-effort: the envelope already carries the right+ // destination, so a failed write costs accuracy on a later recheck, never this run.+ if (chatProjectId !== (schedule.chatProjectId ?? undefined)) {+ await methods+ .persistResolvedProject(schedule.id, chatProjectId, claimToken)+ .catch((err: unknown) =>+ logger.warn(`[schedules] could not converge stored project for ${schedule.id}`, err),+ );+ }+if (await deps.isOutOfBalance(user)) {// Revalidate BEFORE writing the skip. Everything above (user, config, permission// and balance lookups) can outlast the 5-minute lease, and a skip is not a no-op:@@ -407,6 +446,7 @@ export async function fireSchedule(files,conversationId,options?.manual === true,+ chatProjectId,);} catch (envelopeError) {logger.error(`[schedules] trigger envelope build failed for ${schedule.id}:`, envelopeError);@@ -443,6 +483,13 @@ export async function fireSchedule(firedAt: new Date(),capacitySlot,deliveryKey,+ // The destination THIS occurrence used. The schedule-level value can move on+ // (a pin redirects later fires, and a paused run does not block them), so a+ // resume must re-validate what its own conversation was filed under.+ // ALWAYS written, `null` when deliberately unscoped: a later reader has to be+ // able to tell "this run had no project" from "this row predates the field",+ // and only the latter may fall back to the schedule's current value.+ chatProjectId: chatProjectId ?? null,...(typeof schedule.configRevision === 'number'? { configRevision: schedule.configRevision }: {}),diff --git a/packages/api/src/schedules/gate.spec.ts b/packages/api/src/schedules/gate.spec.tsindex 6d2199707f..efcec3e461 100644--- a/packages/api/src/schedules/gate.spec.ts+++ b/packages/api/src/schedules/gate.spec.ts@@ -32,6 +32,7 @@ function makeService(base: Cfg, merged: Cfg = base) {upsertBalance: jest.fn(async () => null),initializeNullBalance: jest.fn(async () => null),resolveAgentFireAccess: jest.fn(async () => 'ok' as const),+ getChatProject: jest.fn(async () => ({ _id: 'proj-1' })),isUserDeleting: jest.fn(async () => false),enqueueAgentTrigger: jest.fn(async () => undefined),getTriggerDelivery: jest.fn(async () => null),@@ -46,6 +47,7 @@ const limits = {minIntervalMinutes: 60,autoDisableAfterFailures: 5,fireConcurrency: 5,+ requireProject: false,};describe('v1 experimental gate, asserted at real entry points', () => {@@ -156,6 +158,7 @@ describe('v1 experimental gate, asserted at real entry points', () => {upsertBalance: jest.fn(),initializeNullBalance: jest.fn(),resolveAgentFireAccess: jest.fn(),+ getChatProject: jest.fn(),} as unknown as SchedulesServiceDeps),).toThrow(/isUserDeleting/);});diff --git a/packages/api/src/schedules/handlers.spec.ts b/packages/api/src/schedules/handlers.spec.tsindex 0c32909a1c..c475ea72c6 100644--- a/packages/api/src/schedules/handlers.spec.ts+++ b/packages/api/src/schedules/handlers.spec.ts@@ -60,6 +60,7 @@ describe('toWireSchedule', () => {['agent_id','cadence',+ 'chatProjectId',// Public so the edit dialog can fence its PATCH on the revision it opened// with (updateSchedulePayloadSchema.expectedConfigRevision).'configRevision',diff --git a/packages/api/src/schedules/handlers.ts b/packages/api/src/schedules/handlers.tsindex daec7c7304..ca8d0cb579 100644--- a/packages/api/src/schedules/handlers.ts+++ b/packages/api/src/schedules/handlers.ts@@ -13,12 +13,16 @@ import type {} from './types';import type { ServerRequest } from '~/types';import { isValidTimezone, cadenceIntervalMinutes, computeNextRunAt } from './cadence';+import { resolveScheduleProjectId } from './types';export interface SchedulesHandlersDeps {methods: ScheduleMethods;getLimits: (user?: ScheduleUserContext) => Promise<ScheduleLimits>;/** Agent existence + VIEW access for the requesting user. */canViewAgent: (agentId: string, req: ServerRequest) => Promise<boolean>;+ /** Whether the requesting user owns this chat project. Projects are user-owned,+ * so existence and authorization are the same question. */+ canUseProject: (projectId: string, userId: string) => Promise<boolean>;/** Filters to file ids owned by the user. */filterOwnedFileIds: (fileIds: string[], userId: string) => Promise<string[]>;/** Extends a bounded renewable upload hold on attached files so they survive to the@@ -116,6 +120,14 @@ export function computeCreateDigest(payload: TCreateSchedule): string {daysOfWeek: payload.cadence.daysOfWeek ?? null,},file_ids: payload.file_ids ?? null,+ // `!== undefined`, NOT `!= null`: an OMITTED field still digests byte-identically+ // to a payload from before project scope existed, so an in-flight create retried+ // across the upgrade matches its own row — but an explicit `null` is a different+ // INTENT (clear the scope) and must digest differently. Collapsing the two let a+ // request reuse a pinned create's key with `chatProjectId: null` and receive 201+ // for the pinned row, i.e. success for the opposite of what it asked. A pre-scope+ // client never sent the field at all, so nothing legacy can carry an explicit null.+ ...(payload.chatProjectId !== undefined && { chatProjectId: payload.chatProjectId }),});return createHash('sha256').update(canonical).digest('hex');}@@ -143,7 +155,11 @@ function matchesCreatedSchedule(existing: ISchedule, payload: TCreateSchedule):existing.cadence?.hour === payload.cadence.hour &&existing.cadence?.minute === payload.cadence.minute &&sameList(existing.cadence?.daysOfWeek, payload.cadence.daysOfWeek) &&- sameList(existing.file_ids, payload.file_ids)+ sameList(existing.file_ids, payload.file_ids) &&+ // Only when the payload names one: an operator pin is written to the row without+ // the client ever sending it, and a legacy row predates project scope entirely.+ (payload.chatProjectId === undefined ||+ (existing.chatProjectId ?? null) === (payload.chatProjectId ?? null)));}@@ -173,6 +189,7 @@ export type WireSchedule = Pick<| 'cadence'| 'timezone'| 'target'+ | 'chatProjectId'| 'file_ids'| 'enabled'| 'disabledReason'@@ -185,7 +202,17 @@ export type WireSchedule = Pick<| 'updatedAt'>;-export function toWireSchedule(schedule: ISchedule): WireSchedule {+/**+ * Public projection. `limits` is optional only for callers that have none to hand;+ * pass it wherever one is available so the card shows the destination a fire would+ * ACTUALLY use — an operator pin added after a row was written outranks its stored+ * id at fire time, and a projection reading the raw field would name the wrong+ * project until the owner next edits the schedule.+ */+export function toWireSchedule(+ schedule: ISchedule,+ limits?: Pick<ScheduleLimits, 'projectId'>,+): WireSchedule {return {id: schedule.id,user: schedule.user,@@ -195,6 +222,7 @@ export function toWireSchedule(schedule: ISchedule): WireSchedule {cadence: schedule.cadence,timezone: schedule.timezone,target: schedule.target,+ chatProjectId: resolveScheduleProjectId(limits ?? {}, schedule.chatProjectId),file_ids: schedule.file_ids,enabled: schedule.enabled,disabledReason: schedule.disabledReason,@@ -258,6 +286,63 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHreturn true;}+ /**+ * The destination project a write commits, or `false` when the write was refused+ * (the response is already sent). `undefined` is a real value: an unscoped create,+ * or an update that explicitly cleared the scope.+ *+ * Deliberately resolved from the SAME {@link resolveScheduleProjectId} the fire path+ * uses, so a schedule this handler accepts is one the next fire also accepts —+ * the create/fire precheck symmetry `resolveAgentFireAccess` already establishes+ * for agents.+ */+ async function resolveWriteProject(+ res: Response,+ userId: string,+ limits: ScheduleLimits,+ requested: string | null | undefined,+ stored?: string,+ /** Lets a DISABLING edit skip the requirement while still refusing a destination+ * that disagrees with a pin — the two rules are independent, and folding them+ * together let an explicit clear slip past the pin check entirely. */+ options?: { enforceRequirement?: boolean },+ ): Promise<string | undefined | false> {+ // A pin is the ONLY destination. An OMITTED field takes it silently (the client has+ // no choice to make), but anything explicit that disagrees is refused rather than+ // quietly rewritten — including `null`, which the payload contract defines as+ // clearing the scope. Answering 201/200 to an explicit clear while filing the+ // schedule under the pin reports success for the opposite of what was asked.+ if (limits.projectId != null && requested !== undefined && requested !== limits.projectId) {+ res.status(400).json({ error: 'Scheduled chats are pinned to a specific project' });+ return false;+ }+ const chatProjectId = resolveScheduleProjectId(+ limits,+ requested === undefined ? stored : requested,+ );+ if (chatProjectId == null) {+ if (limits.requireProject && options?.enforceRequirement !== false) {+ res.status(400).json({ error: 'Scheduled chats must be assigned to a project' });+ return false;+ }+ return undefined;+ }+ // Re-checked even when it only came from storage: the hold is bounded by the+ // project's lifetime, not by whether this request touched the field, and an+ // edit that leaves a schedule pointing at a deleted project would otherwise+ // succeed and then be auto-disabled by its very next fire.+ if (!(await deps.canUseProject(chatProjectId, userId))) {+ res.status(400).json({+ error:+ limits.projectId != null+ ? 'The configured schedules project was not found'+ : 'Project not found',+ });+ return false;+ }+ return chatProjectId;+ }+/*** Extends the bounded upload hold on attached files (so they survive to the first* fire, which consumes them permanently), with bounded retry. Returns false when it@@ -323,19 +408,27 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesH]);retryDeferredDeletions(requestUser(req).id);res.json({- schedules: schedules.map(toWireSchedule),- limits: { maxPerUser: limits.maxPerUser },+ schedules: schedules.map((schedule) => toWireSchedule(schedule, limits)),+ limits: {+ maxPerUser: limits.maxPerUser,+ requireProject: limits.requireProject,+ ...(limits.projectId != null && { projectId: limits.projectId }),+ },});}async function getSchedule(req: ServerRequest, res: Response): Promise<void> {const { id } = req.params as { id: string };- const schedule = await deps.methods.getScheduleById(id, requestUser(req).id);+ const user = requestUser(req);+ const [schedule, limits] = await Promise.all([+ deps.methods.getScheduleById(id, user.id),+ deps.getLimits(user),+ ]);if (schedule == null) {res.status(404).json({ error: 'Schedule not found' });return;}- res.json(toWireSchedule(schedule));+ res.json(toWireSchedule(schedule, limits));}async function createSchedule(req: ServerRequest, res: Response): Promise<void> {@@ -356,6 +449,10 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHif (!(await validatePayload(req, res, parsed.data, limits))) {return;}+ // Digested from the CLIENT's payload, never from the policy-resolved destination:+ // the digest records one create INTENT, and today's policy is not part of that+ // intent. Resolving first made an operator's pin change (or a deleted project)+ // re-digest a genuine retry into a mismatch.const digest = computeCreateDigest(parsed.data);/**@@ -407,7 +504,7 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHreturn;}logger.info(`[schedules] create retry resolved to ${existing.id} for user ${user.id}`);- res.status(201).json(toWireSchedule(fresh));+ res.status(201).json(toWireSchedule(fresh, limits));};// Resolve a retry BEFORE the capacity pre-check: a retry whose first attempt@@ -422,6 +519,21 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHawait respondToReplay(replayed);return;}+ // Project policy applies to a NEW insert only, and is therefore resolved AFTER every+ // replay lookup above. A committed create whose response was lost must still be+ // recoverable by an identical retry: applying today's policy first let a raised+ // requirement, a deleted project, or a moved pin answer 400 for a row that already+ // exists — pushing the client to rotate its key and create a duplicate schedule,+ // which is precisely what the idempotency key exists to prevent.+ const chatProjectId = await resolveWriteProject(+ res,+ user.id,+ limits,+ parsed.data.chatProjectId,+ );+ if (chatProjectId === false) {+ return;+ }// Fail fast on an obvious over-limit BEFORE retaining attachments, so the common// case never clears an upload TTL it then can't use. The {user, slot} partial// unique index below is the atomic arbiter for the concurrent-create race.@@ -471,6 +583,7 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHconst created = await deps.methods.createScheduleWithSlot({...parsed.data,+ chatProjectId: chatProjectId ?? undefined,id,user: user.id as never,tenantId: user.tenantId,@@ -545,7 +658,7 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHif (rolledBack === 'kept') {const current = await deps.methods.getScheduleById(id, user.id);if (current != null) {- res.status(201).json(toWireSchedule(current));+ res.status(201).json(toWireSchedule(current, limits));return;}}@@ -569,11 +682,11 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHlogger.warn(`[schedules] create for ${id} left unarmed after a concurrent edit`);}logger.info(`[schedules] created ${id} for user ${user.id}`);- res.status(201).json(toWireSchedule(current));+ res.status(201).json(toWireSchedule(current, limits));return;}logger.info(`[schedules] created ${id} for user ${user.id}`);- res.status(201).json(toWireSchedule(created));+ res.status(201).json(toWireSchedule(created, limits));}async function updateSchedule(req: ServerRequest, res: Response): Promise<void> {@@ -649,6 +762,44 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHres.status(400).json({ error: 'Agent not found or not accessible' });return;}+ // The destination is re-resolved on every edit that leaves the schedule ENABLED,+ // against the stored id when this PATCH does not touch the field — the same shape+ // as the stored-agent and effective-cadence rechecks above, and for the same+ // reason: an edit that "succeeds" into a state the next fire auto-disables is not+ // a success. A disabling edit skips the requirement so a schedule stopped by a+ // project_required/project_deleted auto-disable can still be turned off or renamed.+ let chatProjectId: string | undefined;+ if (enabled) {+ const resolved = await resolveWriteProject(+ res,+ user.id,+ limits,+ parsed.data.chatProjectId,+ existing.chatProjectId,+ );+ if (resolved === false) {+ return;+ }+ chatProjectId = resolved;+ } else if (parsed.data.chatProjectId !== undefined) {+ // `!== undefined`, so an explicit `null` lands here too: a pin disagreement is+ // refused whether the edit assigns a different project or clears the scope+ // outright. Only the REQUIREMENT is waived for a disabling edit — without that+ // distinction a pinned deployment accepted `{enabled: false, chatProjectId: null}`+ // and unset the row while still reporting the pin back on the wire.+ const resolved = await resolveWriteProject(+ res,+ user.id,+ limits,+ parsed.data.chatProjectId,+ undefined,+ { enforceRequirement: false },+ );+ if (resolved === false) {+ return;+ }+ chatProjectId = resolved;+ }const cadenceChanged =parsed.data.cadence != null || parsed.data.timezone != null || parsed.data.enabled != null;const reEnabled = parsed.data.enabled === true && existing.enabled === false;@@ -658,6 +809,17 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesH// cadence one, or a name/prompt edit would silently leave it dead.const needsArming = existing.nextRunAt == null;const update: Partial<ISchedule> = { ...editedFields } as Partial<ISchedule>;+ // `chatProjectId` is resolved, not copied: an operator pin rewrites it even when+ // this PATCH never mentioned the field, so the row converges on the policy+ // instead of drifting until the owner happens to touch the picker.+ delete (update as { chatProjectId?: unknown }).chatProjectId;+ // ONLY an explicit `null` clears the scope. A disabling edit resolves nothing and+ // must leave the stored destination intact, or turning a schedule off would+ // silently forget where its runs used to land.+ const clearsProject = parsed.data.chatProjectId === null && chatProjectId == null;+ if (chatProjectId != null) {+ update.chatProjectId = chatProjectId;+ }if (enabled && (cadenceChanged || needsArming)) {const nextRunAt = computeNextRunAt({ cadence, timezone, scheduleId: existing.id });if (nextRunAt == null) {@@ -670,7 +832,13 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHupdate.failureCount = 0;update.balanceSkipCount = 0;}- const unset = reEnabled ? { disabledReason: 1 as const } : undefined;+ const unset =+ reEnabled || clearsProject+ ? {+ ...(reEnabled && { disabledReason: 1 as const }),+ ...(clearsProject && { chatProjectId: 1 as const }),+ }+ : undefined;// Retain the new attachments BEFORE committing the edit, so a retention failure// leaves the ENTIRE schedule unchanged rather than persisting prompt/cadence/// agent/enabled changes while only reverting file_ids. A file whose TTL was@@ -726,7 +894,7 @@ export function createSchedulesHandlers(deps: SchedulesHandlersDeps): SchedulesHres.status(404).json({ error: 'Schedule not found' });return;}- res.json(toWireSchedule(schedule));+ res.json(toWireSchedule(schedule, limits));}async function deleteSchedule(req: ServerRequest, res: Response): Promise<void> {diff --git a/packages/api/src/schedules/project.spec.ts b/packages/api/src/schedules/project.spec.tsnew file mode 100644index 0000000000..8e8b2bee5f--- /dev/null+++ b/packages/api/src/schedules/project.spec.ts@@ -0,0 +1,666 @@+import type { ISchedule, IScheduleRun } from '@librechat/data-schemas';+import type { Response } from 'express';+import type { ScheduleEngineDeps, ScheduleLimits, ScheduleUserContext } from './types';+import type { SchedulesHandlersDeps } from './handlers';+import type { FireableSchedule } from './types';+import type { ServerRequest } from '~/types';+import { createSchedulesHandlers, computeCreateDigest, toWireSchedule } from './handlers';+import { withCapacitySlot } from './capacity';+import { fireSchedule } from './fire';++const OWNER: ScheduleUserContext = { id: 'user-1', tenantId: 't1', role: 'USER' };++const BASE_LIMITS: ScheduleLimits = {+ enabled: true,+ maxPerUser: 10,+ minIntervalMinutes: 60,+ autoDisableAfterFailures: 5,+ fireConcurrency: 5,+ requireProject: false,+};++function makeSchedule(overrides: Partial<FireableSchedule> = {}): FireableSchedule {+ return {+ id: 'sched-1',+ user: 'user-1' as never,+ tenantId: 't1',+ name: 'Digest',+ prompt: 'Summarize',+ agent_id: 'agent-1',+ cadence: { frequency: 'daily', hour: 8, minute: 0 },+ timezone: 'America/New_York',+ target: 'new',+ enabled: true,+ claimToken: 'ct-1',+ leaseBy: 'inst-1',+ runCount: 0,+ failureCount: 0,+ balanceSkipCount: 0,+ ...overrides,+ } as FireableSchedule;+}++/** Minimal run store: enough for the reservation the fire path makes once its+ * prechecks pass, so a skipped fire is distinguishable from a dispatched one. */+function makeMethods() {+ const disabled: string[] = [];+ const reservations: Array<Partial<IScheduleRun>> = [];+ const methods = {+ releaseLease: jest.fn(async () => true),+ releaseLeaseByHolder: jest.fn(async () => undefined),+ advanceSchedule: jest.fn(async () => true),+ disableSchedule: jest.fn(async (_id: string, reason: string) => {+ disabled.push(reason);+ }),+ revalidateClaim: jest.fn(async () => true),+ reserveStartedRun: jest.fn(async (data: Partial<IScheduleRun>) => {+ reservations.push(data);+ return { run: { scheduleId: 'sched-1' } };+ }),+ getCapacityOccupancy: jest.fn(async () => ({ takenSlots: [] as number[], unslotted: 0 })),+ deleteScheduleRun: jest.fn(async () => undefined),+ setRunFireDetails: jest.fn(async () => undefined),+ persistResolvedProject: jest.fn(async () => undefined),+ countActiveRuns: jest.fn(async () => 0),+ recordSkippedRun: jest.fn(async () => undefined),+ };+ return { methods, disabled, reservations };+}++function makeEngineDeps(+ methods: ReturnType<typeof makeMethods>['methods'],+ over: Partial<ScheduleEngineDeps> = {},+): ScheduleEngineDeps {+ return {+ methods: methods as unknown as ScheduleEngineDeps['methods'],+ getLimits: async () => BASE_LIMITS,+ getUserContext: async () => OWNER,+ isOutOfBalance: async () => false,+ agentAccess: async () => 'ok',+ projectAccess: async () => 'ok',+ hasScheduleAccess: async () => true,+ resolveFiles: async () => [],+ enqueueTrigger: jest.fn(async () => undefined),+ getTriggerDelivery: async () => null,+ runInTenantContext: (_user, fn) => fn(),+ getJobStatus: async () => null,+ abortScheduledJob: async () => undefined,+ clearReconciledJob: async () => undefined,+ isOwnerDeleting: async () => false,+ isGloballyDisabled: async () => false,+ countActiveRunsGlobal: async () => 0,+ withGlobalCapacitySlot: (cap: number, claim: (slot: number) => Promise<unknown>) =>+ withCapacitySlot(+ cap,+ () => methods.getCapacityOccupancy(),+ claim as Parameters<typeof withCapacitySlot>[2],+ ),+ ...over,+ } as ScheduleEngineDeps;+}++const dueAt = () => new Date(Date.now() - 60_000);++describe('fire-time project scope', () => {+ it('carries the stored project into the trigger envelope', async () => {+ const { methods } = makeMethods();+ const enqueueTrigger = jest.fn<+ ReturnType<ScheduleEngineDeps['enqueueTrigger']>,+ Parameters<ScheduleEngineDeps['enqueueTrigger']>+ >(async () => undefined);++ const result = await fireSchedule(+ makeEngineDeps(methods, { enqueueTrigger }),+ makeSchedule({ chatProjectId: 'proj-1' }),+ BASE_LIMITS,+ dueAt(),+ );++ expect(result.fired).toBe(true);+ expect(enqueueTrigger.mock.calls[0][0]).toMatchObject({+ run: { chatProjectId: 'proj-1' },+ });+ });++ /** The pin is a policy about where scheduled runs land. A row written before the+ * pin must follow it, not keep its own destination until someone edits it. */+ it('lets an operator pin override the stored project', async () => {+ const { methods } = makeMethods();+ const enqueueTrigger = jest.fn<+ ReturnType<ScheduleEngineDeps['enqueueTrigger']>,+ Parameters<ScheduleEngineDeps['enqueueTrigger']>+ >(async () => undefined);+ const pinned = { ...BASE_LIMITS, requireProject: true, projectId: 'proj-pinned' };++ await fireSchedule(+ makeEngineDeps(methods, { enqueueTrigger, getLimits: async () => pinned }),+ makeSchedule({ chatProjectId: 'proj-old' }),+ BASE_LIMITS,+ dueAt(),+ );++ expect(enqueueTrigger.mock.calls[0][0]).toMatchObject({+ run: { chatProjectId: 'proj-pinned' },+ });+ });++ /** Raising the requirement must STOP schedules that predate it — filing their runs+ * loose would quietly ignore the policy the operator just set. */+ it('disables an unscoped schedule once a project becomes required', async () => {+ const { methods, disabled } = makeMethods();+ const enqueueTrigger = jest.fn(async () => undefined);+ const required = { ...BASE_LIMITS, requireProject: true };++ const result = await fireSchedule(+ makeEngineDeps(methods, { enqueueTrigger, getLimits: async () => required }),+ makeSchedule(),+ BASE_LIMITS,+ dueAt(),+ );++ expect(result).toMatchObject({ fired: false, skipped: 'project_required' });+ expect(disabled).toEqual(['project_required']);+ expect(enqueueTrigger).not.toHaveBeenCalled();+ // Every path advances, so the schedule cannot wedge on the same occurrence.+ expect(methods.advanceSchedule).toHaveBeenCalledTimes(1);+ });++ /** Mirrors agent_deleted: stop at the boundary rather than dispatching a billed run+ * whose conversation the conversation save would file nowhere. */+ it('disables when the destination project is gone', async () => {+ const { methods, disabled } = makeMethods();+ const enqueueTrigger = jest.fn(async () => undefined);++ const result = await fireSchedule(+ makeEngineDeps(methods, { enqueueTrigger, projectAccess: async () => 'missing' }),+ makeSchedule({ chatProjectId: 'proj-gone' }),+ BASE_LIMITS,+ dueAt(),+ );++ expect(result).toMatchObject({ fired: false, skipped: 'project_deleted' });+ expect(disabled).toEqual(['project_deleted']);+ expect(enqueueTrigger).not.toHaveBeenCalled();+ });++ /**+ * The row must not keep claiming project A once a pin has been sending this+ * schedule's conversations to B: every later re-validation — the resume boundary+ * above all — would then check a project the conversation was never filed under.+ */+ it('converges the stored project on the destination it actually resolved', async () => {+ const { methods } = makeMethods();+ const pinned = { ...BASE_LIMITS, requireProject: true, projectId: 'proj-pinned' };++ await fireSchedule(+ makeEngineDeps(methods, { getLimits: async () => pinned }),+ makeSchedule({ chatProjectId: 'proj-old' }),+ BASE_LIMITS,+ dueAt(),+ );++ // Claim-token fenced like every other worker-side write.+ expect(methods.persistResolvedProject).toHaveBeenCalledWith('sched-1', 'proj-pinned', 'ct-1');+ });++ it('leaves the row alone when the resolved destination already matches', async () => {+ const { methods } = makeMethods();++ await fireSchedule(+ makeEngineDeps(methods),+ makeSchedule({ chatProjectId: 'proj-1' }),+ BASE_LIMITS,+ dueAt(),+ );++ expect(methods.persistResolvedProject).not.toHaveBeenCalled();+ });++ /** An unusable pin is refused, and must never be written to the row on the way out. */+ it('does not converge a destination that failed validation', async () => {+ const { methods } = makeMethods();++ await fireSchedule(+ makeEngineDeps(methods, { projectAccess: async () => 'missing' }),+ makeSchedule({ chatProjectId: 'proj-gone' }),+ BASE_LIMITS,+ dueAt(),+ );++ expect(methods.persistResolvedProject).not.toHaveBeenCalled();+ });++ /** A failed convergence costs accuracy on a later recheck, never this run. */+ it('fires anyway when the convergence write fails', async () => {+ const { methods } = makeMethods();+ methods.persistResolvedProject = jest.fn(async () => {+ throw new Error('mongo down');+ });+ const enqueueTrigger = jest.fn(async () => undefined);+ const pinned = { ...BASE_LIMITS, requireProject: true, projectId: 'proj-pinned' };++ const result = await fireSchedule(+ makeEngineDeps(methods, { enqueueTrigger, getLimits: async () => pinned }),+ makeSchedule({ chatProjectId: 'proj-old' }),+ BASE_LIMITS,+ dueAt(),+ );++ expect(result.fired).toBe(true);+ expect(enqueueTrigger).toHaveBeenCalledTimes(1);+ });++ /** The schedule-level value can move on while a run is paused, so the RESERVATION+ * is what a resume re-validates against. */+ it('records the destination on the occurrence it reserves', async () => {+ const { methods, reservations } = makeMethods();+ const pinned = { ...BASE_LIMITS, requireProject: true, projectId: 'proj-pinned' };++ await fireSchedule(+ makeEngineDeps(methods, { getLimits: async () => pinned }),+ makeSchedule({ chatProjectId: 'proj-old' }),+ BASE_LIMITS,+ dueAt(),+ );++ expect(reservations[0].chatProjectId).toBe('proj-pinned');+ });++ /** Recorded as an explicit null, never omitted: a later reader must be able to tell+ * "this run had no project" from "this row predates the field". */+ it('records an unscoped occurrence as an explicit null', async () => {+ const { methods, reservations } = makeMethods();++ await fireSchedule(makeEngineDeps(methods), makeSchedule(), BASE_LIMITS, dueAt());++ expect(reservations[0]).toHaveProperty('chatProjectId', null);+ });++ it('never consults project access for an unscoped schedule', async () => {+ const { methods } = makeMethods();+ const projectAccess = jest.fn(async () => 'ok' as const);++ await fireSchedule(+ makeEngineDeps(methods, { projectAccess }),+ makeSchedule(),+ BASE_LIMITS,+ dueAt(),+ );++ expect(projectAccess).not.toHaveBeenCalled();+ });+});++function makeRes() {+ const captured: { status?: number; body?: unknown } = {};+ const res = {+ status(code: number) {+ captured.status = code;+ return this;+ },+ json(body: unknown) {+ captured.body = body;+ return this;+ },+ };+ return { res: res as unknown as Response, captured };+}++const CREATE_BODY = {+ name: 'Digest',+ prompt: 'Summarize',+ agent_id: 'agent-1',+ cadence: { frequency: 'daily' as const, hour: 8, minute: 0 },+ timezone: 'America/New_York',+ clientRequestId: 'intent-1',+};++function makeReq(body: Record<string, unknown>, params: Record<string, string> = {}) {+ return {+ body,+ params,+ user: { id: 'user-1', tenantId: 't1', role: 'USER' },+ } as unknown as ServerRequest;+}++function makeHandlerDeps(+ limits: Partial<ScheduleLimits>,+ over: Partial<SchedulesHandlersDeps> = {},+) {+ const created: Array<Partial<ISchedule>> = [];+ const updates: Array<{ update: Partial<ISchedule>; unset?: Record<string, 1> }> = [];+ const methods = {+ countSchedulesByUser: jest.fn(async () => 0),+ createScheduleWithSlot: jest.fn(async (data: Partial<ISchedule>) => {+ created.push(data);+ return { ...data, configRevision: 0 } as ISchedule;+ }),+ getScheduleByClientRequestId: jest.fn(async () => null),+ // Reads back what this attempt inserted: creation arms in a SECOND write and then+ // re-reads, so a null here would send every create down the "row is gone" 410.+ getScheduleById: jest.fn(async () => (created[0] ?? null) as ISchedule | null),+ updateScheduleById: jest.fn(+ async (_id: string, _user: string, update: Partial<ISchedule>, unset?: Record<string, 1>) => {+ updates.push({ update, unset });+ return { id: 'sched-1', ...update } as ISchedule;+ },+ ),+ armSchedule: jest.fn(async () => true),+ getDeletingScheduleIds: jest.fn(async () => []),+ };+ const deps = {+ methods: methods as unknown as SchedulesHandlersDeps['methods'],+ getLimits: async () => ({ ...BASE_LIMITS, ...limits }),+ canViewAgent: async () => true,+ canUseProject: async () => true,+ filterOwnedFileIds: async (ids: string[]) => ids,+ markFilesUsed: async () => undefined,+ fireNow: async () => null,+ deleteSchedule: async () => 'deleted',+ isUserDeleting: async () => false,+ ...over,+ } as unknown as SchedulesHandlersDeps;+ return { deps, methods, created, updates };+}++describe('write-time project scope', () => {+ it('refuses a project the requester does not own', async () => {+ const { deps, methods } = makeHandlerDeps({}, { canUseProject: async () => false });+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).createSchedule(+ makeReq({ ...CREATE_BODY, chatProjectId: 'someone-elses' }),+ res,+ );++ expect(captured.status).toBe(400);+ expect(methods.createScheduleWithSlot).not.toHaveBeenCalled();+ });++ it('refuses an unscoped create when the deployment requires a project', async () => {+ const { deps, methods } = makeHandlerDeps({ requireProject: true });+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).createSchedule(makeReq({ ...CREATE_BODY }), res);++ expect(captured.status).toBe(400);+ expect(methods.createScheduleWithSlot).not.toHaveBeenCalled();+ });++ /** The client sends nothing under a pin; the row still records the destination so+ * its projection and its runs agree about where they land. */+ it('stores the pinned project even when the payload omits it', async () => {+ const { deps, created } = makeHandlerDeps({ requireProject: true, projectId: 'proj-pinned' });+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).createSchedule(makeReq({ ...CREATE_BODY }), res);++ expect(captured.status).toBe(201);+ expect(created[0].chatProjectId).toBe('proj-pinned');+ });++ /** Silently rewriting a named destination would hide a real disagreement about+ * where the schedule's runs go. */+ /** `null` is the payload contract's CLEAR, not an omission. Resolving it to the pin+ * would answer 201 for the opposite of what was asked. */+ it('refuses an explicit clear when a project is pinned', async () => {+ const { deps, methods } = makeHandlerDeps({ projectId: 'proj-pinned' });+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).createSchedule(+ makeReq({ ...CREATE_BODY, chatProjectId: null }),+ res,+ );++ expect(captured.status).toBe(400);+ expect(methods.createScheduleWithSlot).not.toHaveBeenCalled();+ });++ /**+ * The idempotency key exists so a create whose response was lost can be recovered by+ * an identical retry. Policy that changed in between must not turn that recovery into+ * a 400 — the client would rotate its key and create a DUPLICATE schedule, the exact+ * failure the key prevents.+ */+ it('recovers a committed create by retry even after the policy tightened', async () => {+ const { deps, methods } = makeHandlerDeps(+ { requireProject: true, projectId: 'proj-pinned' },+ { canUseProject: async () => false },+ );+ const original = {+ id: 'sched-1',+ user: 'user-1',+ name: CREATE_BODY.name,+ prompt: CREATE_BODY.prompt,+ agent_id: CREATE_BODY.agent_id,+ timezone: CREATE_BODY.timezone,+ target: 'new',+ enabled: true,+ cadence: CREATE_BODY.cadence,+ configRevision: 0,+ nextRunAt: new Date('2026-09-01T12:00:00Z'),+ clientRequestDigest: computeCreateDigest({+ ...CREATE_BODY,+ target: 'new',+ enabled: true,+ } as never),+ } as unknown as ISchedule;+ (methods.getScheduleByClientRequestId as jest.Mock).mockResolvedValue(original);+ (methods.getScheduleById as jest.Mock).mockResolvedValue(original);+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).createSchedule(makeReq({ ...CREATE_BODY }), res);++ expect(captured.status).toBe(201);+ expect(methods.createScheduleWithSlot).not.toHaveBeenCalled();+ });++ it('refuses a create that names a project other than the pin', async () => {+ const { deps, methods } = makeHandlerDeps({ projectId: 'proj-pinned' });+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).createSchedule(+ makeReq({ ...CREATE_BODY, chatProjectId: 'proj-other' }),+ res,+ );++ expect(captured.status).toBe(400);+ expect(methods.createScheduleWithSlot).not.toHaveBeenCalled();+ });++ const storedSchedule = (over: Partial<ISchedule> = {}): ISchedule =>+ ({+ id: 'sched-1',+ user: 'user-1',+ name: 'Digest',+ prompt: 'Summarize',+ agent_id: 'agent-1',+ cadence: { frequency: 'daily', hour: 8, minute: 0 },+ timezone: 'America/New_York',+ target: 'new',+ enabled: true,+ configRevision: 3,+ nextRunAt: new Date('2026-09-01T12:00:00Z'),+ runCount: 0,+ failureCount: 0,+ balanceSkipCount: 0,+ ...over,+ }) as unknown as ISchedule;++ it('clears the scope only on an explicit null', async () => {+ const { deps, methods, updates } = makeHandlerDeps({});+ (methods.getScheduleById as jest.Mock).mockResolvedValue(+ storedSchedule({ chatProjectId: 'proj-1' }),+ );+ const { res } = makeRes();++ await createSchedulesHandlers(deps).updateSchedule(+ makeReq({ chatProjectId: null }, { id: 'sched-1' }),+ res,+ );++ expect(updates[0].unset).toMatchObject({ chatProjectId: 1 });+ expect(updates[0].update).not.toHaveProperty('chatProjectId');+ });++ /** A rename must not drag the stored destination along as an edit, but it also must+ * not drop it. */+ it('leaves an untouched scope intact on an unrelated edit', async () => {+ const { deps, methods, updates } = makeHandlerDeps({});+ (methods.getScheduleById as jest.Mock).mockResolvedValue(+ storedSchedule({ chatProjectId: 'proj-1' }),+ );+ const { res } = makeRes();++ await createSchedulesHandlers(deps).updateSchedule(+ makeReq({ name: 'Renamed' }, { id: 'sched-1' }),+ res,+ );++ expect(updates[0].unset).toBeUndefined();+ expect(updates[0].update.chatProjectId).toBe('proj-1');+ });++ /** The requirement is checked against the EFFECTIVE state, so a schedule that+ * already has a project is editable without resending it. */+ it('accepts an unrelated edit under requireProject when a project is stored', async () => {+ const { deps, methods } = makeHandlerDeps({ requireProject: true });+ (methods.getScheduleById as jest.Mock).mockResolvedValue(+ storedSchedule({ chatProjectId: 'proj-1' }),+ );+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).updateSchedule(+ makeReq({ name: 'Renamed' }, { id: 'sched-1' }),+ res,+ );++ expect(captured.status).toBeUndefined();+ expect(methods.updateScheduleById).toHaveBeenCalled();+ });++ it('refuses an edit that leaves an unscoped schedule enabled under requireProject', async () => {+ const { deps, methods } = makeHandlerDeps({ requireProject: true });+ (methods.getScheduleById as jest.Mock).mockResolvedValue(storedSchedule());+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).updateSchedule(+ makeReq({ name: 'Renamed' }, { id: 'sched-1' }),+ res,+ );++ expect(captured.status).toBe(400);+ expect(methods.updateScheduleById).not.toHaveBeenCalled();+ });++ /** Otherwise a schedule auto-disabled for project_required could never be turned+ * off or tidied up — the requirement would trap it. */+ it('still allows DISABLING an unscoped schedule under requireProject', async () => {+ const { deps, methods } = makeHandlerDeps({ requireProject: true });+ (methods.getScheduleById as jest.Mock).mockResolvedValue(storedSchedule());+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).updateSchedule(+ makeReq({ enabled: false }, { id: 'sched-1' }),+ res,+ );++ expect(captured.status).toBeUndefined();+ expect(methods.updateScheduleById).toHaveBeenCalled();+ });++ /** An omitted field and an explicit `null` are different INTENTS, so they must not+ * share a digest — otherwise a key reused with a clear is answered 201 describing+ * the pinned row it did not ask for. */+ it('digests an explicit clear differently from an omitted field', () => {+ const omitted = computeCreateDigest({ ...CREATE_BODY, target: 'new', enabled: true } as never);+ const cleared = computeCreateDigest({+ ...CREATE_BODY,+ target: 'new',+ enabled: true,+ chatProjectId: null,+ } as never);+ expect(cleared).not.toBe(omitted);+ });++ /** ...while an omitted field still digests exactly as it did before project scope+ * existed, so a create in flight across the upgrade still matches its own row. */+ it('keeps the omitted-field digest stable against a pre-scope payload', () => {+ const withKey = computeCreateDigest({+ ...CREATE_BODY,+ target: 'new',+ enabled: true,+ chatProjectId: undefined,+ } as never);+ const withoutKey = computeCreateDigest({+ ...CREATE_BODY,+ target: 'new',+ enabled: true,+ } as never);+ expect(withKey).toBe(withoutKey);+ });++ /** A pin disagreement is refused whether the edit assigns a different project or+ * clears the scope — only the REQUIREMENT is waived for a disabling edit. */+ it('refuses an explicit clear under a pin even while disabling', async () => {+ const { deps, methods } = makeHandlerDeps({ projectId: 'proj-pinned' });+ (methods.getScheduleById as jest.Mock).mockResolvedValue(+ storedSchedule({ chatProjectId: 'proj-pinned' }),+ );+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).updateSchedule(+ makeReq({ enabled: false, chatProjectId: null }, { id: 'sched-1' }),+ res,+ );++ expect(captured.status).toBe(400);+ expect(methods.updateScheduleById).not.toHaveBeenCalled();+ });++ /** The requirement, unlike the pin, IS waived so a stopped row stays tidy-able. */+ it('allows clearing the scope while disabling when only a requirement is set', async () => {+ const { deps, methods, updates } = makeHandlerDeps({ requireProject: true });+ (methods.getScheduleById as jest.Mock).mockResolvedValue(+ storedSchedule({ chatProjectId: 'proj-1' }),+ );+ const { res, captured } = makeRes();++ await createSchedulesHandlers(deps).updateSchedule(+ makeReq({ enabled: false, chatProjectId: null }, { id: 'sched-1' }),+ res,+ );++ expect(captured.status).toBeUndefined();+ expect(updates[0].unset).toMatchObject({ chatProjectId: 1 });+ });++ /** Turning a schedule off is not a decision about its destination. */+ it('keeps the stored project when a schedule is disabled', async () => {+ const { deps, methods, updates } = makeHandlerDeps({});+ (methods.getScheduleById as jest.Mock).mockResolvedValue(+ storedSchedule({ chatProjectId: 'proj-1' }),+ );+ const { res } = makeRes();++ await createSchedulesHandlers(deps).updateSchedule(+ makeReq({ enabled: false }, { id: 'sched-1' }),+ res,+ );++ expect(updates[0].unset).toBeUndefined();+ expect(updates[0].update).not.toHaveProperty('chatProjectId');+ });+});++describe('wire projection', () => {+ const row = { id: 'sched-1', chatProjectId: 'proj-stored' } as unknown as ISchedule;++ it('reports the pin rather than the stored id', () => {+ expect(toWireSchedule(row, { projectId: 'proj-pinned' }).chatProjectId).toBe('proj-pinned');+ });++ it('reports the stored id when nothing is pinned', () => {+ expect(toWireSchedule(row, {}).chatProjectId).toBe('proj-stored');+ });+});diff --git a/packages/api/src/schedules/service.spec.ts b/packages/api/src/schedules/service.spec.tsindex 1c609baad0..52e24dc5f6 100644--- a/packages/api/src/schedules/service.spec.ts+++ b/packages/api/src/schedules/service.spec.ts@@ -63,6 +63,7 @@ function makeService(upsertBalance: jest.fn(async () => null),initializeNullBalance: jest.fn(async () => null),resolveAgentFireAccess: jest.fn(async () => 'ok' as const),+ getChatProject: jest.fn(async () => ({ _id: 'proj-1' })),isUserDeleting: jest.fn(async () => false),enqueueAgentTrigger,getTriggerDelivery: jest.fn(async () => null),@@ -132,6 +133,7 @@ describe('manual Run Now lease cleanup', () => {minIntervalMinutes: 60,autoDisableAfterFailures: 5,fireConcurrency: 5,+ requireProject: false,}),).rejects.toThrow('user lookup failed');@@ -165,6 +167,7 @@ describe('balance initialization', () => {upsertBalance,initializeNullBalance,resolveAgentFireAccess: jest.fn(async () => 'ok' as const),+ getChatProject: jest.fn(async () => ({ _id: 'proj-1' })),isUserDeleting: jest.fn(async () => false),enqueueAgentTrigger: jest.fn(async () => undefined),getTriggerDelivery: jest.fn(async () => null),@@ -276,6 +279,7 @@ describe('balance initialization', () => {upsertBalance,initializeNullBalance,resolveAgentFireAccess: jest.fn(async () => 'ok' as const),+ getChatProject: jest.fn(async () => ({ _id: 'proj-1' })),isUserDeleting: jest.fn(async () => false),enqueueAgentTrigger: jest.fn(async () => undefined),getTriggerDelivery: jest.fn(async () => null),@@ -817,6 +821,198 @@ describe('isScheduleLive policy recheck', () => {await expect(service.isScheduleLive('s1', undefined, { policy: true })).resolves.toBe(false);});++ /**+ * Project policy rides this branch on purpose: BOTH callers route its refusal through+ * abort-and-settle, so a policy stop settles the occurrence rather than leaving it at+ * `requires_action` answering 409 to every approval until it expires.+ */+ describe('project policy', () => {+ function makeProjectService(+ row: Record<string, unknown>,+ schedulesConfig: Record<string, unknown>,+ project: unknown = { _id: 'proj-1' },+ over: { run?: { recorded: boolean; chatProjectId?: string } | null } = {},+ ) {+ const service = makeService(+ jest.fn<Promise<ActiveRun[]>, [string]>().mockResolvedValue([]),+ jest.fn(async () => ({+ interfaceConfig: { schedules: { use: true, ...schedulesConfig } },+ })) as unknown as SchedulesServiceDeps['getAppConfig'],+ );+ const methods = service.engineDeps.methods as unknown as {+ getScheduleById: jest.Mock;+ getRoleByName: jest.Mock;+ };+ methods.getScheduleById = jest.fn(async () => ({+ id: 's1',+ user: 'u1',+ enabled: true,+ ...row,+ }));+ methods.getRoleByName = jest.fn(async () => ({ permissions: { SCHEDULES: { USE: true } } }));+ (methods as unknown as { getScheduleRunProject: jest.Mock }).getScheduleRunProject = jest.fn(+ async () => ('run' in over ? over.run : null),+ );+ (service.engineDeps as unknown as { getUserContext: jest.Mock }).getUserContext = jest.fn(+ async () => ({ id: 'u1', tenantId: 't1', role: 'USER' }),+ );+ (service.engineDeps as unknown as { projectAccess: jest.Mock }).projectAccess = jest.fn(+ async () => (project == null ? 'missing' : 'ok'),+ );+ return service;+ }++ it('refuses when the destination project was deleted', async () => {+ const service = makeProjectService({ chatProjectId: 'proj-gone' }, {}, null);+ await expect(service.isScheduleLive('s1', undefined, { policy: true })).resolves.toBe(false);+ });++ it('refuses an unscoped schedule once the owner requires a project', async () => {+ const service = makeProjectService({}, { requireProject: true });+ await expect(service.isScheduleLive('s1', undefined, { policy: true })).resolves.toBe(false);+ });++ /**+ * A pin governs where the NEXT run lands, and the fire path already redirects those.+ * The paused conversation cannot be rebound — `chatProjectId` is excluded from the+ * resume context and the continuation reuses the same conversationId — so refusing+ * here would strand a pending approval over a destination it can never reach.+ */+ it('admits a paused run whose pin moved to a different project', async () => {+ const service = makeProjectService({ chatProjectId: 'proj-old' }, { projectId: 'proj-new' });+ await expect(service.isScheduleLive('s1', undefined, { policy: true })).resolves.toBe(true);+ });++ it('admits a scoped schedule whose project is still owned', async () => {+ const service = makeProjectService({ chatProjectId: 'proj-1' }, {});+ await expect(service.isScheduleLive('s1', undefined, { policy: true })).resolves.toBe(true);+ });++ /**+ * A paused run does NOT block later occurrences (the single-active index covers+ * `started` only), so a fire after a pin move rewrites the schedule row while the+ * paused conversation stays where it was filed. The occurrence's own record is+ * what must be validated.+ */+ it('validates the occurrence record over a schedule row a later fire moved', async () => {+ const service = makeProjectService(+ { chatProjectId: 'proj-new' },+ { projectId: 'proj-new' },+ null,+ { run: { recorded: true, chatProjectId: 'proj-paused' } },+ );+ const access = (service.engineDeps as unknown as { projectAccess: jest.Mock }).projectAccess;++ await expect(+ service.isScheduleLive('s1', undefined, {+ policy: true,+ scheduledFor: '2026-08-17T12:00:00.000Z',+ }),+ ).resolves.toBe(false);+ expect(access).toHaveBeenCalledWith('proj-paused', expect.anything());+ });++ it('admits when the occurrence record itself is still live', async () => {+ const service = makeProjectService(+ { chatProjectId: 'proj-new' },+ {},+ { _id: 'x' },+ {+ run: { recorded: true, chatProjectId: 'proj-paused' },+ },+ );++ await expect(+ service.isScheduleLive('s1', undefined, {+ policy: true,+ scheduledFor: '2026-08-17T12:00:00.000Z',+ }),+ ).resolves.toBe(true);+ });++ /** An absent record is not evidence to stop a run: pre-scope occurrences and rows+ * that are simply gone fall back to the schedule-level resolution. */+ it('falls back to the schedule when the occurrence recorded nothing', async () => {+ const service = makeProjectService({ chatProjectId: 'proj-gone' }, {}, null, { run: null });++ await expect(+ service.isScheduleLive('s1', undefined, {+ policy: true,+ scheduledFor: '2026-08-17T12:00:00.000Z',+ }),+ ).resolves.toBe(false);+ });++ /**+ * A run that DELIBERATELY went unscoped recorded that decision. Falling back to the+ * schedule's current project for it would admit a conversation satisfying no+ * present requirement — the fallback is for UNKNOWN records only.+ */+ it('refuses a recorded-unscoped occurrence once a project became required', async () => {+ const service = makeProjectService(+ { chatProjectId: 'proj-new' },+ { requireProject: true },+ { _id: 'x' },+ {+ run: { recorded: true },+ },+ );++ await expect(+ service.isScheduleLive('s1', undefined, {+ policy: true,+ scheduledFor: '2026-08-17T12:00:00.000Z',+ }),+ ).resolves.toBe(false);+ });++ /** A pre-scope row is UNKNOWN, not unscoped, and keeps today's behaviour. */+ it('falls back for an unrecorded pre-scope occurrence', async () => {+ const service = makeProjectService(+ { chatProjectId: 'proj-live' },+ { requireProject: true },+ { _id: 'x' },+ {+ run: { recorded: false },+ },+ );++ await expect(+ service.isScheduleLive('s1', undefined, {+ policy: true,+ scheduledFor: '2026-08-17T12:00:00.000Z',+ }),+ ).resolves.toBe(true);+ });++ /**+ * The INITIAL start runs the same policy branch, and its run row is reserved before+ * the loopback request is dispatched — so a pin introduced while that request sat+ * queued must not be validated in place of the destination whose envelope was+ * already built. Same call shape as the resume path.+ */+ it('refuses an initial start whose occurrence was reserved unscoped', async () => {+ const service = makeProjectService(+ { chatProjectId: 'proj-pinned' },+ { projectId: 'proj-pinned' },+ { _id: 'x' },+ { run: { recorded: true } },+ );++ await expect(+ service.isScheduleLive('s1', undefined, {+ policy: true,+ scheduledFor: '2026-08-17T12:00:00.000Z',+ }),+ ).resolves.toBe(false);+ });++ it('leaves the non-policy recheck untouched', async () => {+ const service = makeProjectService({ chatProjectId: 'proj-gone' }, {}, null);+ await expect(service.isScheduleLive('s1')).resolves.toBe(true);+ });+ });});describe('quiesceUserSchedules drain wait', () => {@@ -1196,13 +1392,21 @@ describe('global kill switch', () => {});describe('scheduled resume capacity', () => {- function makeResumeService(occupancy: { takenSlots: number[]; unslotted: number }) {+ function makeResumeService(+ occupancy: { takenSlots: number[]; unslotted: number },+ over: {+ scheduleProjectId?: string;+ projectConfig?: Record<string, unknown>;+ project?: unknown;+ } = {},+ ) {const methods = {getScheduleById: jest.fn(async () => ({id: 's1',user: 'user-1',enabled: true,configRevision: 3,+ ...(over.scheduleProjectId != null && { chatProjectId: over.scheduleProjectId }),})),getRoleByName: jest.fn(async () => ({ permissions: { SCHEDULES: { USE: true } } })),getCapacityOccupancy: jest.fn(async () => occupancy),@@ -1228,6 +1432,7 @@ describe('scheduled resume capacity', () => {minIntervalMinutes: 60,autoDisableAfterFailures: 5,fireConcurrency: 1,+ ...(over.projectConfig ?? {}),},},})),@@ -1236,6 +1441,7 @@ describe('scheduled resume capacity', () => {upsertBalance: jest.fn(async () => null),initializeNullBalance: jest.fn(async () => null),resolveAgentFireAccess: jest.fn(async () => 'ok' as const),+ getChatProject: jest.fn(async () => ('project' in over ? over.project : { _id: 'proj-1' })),isUserDeleting: jest.fn(async () => false),enqueueAgentTrigger: jest.fn(async () => undefined),getTriggerDelivery: jest.fn(async () => null),diff --git a/packages/api/src/schedules/service.ts b/packages/api/src/schedules/service.tsindex 6aa16fd256..5d358662ad 100644--- a/packages/api/src/schedules/service.ts+++ b/packages/api/src/schedules/service.ts@@ -1,6 +1,6 @@import { logger, runAsSystem, tenantStorage, isRuntimeDisabled } from '@librechat/data-schemas';import { getRefillEligibilityDate, Permissions, PermissionTypes } from 'librechat-data-provider';-import type { ScheduleMethods, AppConfig, IBalance } from '@librechat/data-schemas';+import type { ScheduleMethods, AppConfig, IBalance, IChatProject } from '@librechat/data-schemas';import type { TCheckpointerConfig } from 'librechat-data-provider';import type { Types } from 'mongoose';import type {@@ -16,6 +16,7 @@ import type { SerializableJobData } from '../stream/interfaces/IJobStore';import type { BalanceUpdateFields } from '../types/balance';import type { GetAppConfigOptions } from '../app/service';import {+ resolveScheduleProjectId,DEFAULT_SCHEDULE_LIMITS,SCHEDULE_FILE_HOLD,hasResumeHandoffInFlight,@@ -161,6 +162,10 @@ export interface SchedulesServiceDeps {agentId: string,user: ScheduleUserContext,) => Promise<'ok' | 'missing' | 'forbidden'>;+ /** Loads a chat project scoped to its owner, or null when it does not exist for+ * them. Chat projects are user-owned, so this is both the existence check and the+ * authorization check. */+ getChatProject: (userId: string, projectId: string) => Promise<IChatProject | null>;/** Whether this user's account deletion has begun. Fail-closed (unknown == true). */isUserDeleting: (userId: string) => Promise<boolean>;/** Shared durable trigger admission from the merged agent-trigger service. */@@ -234,7 +239,7 @@ export interface SchedulesService {isScheduleLive: (scheduleId: string,expectedConfigRevision?: number,- options?: { automatic?: boolean; policy?: boolean },+ options?: { automatic?: boolean; policy?: boolean; scheduledFor?: string | Date },) => Promise<boolean>;/** Soft-deletes an owner's schedule: stop claims, abort active runs, drain, erase. */deleteScheduleForOwner: (scheduleId: string, userId: string) => Promise<ScheduleDeleteResult>;@@ -297,6 +302,7 @@ export function createSchedulesService('upsertBalance','initializeNullBalance','resolveAgentFireAccess',+ 'getChatProject','isUserDeleting','enqueueAgentTrigger','getTriggerDelivery',@@ -354,6 +360,11 @@ export function createSchedulesService(if (config === true) {return DEFAULT_SCHEDULE_LIMITS;}+ // A pinned project is itself a requirement: leaving `requireProject` to be set+ // separately would let `projectId` alone resolve to "optional destination that+ // happens to be forced", and a schedule created before the pin would keep firing+ // with no project at all rather than being stopped for review.+ const projectId = config.projectId?.trim() || undefined;return {enabled: config.use !== false,maxPerUser: config.maxPerUser ?? DEFAULT_SCHEDULE_LIMITS.maxPerUser,@@ -361,6 +372,8 @@ export function createSchedulesService(autoDisableAfterFailures:config.autoDisableAfterFailures ?? DEFAULT_SCHEDULE_LIMITS.autoDisableAfterFailures,fireConcurrency: config.fireConcurrency ?? DEFAULT_SCHEDULE_LIMITS.fireConcurrency,+ requireProject: config.requireProject === true || projectId != null,+ ...(projectId != null && { projectId }),};}@@ -491,6 +504,11 @@ export function createSchedulesService(// VIEW with the manage:agents bypass); shared with the create/update precheck// so the two never diverge.agentAccess: (agentId, user) => deps.resolveAgentFireAccess(agentId, user),+ // Ownership IS existence for a chat project, so one lookup answers both. Failing+ // closed here would auto-disable a schedule on a transient Mongo blip, so a read+ // error propagates instead: the fire fails and is retried like any other error.+ projectAccess: async (projectId, user) =>+ (await deps.getChatProject(user.id, projectId)) == null ? 'missing' : 'ok',resolveFiles: async (fileIds, user) => {// Renew the bounded upload hold at every fire preflight, BEST-EFFORT: the hold// only has to bridge upload -> first consumption (a real send clears the TTL@@ -974,7 +992,7 @@ export function createSchedulesService(async function isScheduleLive(scheduleId: string,expectedConfigRevision?: number,- options?: { automatic?: boolean; policy?: boolean },+ options?: { automatic?: boolean; policy?: boolean; scheduledFor?: string | Date },): Promise<boolean> {if (!scheduleId) {return false;@@ -1027,6 +1045,47 @@ export function createSchedulesService(if (!(await engineDeps.hasScheduleAccess(owner))) {return false;}+ // Project policy belongs HERE rather than in the resume claim: this branch's+ // refusal is already routed through abort-and-settle by both callers, so a+ // policy stop settles the occurrence instead of leaving it at `requires_action`+ // answering 409 to every approval attempt until it expires.+ //+ // Deliberately NARROW. It refuses only where there is no valid destination left:+ // the requirement is on with nothing to satisfy it, or the schedule's own project+ // is gone (which also unset it on the conversation). It does NOT refuse merely+ // because an operator's pin moved to a different project — the paused+ // conversation cannot be rebound (`chatProjectId` is excluded from the resume+ // context, and the continuation reuses the same conversationId), so refusing+ // would strand a pending approval over a pin that only governs where the NEXT+ // run lands, which the fire path already redirects.+ // Prefer the destination THIS OCCURRENCE recorded over the schedule-level value.+ // A paused run does not block later occurrences (the single-active index covers+ // `started` only), so after a pin moves, a subsequent fire rewrites the schedule+ // row while the paused conversation stays where it was — validating the row would+ // then check a project that conversation was never filed under.+ //+ // An ABSENT record falls back to the schedule: a pre-scope occurrence, or one+ // whose row is gone, must never be read as evidence to stop a run.+ const occurrence =+ options?.scheduledFor != null+ ? await methods.getScheduleRunProject(scheduleId, options.scheduledFor)+ : null;+ // `recorded`, not the id: an occurrence that deliberately ran unscoped recorded a+ // null, and validating the schedule's CURRENT value for it would admit a+ // conversation that satisfies no present requirement. Only an unknown record — a+ // row from before the field, or none at all — falls back.+ const effectiveProject = occurrence?.recorded+ ? occurrence.chatProjectId+ : resolveScheduleProjectId(limits, schedule.chatProjectId);+ if (limits.requireProject && effectiveProject == null) {+ return false;+ }+ if (+ effectiveProject != null &&+ (await engineDeps.projectAccess(effectiveProject, owner)) !== 'ok'+ ) {+ return false;+ }}return true;}@@ -1064,6 +1123,10 @@ export function createSchedulesService(if (!ownerLimits.enabled || globallyDisabled || !hasAccess) {return { conflict: 'inactive' };}+ // Project policy is NOT re-checked here. It lives in isScheduleLive's `policy`+ // branch, which both entry points consult first and whose refusal aborts and+ // settles the occurrence; a second copy here would answer a bare 409 and strand+ // the run at `requires_action` instead.// FINAL schedule-side admission fence. Everything above is asynchronous and an// owner edit/disable can land while it runs. Claim the schedule document under// the expected config generation now, carry this lease through the approval CAS,diff --git a/packages/api/src/schedules/types.ts b/packages/api/src/schedules/types.tsindex 52c5febb42..16978a2697 100644--- a/packages/api/src/schedules/types.ts+++ b/packages/api/src/schedules/types.ts@@ -15,6 +15,13 @@ export interface ScheduleLimits {minIntervalMinutes: number;autoDisableAfterFailures: number;fireConcurrency: number;+ /** Every schedule must be filed under a chat project. A pinned `projectId`+ * implies this, so callers only ever have to read one flag. */+ requireProject: boolean;+ /** Operator-pinned destination project. When set it OVERRIDES whatever the row+ * stores, at write time and at fire time alike — the pin is a policy about where+ * scheduled runs land, and a stored id from before the pin must not outrank it. */+ projectId?: string;}export const DEFAULT_SCHEDULE_LIMITS: ScheduleLimits = {@@ -23,8 +30,23 @@ export const DEFAULT_SCHEDULE_LIMITS: ScheduleLimits = {minIntervalMinutes: 60,autoDisableAfterFailures: 5,fireConcurrency: 5,+ requireProject: false,};+/**+ * The project a schedule's runs must land in under the CURRENT policy: an operator+ * pin outranks the stored choice, otherwise the owner's own selection stands.+ * Single source of truth for the write handlers, the fire path, and the wire+ * projection, so the form, the precheck, and the dispatched conversation can never+ * disagree about the destination.+ */+export function resolveScheduleProjectId(+ limits: Pick<ScheduleLimits, 'projectId'>,+ stored?: string | null,+): string | undefined {+ return limits.projectId ?? stored ?? undefined;+}+export interface ScheduleUserContext {id: string;tenantId?: string;@@ -160,6 +182,13 @@ export interface ScheduleEngineDeps {agentId: string,user: ScheduleUserContext,) => Promise<'ok' | 'missing' | 'forbidden'>;+ /**+ * Whether the owner still owns the schedule's destination chat project. Projects+ * are user-owned, so 'missing' covers both deletion and a pinned id belonging to+ * someone else — the fire path treats them identically because the observable+ * outcome is the same: the conversation would be filed nowhere.+ */+ projectAccess: (projectId: string, user: ScheduleUserContext) => Promise<'ok' | 'missing'>;/** Whether the owning user's current role still grants SCHEDULES access. */hasScheduleAccess: (user: ScheduleUserContext) => Promise<boolean>;/** Re-resolves stored file_ids to attachment payloads; missing files are simply absent. */@@ -274,6 +303,8 @@ export interface FireResult {| 'user_missing'| 'user_deleting'| 'permission_revoked'+ | 'project_deleted'+ | 'project_required'| 'rate_limited'| 'disabled';error?: string;diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 9384f8ff1c..5aa86d4039 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1573,6 +1573,15 @@ export const interfaceSchema = zminIntervalMinutes: z.number().int().min(1).optional(),autoDisableAfterFailures: z.number().int().min(1).optional(),fireConcurrency: z.number().int().min(1).optional(),+ /** Refuse schedules that are not filed under a chat project. Enforced on+ * create/update AND at every fire, so raising it later stops schedules+ * that predate the policy instead of grandfathering them. */+ requireProject: z.boolean().optional(),+ /** Pins every scheduled run to ONE chat project, ignoring any client+ * choice. Implies `requireProject`. The project must belong to the+ * schedule's owner, so a deployment-wide value only makes sense with a+ * per-user/per-role config override. */+ projectId: z.string().trim().min(1).optional(),}),]).optional(),diff --git a/packages/data-provider/src/types/schedules.ts b/packages/data-provider/src/types/schedules.tsindex 9e50b6ac83..0094078239 100644--- a/packages/data-provider/src/types/schedules.ts+++ b/packages/data-provider/src/types/schedules.ts@@ -11,7 +11,9 @@ export type ScheduleDisabledReason =| 'agent_deleted'| 'invalid_schedule'| 'permission_revoked'- | 'insufficient_balance';+ | 'insufficient_balance'+ | 'project_deleted'+ | 'project_required';export type ScheduleRunStatus =| 'started'@@ -47,6 +49,12 @@ export const createSchedulePayloadSchema = z.object({.max(10).transform((ids) => Array.from(new Set(ids))).optional(),+ /**+ * Chat project each run's conversation is filed under. `null` clears the scope.+ * Ownership is checked server-side at write time and again at every fire, so a+ * deleted project disables the schedule instead of silently filing runs loose.+ */+ chatProjectId: z.string().trim().min(1).nullable().optional(),enabled: z.boolean().default(true),/*** Client-generated key making creation idempotent across retries. Creation commits@@ -93,6 +101,7 @@ export type TSchedule = {timezone: string;target: ScheduleTarget;file_ids?: string[];+ chatProjectId?: string | null;enabled: boolean;disabledReason?: ScheduleDisabledReason;nextRunAt?: string;@@ -115,9 +124,21 @@ export type TScheduleRun = {durationMs?: number;};+/** Server-resolved policy the dialog must mirror. Sourced from the same+ * per-principal `interface.schedules` resolution the write handlers and the fire+ * path enforce, so the form can never offer a choice the server would refuse. */+export type TScheduleLimits = {+ maxPerUser: number;+ /** Every schedule must be filed under a chat project. */+ requireProject: boolean;+ /** Operator-pinned destination project; when set it is the ONLY destination and+ * the client must not offer a picker. */+ projectId?: string;+};+export type TSchedulesResponse = {schedules: TSchedule[];- limits: { maxPerUser: number };+ limits: TScheduleLimits;};export type TScheduleRunNowResponse = {diff --git a/packages/data-schemas/src/methods/schedule.methods.spec.ts b/packages/data-schemas/src/methods/schedule.methods.spec.tsindex feab6e8c6b..033406f4ba 100644--- a/packages/data-schemas/src/methods/schedule.methods.spec.ts+++ b/packages/data-schemas/src/methods/schedule.methods.spec.ts@@ -221,6 +221,56 @@ describe('recordSkippedRun duplicate-occurrence guard', () => {});});+describe('getScheduleRunProject (occurrence scope, recorded vs unknown)', () => {+ /**+ * The whole distinction rests on a stored `null` surviving as a PRESENT key while a+ * never-written field stays absent. Asserted against real Mongo rather than assumed:+ * if that ever stopped holding, a deliberately unscoped run would silently start+ * being validated against the schedule's current project instead.+ */+ it('reports a recorded null apart from a field that was never written', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const scoped = new Date('2026-07-20T12:00:00Z');+ const unscoped = new Date('2026-07-21T12:00:00Z');++ await methods.reserveStartedRun(+ runData(schedule, { scheduledFor: scoped, chatProjectId: 'proj-1' }),+ );+ await methods.recordRunOutcome({+ scheduleId: schedule.id,+ scheduledFor: scoped,+ status: 'success',+ autoDisableAfterFailures: 5,+ });+ await methods.reserveStartedRun(+ runData(schedule, { scheduledFor: unscoped, chatProjectId: null }),+ );++ expect(await methods.getScheduleRunProject(schedule.id, scoped)).toEqual({+ recorded: true,+ chatProjectId: 'proj-1',+ });+ // Recorded, and deliberately without a project — NOT a fallback case.+ expect(await methods.getScheduleRunProject(schedule.id, unscoped)).toEqual({ recorded: true });+ });++ it('reports a pre-scope row as unrecorded, and a missing row as null', async () => {+ const schedule = await methods.createSchedule(scheduleData());+ const legacy = new Date('2026-07-22T12:00:00Z');+ await methods.reserveStartedRun(runData(schedule, { scheduledFor: legacy }));+ // Strip the key the way a row written before this field looks on disk.+ await mongoose.models.ScheduleRun.collection.updateOne(+ { scheduleId: schedule.id, scheduledFor: legacy },+ { $unset: { chatProjectId: '' } },+ );++ expect(await methods.getScheduleRunProject(schedule.id, legacy)).toEqual({ recorded: false });+ expect(+ await methods.getScheduleRunProject(schedule.id, new Date('2030-01-01T00:00:00Z')),+ ).toBeNull();+ });+});+describe('settledAt retention marker', () => {it('stamps settledAt on terminal outcomes but never on a pause', async () => {const schedule = await methods.createSchedule(scheduleData());diff --git a/packages/data-schemas/src/methods/schedule.ts b/packages/data-schemas/src/methods/schedule.tsindex 773c5fabda..8433b0a5a9 100644--- a/packages/data-schemas/src/methods/schedule.ts+++ b/packages/data-schemas/src/methods/schedule.ts@@ -222,6 +222,18 @@ export type ScheduleMethods = {counterGuard?: Record<string, unknown>,) => Promise<void>;insertScheduleRun: (data: Partial<IScheduleRun>) => Promise<IScheduleRun | null>;+ /** Converges the schedule row on the destination a fire resolved; claim-token+ * fenced, and never bumps configRevision (this is not an owner edit). */+ persistResolvedProject: (+ id: string,+ chatProjectId: string | undefined,+ expectedClaimToken?: string,+ ) => Promise<void>;+ /** The destination one occurrence used; null when the row is absent. */+ getScheduleRunProject: (+ scheduleId: string,+ scheduledFor: string | Date,+ ) => Promise<{ recorded: boolean; chatProjectId?: string } | null>;reserveStartedRun: (data: Partial<IScheduleRun>) => Promise<StartedRunReservation>;getCapacityOccupancy: () => Promise<{ takenSlots: number[]; unslotted: number }>;requestRunAbort: (@@ -789,6 +801,59 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): Sche});}+ /**+ * Converges the row on the destination a fire actually RESOLVED, so the stored id+ * never lies about where this schedule's conversations are going.+ *+ * An operator pin outranks the stored id at fire time, and the wire projection+ * already reports the pin — but the row kept its old value, so a paused occurrence+ * could only be re-validated against a project its conversation was never filed+ * under. Claim-token fenced like every other worker-side write, and deliberately+ * WITHOUT a configRevision bump: this is the server reconciling itself to policy,+ * not an owner edit, and bumping would fence an in-flight occurrence off its own run.+ */+ /**+ * The destination one OCCURRENCE actually used, for re-validating a paused run.+ *+ * `recorded` is the load-bearing part. A reservation ALWAYS writes the field (null+ * when deliberately unscoped), so a row missing the key is one written before this+ * existed — "unknown", not "no project". Callers fall back to the schedule-level+ * resolution only for unknown, and treat a recorded null as the genuinely unscoped+ * occurrence it is. Returns null when there is no row at all.+ */+ async function getScheduleRunProject(+ scheduleId: string,+ scheduledFor: string | Date,+ ): Promise<{ recorded: boolean; chatProjectId?: string } | null> {+ const run = await ScheduleRun()+ .findOne({ scheduleId, scheduledFor: new Date(scheduledFor) })+ .select('chatProjectId')+ .lean<{ chatProjectId?: string | null } | null>();+ if (run == null) {+ return null;+ }+ // Key PRESENCE, not truthiness: `null` is a recorded decision, absent is not.+ const recorded = Object.prototype.hasOwnProperty.call(run, 'chatProjectId');+ return recorded && run.chatProjectId != null+ ? { recorded, chatProjectId: run.chatProjectId }+ : { recorded };+ }++ async function persistResolvedProject(+ id: string,+ chatProjectId: string | undefined,+ expectedClaimToken?: string,+ ): Promise<void> {+ const filter: Record<string, unknown> = { id };+ if (expectedClaimToken !== undefined) {+ filter.claimToken = expectedClaimToken;+ }+ await Schedule().updateOne(+ filter,+ chatProjectId == null ? { $unset: { chatProjectId: 1 } } : { $set: { chatProjectId } },+ );+ }+/*** Inserts the run row BEFORE firing. The unique {scheduleId, scheduledFor}* index makes this the durable idempotency claim: null means this occurrence@@ -2031,6 +2096,8 @@ export function createScheduleMethods(mongoose: typeof import('mongoose')): SchereserveStartedRun,getCapacityOccupancy,requestRunAbort,+ persistResolvedProject,+ getScheduleRunProject,getScheduleRunAbortState,markRunResumeClaimed,releaseRunResumeClaim,diff --git a/packages/data-schemas/src/schema/schedule.ts b/packages/data-schemas/src/schema/schedule.tsindex 4fabb22065..6e1daf69eb 100644--- a/packages/data-schemas/src/schema/schedule.ts+++ b/packages/data-schemas/src/schema/schedule.ts@@ -52,6 +52,9 @@ const scheduleSchema: Schema<IScheduleDocument> = new Schema(default: 'new',required: true,},+ chatProjectId: {+ type: String,+ },file_ids: {type: [String],default: undefined,@@ -76,6 +79,8 @@ const scheduleSchema: Schema<IScheduleDocument> = new Schema('invalid_schedule','permission_revoked','insufficient_balance',+ 'project_deleted',+ 'project_required',],},nextRunAt: {diff --git a/packages/data-schemas/src/schema/scheduleRun.ts b/packages/data-schemas/src/schema/scheduleRun.tsindex 6e278ae864..4a1147db34 100644--- a/packages/data-schemas/src/schema/scheduleRun.ts+++ b/packages/data-schemas/src/schema/scheduleRun.ts@@ -35,6 +35,9 @@ const scheduleRunSchema: Schema<IScheduleRunDocument> = new Schema(deliveryKey: {type: String,},+ chatProjectId: {+ type: String,+ },/** Fresh while a RESUME of this paused run is mid-flight; a re-pause hand-off's* writes are still landing, so quiesce must not settle on the paused job state.* Cleared by the pause record (the hand-off completion) or aged out. */diff --git a/packages/data-schemas/src/types/schedule.ts b/packages/data-schemas/src/types/schedule.tsindex 531caed161..0c561e6b70 100644--- a/packages/data-schemas/src/types/schedule.ts+++ b/packages/data-schemas/src/types/schedule.ts@@ -16,6 +16,9 @@ export interface ISchedule {cadence: TScheduleCadence;timezone: string;target: 'new';+ /** Chat project every run's conversation is filed under. Re-validated at each+ * fire; a pinned operator project (interface.schedules.projectId) overrides it. */+ chatProjectId?: string;file_ids?: string[];tools?: string[];cron?: string;@@ -88,6 +91,15 @@ export interface IScheduleRun {* state instead of orphan-settling a jobless run that is merely deferred (Retry-After)* or that dead-lettered before a generation ever started. */deliveryKey?: string;+ /** The destination project THIS occurrence actually used, recorded at reservation+ * because the schedule-level value can move on (an operator pin redirects later+ * fires, and a paused run does not block them), leaving the row describing a project+ * this occurrence's conversation was never filed under.+ *+ * ALWAYS written, `null` for a deliberately unscoped occurrence: an absent key means+ * "this row predates the field", which is a different thing from "this run had no+ * project" and must not be validated as if it were. */+ chatProjectId?: string | null;droppedFileIds?: string[];durationMs?: number;bookkept?: boolean;