Add URL-based change review and selective change-set rollback

This commit is contained in:
Ruslan Bakiev
2026-02-20 19:04:49 +07:00
parent b9ba5778f5
commit 129daa31d7
5 changed files with 593 additions and 88 deletions

View File

@@ -18,12 +18,13 @@ import archiveChatConversationMutation from "./graphql/operations/archive-chat-c
import toggleContactPinMutation from "./graphql/operations/toggle-contact-pin.graphql?raw";
import confirmLatestChangeSetMutation from "./graphql/operations/confirm-latest-change-set.graphql?raw";
import rollbackLatestChangeSetMutation from "./graphql/operations/rollback-latest-change-set.graphql?raw";
import rollbackChangeSetItemsMutation from "./graphql/operations/rollback-change-set-items.graphql?raw";
import { Chat as AiChat } from "@ai-sdk/vue";
import { DefaultChatTransport, isTextUIPart, type UIMessage } from "ai";
type TabId = "communications" | "documents";
type CalendarView = "day" | "week" | "month" | "year" | "agenda";
type SortMode = "name" | "lastContact";
type PeopleLeftMode = "contacts" | "calendar";
type PeopleLeftMode = "contacts" | "calendar" | "changes";
type PeopleSortMode = "name" | "lastContact" | "company" | "country";
type FeedCard = {
@@ -321,11 +322,14 @@ type PilotMessage = {
changeStatus?: "pending" | "confirmed" | "rolled_back" | null;
changeSummary?: string | null;
changeItems?: Array<{
id: string;
entity: string;
entityId?: string | null;
action: string;
title: string;
before: string;
after: string;
rolledBack?: boolean;
}> | null;
createdAt?: string;
_live?: boolean;
@@ -1189,8 +1193,13 @@ watchEffect(() => {
livePilotAssistantText.value = textPart?.text ?? "";
});
const changePanelOpen = ref(true);
const changeActionBusy = ref(false);
const activeChangeSetId = ref("");
const activeChangeStep = ref(0);
const changeSelectionByItemId = ref<Record<string, boolean>>({});
const focusedCalendarEventId = ref("");
const uiPathSyncLocked = ref(false);
let popstateHandler: (() => void) | null = null;
const pilotHeaderPhrases = [
"Every step moves you forward",
"Focus first, results follow",
@@ -1211,6 +1220,185 @@ const latestChangeMessage = computed(() => {
);
});
const activeChangeMessage = computed(() => {
const targetId = activeChangeSetId.value.trim();
if (!targetId) return latestChangeMessage.value;
return (
[...pilotMessages.value]
.reverse()
.find((m) => m.role === "assistant" && m.changeSetId === targetId) ?? null
);
});
const activeChangeItems = computed(() => activeChangeMessage.value?.changeItems ?? []);
const activeChangeItem = computed(() => {
const items = activeChangeItems.value;
if (!items.length) return null;
const idx = Math.max(0, Math.min(activeChangeStep.value, items.length - 1));
return items[idx] ?? null;
});
const selectedRollbackItemIds = computed(() =>
activeChangeItems.value
.filter((item) => !item.rolledBack && changeSelectionByItemId.value[item.id])
.map((item) => item.id),
);
const selectedRollbackCount = computed(() => selectedRollbackItemIds.value.length);
function toggleAllChangeItems(checked: boolean) {
const next: Record<string, boolean> = {};
for (const item of activeChangeItems.value) {
next[item.id] = item.rolledBack ? false : checked;
}
changeSelectionByItemId.value = next;
}
function calendarCursorToken(date: Date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, "0");
return `${y}-${m}`;
}
function parseCalendarCursorToken(token: string | null | undefined) {
const text = String(token ?? "").trim();
const m = text.match(/^(\d{4})-(\d{2})$/);
if (!m) return null;
const year = Number(m[1]);
const month = Number(m[2]);
if (!Number.isFinite(year) || !Number.isFinite(month) || month < 1 || month > 12) return null;
return new Date(year, month - 1, 1);
}
function normalizedConversationId() {
return (selectedChatId.value || authMe.value?.conversation.id || "pilot").trim();
}
function currentUiPath() {
if (selectedTab.value !== "communications") {
return `/chat/${encodeURIComponent(normalizedConversationId())}`;
}
if (peopleLeftMode.value === "changes" && activeChangeSetId.value.trim()) {
const step = Math.max(1, activeChangeStep.value + 1);
return `/changes/${encodeURIComponent(activeChangeSetId.value.trim())}/step/${step}`;
}
if (peopleLeftMode.value === "calendar") {
if (focusedCalendarEventId.value.trim()) {
return `/calendar/event/${encodeURIComponent(focusedCalendarEventId.value.trim())}`;
}
return `/calendar/${encodeURIComponent(calendarView.value)}/${encodeURIComponent(calendarCursorToken(calendarCursor.value))}`;
}
return `/chat/${encodeURIComponent(normalizedConversationId())}`;
}
function syncPathFromUi(push = false) {
if (process.server) return;
const nextPath = currentUiPath();
const currentPath = window.location.pathname;
if (nextPath === currentPath) return;
if (push) {
window.history.pushState({}, "", nextPath);
} else {
window.history.replaceState({}, "", nextPath);
}
}
function ensureChangeSelectionSeeded(message: PilotMessage | null | undefined) {
if (!message?.changeItems?.length) {
changeSelectionByItemId.value = {};
return;
}
const next: Record<string, boolean> = {};
for (const item of message.changeItems) {
const prev = changeSelectionByItemId.value[item.id];
next[item.id] = typeof prev === "boolean" ? prev : !item.rolledBack;
}
changeSelectionByItemId.value = next;
}
function setPeopleLeftMode(mode: PeopleLeftMode, push = false) {
selectedTab.value = "communications";
peopleLeftMode.value = mode;
if (mode !== "changes") {
activeChangeSetId.value = "";
activeChangeStep.value = 0;
}
focusedCalendarEventId.value = "";
syncPathFromUi(push);
}
function openChangeReview(changeSetId: string, step = 0, push = true) {
const targetId = String(changeSetId ?? "").trim();
if (!targetId) return;
selectedTab.value = "communications";
peopleLeftMode.value = "changes";
activeChangeSetId.value = targetId;
const items = activeChangeMessage.value?.changeItems ?? [];
activeChangeStep.value = items.length ? Math.max(0, Math.min(step, items.length - 1)) : 0;
ensureChangeSelectionSeeded(activeChangeMessage.value);
syncPathFromUi(push);
}
function applyPathToUi(pathname: string) {
const path = String(pathname || "/").trim() || "/";
const calendarEventMatch = path.match(/^\/calendar\/event\/([^/]+)\/?$/i);
if (calendarEventMatch) {
const rawEventId = decodeURIComponent(calendarEventMatch[1] ?? "").trim();
selectedTab.value = "communications";
peopleLeftMode.value = "calendar";
const event = sortedEvents.value.find((x) => x.id === rawEventId);
if (event) {
pickDate(event.start.slice(0, 10));
}
focusedCalendarEventId.value = rawEventId;
activeChangeSetId.value = "";
activeChangeStep.value = 0;
return;
}
const calendarMatch = path.match(/^\/calendar\/([^/]+)\/([^/]+)\/?$/i);
if (calendarMatch) {
const rawView = decodeURIComponent(calendarMatch[1] ?? "").trim();
const rawCursor = decodeURIComponent(calendarMatch[2] ?? "").trim();
const view = (["day", "week", "month", "year", "agenda"] as CalendarView[]).includes(rawView as CalendarView)
? (rawView as CalendarView)
: "month";
const cursor = parseCalendarCursorToken(rawCursor);
selectedTab.value = "communications";
peopleLeftMode.value = "calendar";
focusedCalendarEventId.value = "";
calendarView.value = view;
if (cursor) {
calendarCursor.value = cursor;
selectedDateKey.value = dayKey(cursor);
}
activeChangeSetId.value = "";
activeChangeStep.value = 0;
return;
}
const changesMatch = path.match(/^\/changes\/([^/]+)(?:\/step\/(\d+))?\/?$/i);
if (changesMatch) {
const rawId = decodeURIComponent(changesMatch[1] ?? "").trim();
const rawStep = Number(changesMatch[2] ?? "1");
selectedTab.value = "communications";
peopleLeftMode.value = "changes";
focusedCalendarEventId.value = "";
activeChangeSetId.value = rawId;
activeChangeStep.value = Number.isFinite(rawStep) && rawStep > 0 ? rawStep - 1 : 0;
ensureChangeSelectionSeeded(activeChangeMessage.value);
return;
}
selectedTab.value = "communications";
peopleLeftMode.value = "contacts";
focusedCalendarEventId.value = "";
activeChangeSetId.value = "";
activeChangeStep.value = 0;
}
async function confirmLatestChangeSet() {
if (changeActionBusy.value || !latestChangeMessage.value?.changeSetId) return;
changeActionBusy.value = true;
@@ -1227,12 +1415,77 @@ async function rollbackLatestChangeSet() {
changeActionBusy.value = true;
try {
await gqlFetch<{ rollbackLatestChangeSet: { ok: boolean } }>(rollbackLatestChangeSetMutation);
await Promise.all([loadPilotMessages(), refreshCrmData()]);
await Promise.all([loadPilotMessages(), refreshCrmData(), loadChatConversations()]);
if (peopleLeftMode.value === "changes") {
activeChangeSetId.value = "";
activeChangeStep.value = 0;
setPeopleLeftMode("contacts");
}
} finally {
changeActionBusy.value = false;
}
}
async function rollbackSelectedChangeItems() {
const targetChangeSetId = activeChangeMessage.value?.changeSetId?.trim() || activeChangeSetId.value.trim();
const itemIds = selectedRollbackItemIds.value;
if (changeActionBusy.value || !targetChangeSetId || itemIds.length === 0) return;
changeActionBusy.value = true;
try {
await gqlFetch<{ rollbackChangeSetItems: { ok: boolean } }>(rollbackChangeSetItemsMutation, {
changeSetId: targetChangeSetId,
itemIds,
});
await Promise.all([loadPilotMessages(), refreshCrmData(), loadChatConversations()]);
ensureChangeSelectionSeeded(activeChangeMessage.value);
} finally {
changeActionBusy.value = false;
}
}
function goToChangeStep(step: number) {
const items = activeChangeItems.value;
if (!items.length) return;
activeChangeStep.value = Math.max(0, Math.min(step, items.length - 1));
syncPathFromUi(true);
}
function openChangeItemTarget(item: NonNullable<PilotMessage["changeItems"]>[number]) {
if (!item) return;
if (item.entity === "calendar_event" && item.entityId) {
const event = sortedEvents.value.find((x) => x.id === item.entityId);
setPeopleLeftMode("calendar", true);
if (event) {
pickDate(event.start.slice(0, 10));
}
focusedCalendarEventId.value = item.entityId;
syncPathFromUi(true);
return;
}
if (item.entity === "contact_note" && item.entityId) {
const contact = contacts.value.find((x) => x.id === item.entityId);
setPeopleLeftMode("contacts", true);
if (contact) selectedContactId.value = contact.id;
syncPathFromUi(true);
return;
}
setPeopleLeftMode("contacts", true);
}
watch(
() => activeChangeMessage.value?.changeSetId,
() => {
if (peopleLeftMode.value !== "changes") return;
ensureChangeSelectionSeeded(activeChangeMessage.value);
const maxIndex = Math.max(0, (activeChangeItems.value.length || 1) - 1);
if (activeChangeStep.value > maxIndex) activeChangeStep.value = maxIndex;
},
);
if (process.server) {
await bootstrapSession();
}
@@ -1247,6 +1500,23 @@ onMounted(() => {
lifecycleNowMs.value = Date.now();
}, 15000);
uiPathSyncLocked.value = true;
try {
applyPathToUi(window.location.pathname);
} finally {
uiPathSyncLocked.value = false;
}
syncPathFromUi(false);
popstateHandler = () => {
uiPathSyncLocked.value = true;
try {
applyPathToUi(window.location.pathname);
} finally {
uiPathSyncLocked.value = false;
}
};
window.addEventListener("popstate", popstateHandler);
if (!authResolved.value) {
void bootstrapSession().finally(() => {
if (authMe.value) startPilotBackgroundPolling();
@@ -1274,6 +1544,10 @@ onBeforeUnmount(() => {
pilotRecorderStream = null;
}
stopPilotBackgroundPolling();
if (popstateHandler) {
window.removeEventListener("popstate", popstateHandler);
popstateHandler = null;
}
if (lifecycleClock) {
clearInterval(lifecycleClock);
lifecycleClock = null;
@@ -1401,6 +1675,7 @@ const yearMonths = computed(() => {
const selectedDayEvents = computed(() => getEventsByDate(selectedDateKey.value));
function shiftCalendar(step: number) {
focusedCalendarEventId.value = "";
if (calendarView.value === "year") {
const next = new Date(calendarCursor.value);
next.setFullYear(next.getFullYear() + step);
@@ -1427,24 +1702,35 @@ function shiftCalendar(step: number) {
}
function setToday() {
focusedCalendarEventId.value = "";
const now = new Date();
selectedDateKey.value = dayKey(now);
calendarCursor.value = new Date(now.getFullYear(), now.getMonth(), 1);
}
function pickDate(key: string) {
focusedCalendarEventId.value = "";
selectedDateKey.value = key;
const d = new Date(`${key}T00:00:00`);
calendarCursor.value = new Date(d.getFullYear(), d.getMonth(), 1);
}
function openYearMonth(monthIndex: number) {
focusedCalendarEventId.value = "";
const year = calendarCursor.value.getFullYear();
calendarCursor.value = new Date(year, monthIndex, 1);
selectedDateKey.value = dayKey(new Date(year, monthIndex, 1));
calendarView.value = "month";
}
watch(
() => [selectedTab.value, peopleLeftMode.value, selectedChatId.value, calendarView.value, calendarCursorToken(calendarCursor.value), activeChangeSetId.value, activeChangeStep.value],
() => {
if (process.server || uiPathSyncLocked.value) return;
syncPathFromUi(false);
},
);
const contactSearch = ref("");
const selectedCountry = ref("All");
const selectedLocation = ref("All");
@@ -2325,8 +2611,7 @@ function pushPilotNote(text: string) {
}
function openCommunicationThread(contact: string) {
selectedTab.value = "communications";
peopleLeftMode.value = "contacts";
setPeopleLeftMode("contacts", true);
selectedDealStepsExpanded.value = false;
const linkedContact = contacts.value.find((item) => item.name === contact);
if (linkedContact) {
@@ -2350,18 +2635,20 @@ function openDealThread(deal: Deal) {
function openThreadFromCalendarItem(event: CalendarEvent) {
if (!event.contact?.trim()) {
selectedTab.value = "communications";
peopleLeftMode.value = "calendar";
setPeopleLeftMode("calendar", true);
pickDate(event.start.slice(0, 10));
focusedCalendarEventId.value = event.id;
syncPathFromUi(true);
return;
}
openCommunicationThread(event.contact);
}
function openEventFromContact(event: CalendarEvent) {
selectedTab.value = "communications";
peopleLeftMode.value = "calendar";
setPeopleLeftMode("calendar", true);
pickDate(event.start.slice(0, 10));
focusedCalendarEventId.value = event.id;
syncPathFromUi(true);
}
function openMessageFromContact(channel: CommItem["channel"]) {
@@ -2537,8 +2824,7 @@ async function executeFeedAction(card: FeedCard) {
selectedDateKey.value = dayKey(start);
calendarCursor.value = new Date(start.getFullYear(), start.getMonth(), 1);
selectedTab.value = "communications";
peopleLeftMode.value = "calendar";
setPeopleLeftMode("calendar", true);
return `Event created: Follow-up · ${formatDay(start.toISOString())} ${formatTime(start.toISOString())} · ${card.contact}`;
}
@@ -2762,6 +3048,18 @@ async function decideFeedCard(card: FeedCard, decision: "accepted" | "rejected")
{{ row.entity }}: {{ row.count }}
</span>
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<button
v-if="message.changeSetId"
class="btn btn-xs btn-outline"
@click="openChangeReview(message.changeSetId, 0, true)"
>
Review Changes
</button>
<span class="text-[10px] uppercase tracking-wide text-amber-100/80">
status: {{ message.changeStatus || "pending" }}
</span>
</div>
</div>
<div v-else class="pilot-message-text">
@@ -2824,52 +3122,6 @@ async function decideFeedCard(card: FeedCard, decision: "accepted" | "rejected")
</div>
</div>
<div
v-if="latestChangeMessage && latestChangeMessage.changeItems && latestChangeMessage.changeItems.length"
class="mb-2 rounded-xl border border-amber-300/40 bg-amber-500/10 p-2"
>
<div class="flex items-center justify-between gap-2">
<div>
<p class="text-xs font-semibold text-amber-100">Detected changes</p>
<p class="text-[11px] text-amber-100/80">
{{ latestChangeMessage.changeSummary || `Changed: ${latestChangeMessage.changeItems.length}` }}
· status: {{ latestChangeMessage.changeStatus || "pending" }}
</p>
</div>
<div class="flex items-center gap-1">
<button class="btn btn-xs btn-ghost" @click="changePanelOpen = !changePanelOpen">
{{ changePanelOpen ? "Hide" : "Show" }}
</button>
<button
class="btn btn-xs"
:disabled="changeActionBusy || latestChangeMessage.changeStatus === 'confirmed'"
@click="confirmLatestChangeSet"
>
Keep
</button>
<button
class="btn btn-xs btn-outline"
:disabled="changeActionBusy || latestChangeMessage.changeStatus === 'rolled_back'"
@click="rollbackLatestChangeSet"
>
Rollback
</button>
</div>
</div>
<div v-if="changePanelOpen" class="mt-2 max-h-44 space-y-2 overflow-y-auto pr-1">
<div
v-for="(item, idx) in latestChangeMessage.changeItems"
:key="`change-item-${idx}`"
class="rounded-lg border border-amber-200/30 bg-[#1e2230] p-2"
>
<p class="text-[11px] font-semibold text-white/90">{{ item.title }}</p>
<p class="text-[11px] text-white/60">{{ item.entity }} · {{ item.action }}</p>
<p v-if="item.before" class="mt-1 text-[11px] text-red-300/80">- {{ item.before }}</p>
<p v-if="item.after" class="text-[11px] text-emerald-300/80">+ {{ item.after }}</p>
</div>
</div>
</div>
<div class="pilot-input-wrap">
<div class="pilot-input-shell">
<textarea
@@ -2926,7 +3178,7 @@ async function decideFeedCard(card: FeedCard, decision: "accepted" | "rejected")
? 'btn-ghost border border-base-300 bg-base-200/70 text-base-content'
: 'btn-ghost border border-transparent text-base-content/65 hover:border-base-300/70 hover:text-base-content'
"
@click="peopleLeftMode = 'contacts'"
@click="setPeopleLeftMode('contacts', true)"
>
Contacts
</button>
@@ -2937,7 +3189,7 @@ async function decideFeedCard(card: FeedCard, decision: "accepted" | "rejected")
? 'btn-ghost border border-base-300 bg-base-200/70 text-base-content'
: 'btn-ghost border border-transparent text-base-content/65 hover:border-base-300/70 hover:text-base-content'
"
@click="peopleLeftMode = 'calendar'"
@click="setPeopleLeftMode('calendar', true)"
>
Calendar
</button>
@@ -2966,7 +3218,117 @@ async function decideFeedCard(card: FeedCard, decision: "accepted" | "rejected")
class="min-h-0 flex-1"
:class="selectedTab === 'communications' && peopleLeftMode === 'contacts' ? 'px-0 pt-0 pb-0' : 'px-3 pt-3 pb-0 md:px-4 md:pt-4 md:pb-0'"
>
<section v-if="selectedTab === 'communications' && peopleLeftMode === 'calendar'" class="flex h-full min-h-0 flex-col gap-3">
<section v-if="selectedTab === 'communications' && peopleLeftMode === 'changes'" class="flex h-full min-h-0 flex-col gap-3">
<div class="rounded-xl border border-amber-300/35 bg-amber-500/10 p-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<div>
<p class="text-sm font-semibold text-amber-100">Change Review</p>
<p class="text-xs text-amber-100/80">
{{ activeChangeMessage?.changeSummary || "No changes selected" }}
<span v-if="activeChangeMessage?.changeStatus"> · status: {{ activeChangeMessage.changeStatus }}</span>
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<button
class="btn btn-xs btn-outline"
:disabled="!activeChangeItems.length"
@click="toggleAllChangeItems(true)"
>
Select all
</button>
<button
class="btn btn-xs btn-outline"
:disabled="!activeChangeItems.length"
@click="toggleAllChangeItems(false)"
>
Clear
</button>
<button
class="btn btn-xs"
:disabled="changeActionBusy || selectedRollbackCount === 0"
@click="rollbackSelectedChangeItems"
>
Rollback selected ({{ selectedRollbackCount }})
</button>
<button
class="btn btn-xs btn-ghost"
:disabled="changeActionBusy || !latestChangeMessage?.changeSetId || activeChangeMessage?.changeSetId !== latestChangeMessage?.changeSetId"
@click="confirmLatestChangeSet"
>
Keep as is
</button>
<button
class="btn btn-xs btn-outline"
:disabled="changeActionBusy || !latestChangeMessage?.changeSetId || activeChangeMessage?.changeSetId !== latestChangeMessage?.changeSetId"
@click="rollbackLatestChangeSet"
>
Rollback all
</button>
<button class="btn btn-xs btn-ghost" @click="setPeopleLeftMode('contacts', true)">Back to contacts</button>
</div>
</div>
</div>
<div v-if="activeChangeItems.length" class="grid min-h-0 flex-1 gap-3 md:grid-cols-[360px_1fr]">
<aside class="min-h-0 overflow-y-auto rounded-xl border border-base-300 bg-base-100 p-2">
<button
v-for="(item, idx) in activeChangeItems"
:key="`change-review-item-${item.id}`"
class="mb-2 block w-full rounded-lg border px-2 py-2 text-left transition hover:bg-base-200/50"
:class="idx === activeChangeStep ? 'border-primary bg-primary/5' : 'border-base-300'"
@click="goToChangeStep(idx)"
>
<div class="flex items-start gap-2">
<input
type="checkbox"
class="checkbox checkbox-xs mt-0.5"
v-model="changeSelectionByItemId[item.id]"
:disabled="item.rolledBack"
@click.stop
>
<div class="min-w-0 flex-1">
<p class="truncate text-xs font-semibold">{{ idx + 1 }}. {{ item.title }}</p>
<p class="text-[11px] text-base-content/60">{{ item.entity }} · {{ item.action }}</p>
<p v-if="item.rolledBack" class="mt-1 text-[10px] uppercase tracking-wide text-red-400">Rolled back</p>
</div>
</div>
</button>
</aside>
<article v-if="activeChangeItem" class="min-h-0 overflow-y-auto rounded-xl border border-base-300 bg-base-100 p-3">
<div class="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<p class="text-sm font-semibold">{{ activeChangeItem.title }}</p>
<p class="text-xs text-base-content/60">
Step {{ activeChangeStep + 1 }} / {{ activeChangeItems.length }} · {{ activeChangeItem.entity }} · {{ activeChangeItem.action }}
</p>
</div>
<div class="flex items-center gap-2">
<button class="btn btn-xs btn-ghost" :disabled="activeChangeStep <= 0" @click="goToChangeStep(activeChangeStep - 1)">Prev</button>
<button class="btn btn-xs btn-ghost" :disabled="activeChangeStep >= activeChangeItems.length - 1" @click="goToChangeStep(activeChangeStep + 1)">Next</button>
<button class="btn btn-xs btn-outline" @click="openChangeItemTarget(activeChangeItem)">Open target</button>
</div>
</div>
<div class="grid gap-3 md:grid-cols-2">
<div class="rounded-lg border border-red-300/40 bg-red-500/5 p-2">
<p class="mb-1 text-xs font-semibold text-red-300">Before</p>
<p class="whitespace-pre-wrap text-xs text-base-content/80">{{ activeChangeItem.before || "—" }}</p>
</div>
<div class="rounded-lg border border-emerald-300/40 bg-emerald-500/5 p-2">
<p class="mb-1 text-xs font-semibold text-emerald-300">After</p>
<p class="whitespace-pre-wrap text-xs text-base-content/80">{{ activeChangeItem.after || "—" }}</p>
</div>
</div>
</article>
</div>
<div v-else class="rounded-xl border border-base-300 bg-base-100 p-4 text-sm text-base-content/65">
No change set found for this route.
</div>
</section>
<section v-else-if="selectedTab === 'communications' && peopleLeftMode === 'calendar'" class="flex h-full min-h-0 flex-col gap-3">
<div class="grid grid-cols-[auto_1fr_auto] items-center gap-2">
<div class="flex items-center gap-1">
<button class="btn btn-xs" @click="setToday">Today</button>
@@ -3103,8 +3465,8 @@ async function decideFeedCard(card: FeedCard, decision: "accepted" | "rejected")
<section v-else-if="selectedTab === 'communications' && false" class="space-y-3">
<div class="mb-1 flex justify-end">
<div class="join">
<button class="btn btn-sm join-item btn-primary" @click="peopleLeftMode = 'contacts'">Contacts</button>
<button class="btn btn-sm join-item btn-ghost" @click="peopleLeftMode = 'calendar'">Calendar</button>
<button class="btn btn-sm join-item btn-primary" @click="setPeopleLeftMode('contacts', true)">Contacts</button>
<button class="btn btn-sm join-item btn-ghost" @click="setPeopleLeftMode('calendar', true)">Calendar</button>
</div>
</div>
<div class="rounded-xl border border-base-300 p-3">

View File

@@ -21,11 +21,14 @@ query ChatMessagesQuery {
changeStatus
changeSummary
changeItems {
id
entity
entityId
action
title
before
after
rolledBack
}
createdAt
}

View File

@@ -0,0 +1,5 @@
mutation RollbackChangeSetItemsMutation($changeSetId: ID!, $itemIds: [ID!]!) {
rollbackChangeSetItems(changeSetId: $changeSetId, itemIds: $itemIds) {
ok
}
}

View File

@@ -5,7 +5,7 @@ import { clearAuthSession, setSession } from "../utils/auth";
import { prisma } from "../utils/prisma";
import { normalizePhone, verifyPassword } from "../utils/password";
import { persistChatMessage, runCrmAgentFor } from "../agent/crmAgent";
import { buildChangeSet, captureSnapshot, rollbackChangeSet } from "../utils/changeSet";
import { buildChangeSet, captureSnapshot, rollbackChangeSet, rollbackChangeSetItems } from "../utils/changeSet";
import type { ChangeSet } from "../utils/changeSet";
type GraphQLContext = {
@@ -275,12 +275,17 @@ async function getChatMessages(auth: AuthContext | null) {
changeStatus: cs?.status ?? null,
changeSummary: cs?.summary ?? null,
changeItems: Array.isArray(cs?.items)
? cs.items.map((item) => ({
? cs.items.map((item, idx) => ({
id: String((item as any)?.id ?? `legacy-${idx}`),
entity: String(item.entity ?? ""),
entityId: (item as any)?.entityId ? String((item as any).entityId) : null,
action: String(item.action ?? ""),
title: String(item.title ?? ""),
before: String(item.before ?? ""),
after: String(item.after ?? ""),
rolledBack: Array.isArray((cs as any)?.rolledBackItemIds)
? (cs as any).rolledBackItemIds.includes((item as any)?.id)
: false,
}))
: [],
createdAt: m.createdAt.toISOString(),
@@ -685,6 +690,31 @@ async function findLatestChangeCarrierMessage(auth: AuthContext | null) {
return null;
}
async function findChangeCarrierMessageByChangeSetId(auth: AuthContext | null, changeSetId: string) {
const ctx = requireAuth(auth);
const targetId = String(changeSetId ?? "").trim();
if (!targetId) return null;
const items = await prisma.chatMessage.findMany({
where: {
teamId: ctx.teamId,
conversationId: ctx.conversationId,
role: "ASSISTANT",
},
orderBy: { createdAt: "desc" },
take: 200,
});
for (const item of items) {
const changeSet = getChangeSetFromPlanJson(item.planJson);
if (!changeSet) continue;
if (changeSet.id !== targetId) continue;
return { item, changeSet };
}
return null;
}
async function confirmLatestChangeSet(auth: AuthContext | null) {
const found = await findLatestChangeCarrierMessage(auth);
if (!found) return { ok: true };
@@ -725,6 +755,54 @@ async function rollbackLatestChangeSet(auth: AuthContext | null) {
...changeSet,
status: "rolled_back",
rolledBackAt: new Date().toISOString(),
rolledBackItemIds: Array.isArray(changeSet.items)
? changeSet.items
.map((changeItem: any, idx: number) => String(changeItem?.id ?? `legacy-${idx}`))
.filter(Boolean)
: [],
},
};
await prisma.chatMessage.update({
where: { id: item.id },
data: { planJson: next as any },
});
return { ok: true };
}
async function rollbackChangeSetItemsMutation(auth: AuthContext | null, changeSetId: string, itemIds: string[]) {
const ctx = requireAuth(auth);
const found = await findChangeCarrierMessageByChangeSetId(ctx, changeSetId);
if (!found) return { ok: true };
const { item, changeSet } = found;
if (changeSet.status === "rolled_back") return { ok: true };
const selectedIds = [...new Set((itemIds ?? []).map((id) => String(id ?? "").trim()).filter(Boolean))];
if (!selectedIds.length) return { ok: true };
await rollbackChangeSetItems(prisma, ctx.teamId, changeSet, selectedIds);
const allIds = Array.isArray(changeSet.items)
? changeSet.items
.map((changeItem: any, idx: number) => String(changeItem?.id ?? `legacy-${idx}`))
.filter(Boolean)
: [];
const prevRolledBack = Array.isArray((changeSet as any)?.rolledBackItemIds)
? ((changeSet as any).rolledBackItemIds as string[]).map((id) => String(id))
: [];
const nextRolledBackSet = new Set([...prevRolledBack, ...selectedIds]);
const nextRolledBack = [...nextRolledBackSet];
const allRolledBack = allIds.length > 0 && allIds.every((id) => nextRolledBackSet.has(id));
const next = {
...((item.planJson as any) ?? {}),
changeSet: {
...changeSet,
status: allRolledBack ? "rolled_back" : "pending",
rolledBackAt: allRolledBack ? new Date().toISOString() : null,
rolledBackItemIds: nextRolledBack,
},
};
@@ -867,6 +945,7 @@ export const crmGraphqlSchema = buildSchema(`
sendPilotMessage(text: String!): MutationResult!
confirmLatestChangeSet: MutationResult!
rollbackLatestChangeSet: MutationResult!
rollbackChangeSetItems(changeSetId: ID!, itemIds: [ID!]!): MutationResult!
logPilotNote(text: String!): MutationResult!
toggleContactPin(contact: String!, text: String!): PinToggleResult!
createCalendarEvent(input: CreateCalendarEventInput!): CalendarEvent!
@@ -963,11 +1042,14 @@ export const crmGraphqlSchema = buildSchema(`
}
type PilotChangeItem {
id: ID!
entity: String!
entityId: String
action: String!
title: String!
before: String!
after: String!
rolledBack: Boolean!
}
type PilotToolRun {
@@ -1116,6 +1198,11 @@ export const crmGraphqlRoot = {
rollbackLatestChangeSet: async (_args: unknown, context: GraphQLContext) =>
rollbackLatestChangeSet(context.auth),
rollbackChangeSetItems: async (
args: { changeSetId: string; itemIds: string[] },
context: GraphQLContext,
) => rollbackChangeSetItemsMutation(context.auth, args.changeSetId, args.itemIds),
logPilotNote: async (args: { text: string }, context: GraphQLContext) =>
logPilotNote(context.auth, args.text),

View File

@@ -49,11 +49,14 @@ export type SnapshotState = {
};
export type ChangeItem = {
id: string;
entity: "calendar_event" | "contact_note" | "message" | "deal";
entityId: string | null;
action: "created" | "updated" | "deleted";
title: string;
before: string;
after: string;
undo: UndoOp[];
};
type UndoOp =
@@ -71,6 +74,7 @@ export type ChangeSet = {
summary: string;
items: ChangeItem[];
undo: UndoOp[];
rolledBackItemIds: string[];
};
function fmt(val: string | null | undefined) {
@@ -190,18 +194,24 @@ export async function captureSnapshot(prisma: PrismaClient, teamId: string): Pro
export function buildChangeSet(before: SnapshotState, after: SnapshotState): ChangeSet | null {
const items: ChangeItem[] = [];
const undo: UndoOp[] = [];
const pushItem = (item: Omit<ChangeItem, "id">) => {
const next: ChangeItem = { ...item, id: randomUUID() };
items.push(next);
undo.push(...next.undo);
};
for (const [id, row] of after.calendarById) {
const prev = before.calendarById.get(id);
if (!prev) {
items.push({
pushItem({
entity: "calendar_event",
entityId: row.id,
action: "created",
title: `Event created: ${row.title}`,
before: "",
after: toCalendarText(row),
undo: [{ kind: "delete_calendar_event", id }],
});
undo.push({ kind: "delete_calendar_event", id });
continue;
}
if (
@@ -214,95 +224,104 @@ export function buildChangeSet(before: SnapshotState, after: SnapshotState): Cha
fmt(prev.archivedAt) !== fmt(row.archivedAt) ||
prev.contactId !== row.contactId
) {
items.push({
pushItem({
entity: "calendar_event",
entityId: row.id,
action: "updated",
title: `Event updated: ${row.title}`,
before: toCalendarText(prev),
after: toCalendarText(row),
undo: [{ kind: "restore_calendar_event", data: prev }],
});
undo.push({ kind: "restore_calendar_event", data: prev });
}
}
for (const [id, row] of before.calendarById) {
if (after.calendarById.has(id)) continue;
items.push({
pushItem({
entity: "calendar_event",
entityId: row.id,
action: "deleted",
title: `Event archived: ${row.title}`,
before: toCalendarText(row),
after: "",
undo: [{ kind: "restore_calendar_event", data: row }],
});
undo.push({ kind: "restore_calendar_event", data: row });
}
for (const [contactId, row] of after.noteByContactId) {
const prev = before.noteByContactId.get(contactId);
if (!prev) {
items.push({
pushItem({
entity: "contact_note",
entityId: contactId,
action: "created",
title: `Summary added: ${row.contactName}`,
before: "",
after: row.content,
undo: [{ kind: "restore_contact_note", contactId, content: null }],
});
undo.push({ kind: "restore_contact_note", contactId, content: null });
continue;
}
if (prev.content !== row.content) {
items.push({
pushItem({
entity: "contact_note",
entityId: contactId,
action: "updated",
title: `Summary updated: ${row.contactName}`,
before: prev.content,
after: row.content,
undo: [{ kind: "restore_contact_note", contactId, content: prev.content }],
});
undo.push({ kind: "restore_contact_note", contactId, content: prev.content });
}
}
for (const [contactId, row] of before.noteByContactId) {
if (after.noteByContactId.has(contactId)) continue;
items.push({
pushItem({
entity: "contact_note",
entityId: contactId,
action: "deleted",
title: `Summary cleared: ${row.contactName}`,
before: row.content,
after: "",
undo: [{ kind: "restore_contact_note", contactId, content: row.content }],
});
undo.push({ kind: "restore_contact_note", contactId, content: row.content });
}
for (const [id, row] of after.messageById) {
if (before.messageById.has(id)) continue;
items.push({
pushItem({
entity: "message",
entityId: row.id,
action: "created",
title: `Message created: ${row.contactName}`,
before: "",
after: toMessageText(row),
undo: [{ kind: "delete_contact_message", id }],
});
undo.push({ kind: "delete_contact_message", id });
}
for (const [id, row] of after.dealById) {
const prev = before.dealById.get(id);
if (!prev) continue;
if (prev.stage !== row.stage || fmt(prev.nextStep) !== fmt(row.nextStep) || fmt(prev.summary) !== fmt(row.summary)) {
items.push({
pushItem({
entity: "deal",
entityId: row.id,
action: "updated",
title: `Deal updated: ${row.title}`,
before: toDealText(prev),
after: toDealText(row),
});
undo.push({
kind: "restore_deal",
id,
stage: prev.stage,
nextStep: prev.nextStep,
summary: prev.summary,
undo: [
{
kind: "restore_deal",
id,
stage: prev.stage,
nextStep: prev.nextStep,
summary: prev.summary,
},
],
});
}
}
@@ -320,11 +339,12 @@ export function buildChangeSet(before: SnapshotState, after: SnapshotState): Cha
summary: `Created: ${created}, Updated: ${updated}, Archived: ${deleted}`,
items,
undo,
rolledBackItemIds: [],
};
}
export async function rollbackChangeSet(prisma: PrismaClient, teamId: string, changeSet: ChangeSet) {
const ops = [...changeSet.undo].reverse();
async function applyUndoOps(prisma: PrismaClient, teamId: string, undoOps: UndoOp[]) {
const ops = [...undoOps].reverse();
await prisma.$transaction(async (tx) => {
for (const op of ops) {
@@ -424,3 +444,31 @@ export async function rollbackChangeSet(prisma: PrismaClient, teamId: string, ch
}
});
}
export async function rollbackChangeSet(prisma: PrismaClient, teamId: string, changeSet: ChangeSet) {
await applyUndoOps(prisma, teamId, changeSet.undo);
}
export async function rollbackChangeSetItems(
prisma: PrismaClient,
teamId: string,
changeSet: ChangeSet,
itemIds: string[],
) {
const wanted = new Set(itemIds.filter(Boolean));
if (!wanted.size) return;
const itemUndoOps = changeSet.items
.filter((item) => wanted.has(item.id))
.flatMap((item) => (Array.isArray(item.undo) ? item.undo : []));
if (itemUndoOps.length > 0) {
await applyUndoOps(prisma, teamId, itemUndoOps);
return;
}
// Legacy fallback for old change sets without per-item undo.
if (wanted.size >= changeSet.items.length && Array.isArray(changeSet.undo) && changeSet.undo.length > 0) {
await applyUndoOps(prisma, teamId, changeSet.undo);
}
}