Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
OpenAI Platform credential with an OpenAI GPT-5.4-or-newer model. Do not route
Strix through GitHub Models, `github.token`, generic `LLM_API_KEY`, Gemini,
Google/Vertex, GPT-4o, or GPT-4.1; record direct-provider evidence in the PR.
Keep architecture docs and reusable Strix gate tests aligned with this rule so
stale GitHub Models examples cannot re-enter copied workflow guidance.

## PR automation and review defaults

Expand Down
7 changes: 4 additions & 3 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,10 @@ it must never fall back to scanning trusted-base content for a modified PR path.
Pull request scans split scoped changed files into small bounded batches before
the timeout-driven rebalance path, so large PRs do not spend the whole required
check budget on one oversized Strix invocation. Strix remains a required
Medium-or-higher gate. The workflow uses GitHub Models through `models: read`,
the OpenAI-compatible GitHub Models endpoint, and an OpenAI GPT-5-or-newer
model; non-GPT-5 provider fallbacks are not valid PR evidence for this gate.
Medium-or-higher gate. The workflow uses only the explicit
`STRIX_OPENAI_API_KEY` OpenAI Platform credential with an OpenAI
GPT-5.4-or-newer model, rejects GitHub Models routing and `github.token` LLM
credentials, and fails closed when direct credentials are missing or exhausted.
Merge-gate governance for Strix, CodeRabbit, and required review evidence is
documented in `docs/development/merge-gate-policy.md`.

Expand Down
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,12 @@ curl -s -X POST http://localhost:8000/api/tasks/from-email \

# Request a customer-owned calendar writeback intent. This selects a trusted
# server-side source and returns no provider secret or direct write proof.
curl -s http://localhost:8000/api/calendar/writeback-sources \
-H "Authorization: Bearer $NARUON_DEV_BEARER"
curl -s -X POST http://localhost:8000/api/calendar/writeback-intent \
-H "Authorization: Bearer $NARUON_DEV_BEARER" \
-H 'content-type: application/json' \
-d '{"action":"create","summary":"담당자 확인 회의"}'
-d '{"action":"create","summary":"담당자 확인 회의","target_source_id":"caldav-primary"}'
```

## Error-message contract
Expand Down Expand Up @@ -255,9 +257,11 @@ Calendar actions in `EmailDetail` now request `/api/calendar/writeback-intent`
for each extracted execution item and display the selected trusted source
provenance. Calendar source selection now reads opaque
`calendar_writeback_sources.source_uid` rows instead of exposing sequential
CalDAV account ids. The browser no longer claims `/api/calendar/sync` success
from the mail-detail action path; direct provider writes stay deferred until
connector execution can enforce ETag/If-Match and owner capability checks.
CalDAV account ids, and the Calendar workspace loads those rows through signed
`/api/calendar/writeback-sources` before posting an opaque `target_source_id`.
The browser no longer claims `/api/calendar/sync` success from the mail-detail
action path; direct provider writes stay deferred until connector execution can
enforce ETag/If-Match and owner capability checks.
WebDAV writeback and self-sent knowledge materialization use
`webdav_accounts.source_uid` as the browser-visible source id, scope lookup by
the signed session organization, honor persisted `writeback_enabled`
Expand Down
7 changes: 7 additions & 0 deletions backend/api/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,13 @@ async def get_writeback_sources(
)


@router.get("/writeback-sources", response_model=tuple[WritebackSource, ...])
async def list_writeback_sources(
available_sources: tuple[WritebackSource, ...] = Depends(get_writeback_sources),
) -> tuple[WritebackSource, ...]:
return available_sources


async def get_calendar_user_token(
auth_context: AuthContext = Depends(get_auth_context),
) -> dict | None:
Expand Down
35 changes: 35 additions & 0 deletions backend/tests/test_calendar_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,41 @@ def test_calendar_writeback_intent_uses_customer_owned_caldav_account(
}


def test_calendar_writeback_sources_endpoint_lists_authoritative_sources(
writeback_source_override,
):
writeback_source_override(
[
WritebackSource(
source_id="calendar-primary",
provider="fastmail",
protocol="caldav",
owner_id="testuser",
organization_id="org-acme",
capabilities=["read", "write", "etag"],
writeback_enabled=True,
etag="abc123",
)
]
)

response = workspace_client.get("/api/calendar/writeback-sources")

assert response.status_code == 200
assert response.json() == [
{
"source_id": "calendar-primary",
"provider": "fastmail",
"protocol": "caldav",
"owner_id": "testuser",
"organization_id": "org-acme",
"capabilities": ["read", "write", "etag"],
"writeback_enabled": True,
"etag": "abc123",
}
]


def test_calendar_writeback_update_requires_etag_if_match(writeback_source_override):
writeback_source_override(
[
Expand Down
3 changes: 2 additions & 1 deletion docs/operations/source-of-truth-and-writeback-sovereignty.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ contracts, source-linked ticket tasks, self-sent knowledge capture into
idempotent ticket tasks, deterministic sender ontology action hints, generic
WebDAV writeback intent, self-sent knowledge WebDAV/Notes materialization
intent, DB-backed CalDAV intent source selection through opaque
`calendar_writeback_sources.source_uid` rows, and WebDAV intent selection through
`calendar_writeback_sources.source_uid` rows exposed to the Calendar workspace
through a signed source-registry read, and WebDAV intent selection through
opaque, organization-scoped `webdav_accounts.source_uid` rows with persisted
writeback eligibility. Real CalDAV/WebDAV mutation,
ETag-aware WebDAV/Notes provider execution for synthesized knowledge, POP3
Expand Down
6 changes: 6 additions & 0 deletions docs/plans/2026-05-27-calendar-writeback-intent-ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ is the calendar server or directly writing provider data from the browser.
- Customer CalDAV/CardDAV/WebDAV accounts remain the source of truth.
- Calendar actions create server-authoritative intent through
`POST /api/calendar/writeback-intent`.
- The Calendar workspace first loads server-owned source registry rows through
`GET /api/calendar/writeback-sources`; the browser may pass only the opaque
`target_source_id`, never owner or capability claims.
- The UI must show `writeback_mode`, `protocol`, `target_source_id`,
`if_match`, and `audit_event` when the intent is accepted.
- `422` means no customer-owned source is available.
Expand All @@ -23,6 +26,8 @@ is the calendar server or directly writing provider data from the browser.
## Implemented Slice

- `/calendar` now exposes a CalDAV/CardDAV/WebDAV intent check panel.
- The intent panel lists signed-session CalDAV registry sources and chooses an
eligible write-capable customer source before posting intent.
- The monthly, weekly, detail, coordination, and candidate calendar tabs all
render concrete surfaces instead of an inert "under implementation" state.
- Mobile layout keeps the header and monthly grid bounded, and adds bottom safe
Expand All @@ -34,6 +39,7 @@ is the calendar server or directly writing provider data from the browser.

```bash
npm test -- src/app/calendar/page.test.tsx src/components/EmailDetail.test.tsx src/lib/api-client.test.ts
PYTHONDONTWRITEBYTECODE=1 DISABLE_BACKGROUND_WORKERS=1 python3 -m pytest backend/tests/test_calendar_api.py -q
npm test -- src/components/mobile-workspace-panels.test.tsx
npm run typecheck
npm run build
Expand Down
27 changes: 27 additions & 0 deletions frontend/src/app/calendar/page.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ async function flushAsyncWork() {
});
}

const calendarSourceList = [
{
source_id: "caldav-primary",
provider: "Customer CalDAV",
protocol: "caldav",
owner_id: "user-1",
organization_id: "org-acme",
capabilities: ["read", "write", "etag"],
writeback_enabled: true,
etag: "etag-caldav-1",
},
];

describe("CalendarPage", () => {
let root: Root | null = null;
let container: HTMLDivElement | null = null;
Expand All @@ -53,6 +66,7 @@ describe("CalendarPage", () => {
});

it("renders monthly weekly detail coordination candidate and CalDAV writeback workspaces", () => {
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(calendarSourceList)));
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
Expand All @@ -69,6 +83,14 @@ describe("CalendarPage", () => {
it("creates a signed customer-owned calendar writeback intent", async () => {
localStorage.setItem("naruon_session_token", "signed-calendar-session");
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
if (String(input) === "/api/calendar/writeback-sources") {
expect(init?.method).toBeUndefined();
expect(init?.headers).toEqual(expect.objectContaining({
"Content-Type": "application/json",
Authorization: "Bearer signed-calendar-session",
}));
return jsonResponse(calendarSourceList);
}
expect(String(input)).toBe("/api/calendar/writeback-intent");
expect(init?.method).toBe("POST");
expect(init?.headers).toEqual(expect.objectContaining({
Expand All @@ -90,6 +112,7 @@ describe("CalendarPage", () => {
expect(JSON.parse(String(init?.body))).toEqual({
action: "create",
summary: "Naruon 일정 후보 writeback intent 점검",
target_source_id: "caldav-primary",
});
return jsonResponse({
workspace_id: "workspace-org-acme",
Expand All @@ -114,6 +137,8 @@ describe("CalendarPage", () => {
act(() => {
root?.render(<CalendarPage />);
});
await flushAsyncWork();
expect(container.textContent).toContain("Customer CalDAV");

const button = Array.from(container.querySelectorAll("button")).find((node) => node.textContent?.includes("새 일정 intent 점검"));
expect(button).toBeTruthy();
Expand Down Expand Up @@ -148,6 +173,7 @@ describe("CalendarPage", () => {

it("distinguishes no-source and ETag conflict writeback errors", async () => {
const responses = [
jsonResponse(calendarSourceList),
jsonResponse({ detail: "No customer-owned writeback source is available" }, false, 422),
jsonResponse({ detail: "ETag is required for writeback updates" }, false, 409),
];
Expand All @@ -159,6 +185,7 @@ describe("CalendarPage", () => {
act(() => {
root?.render(<CalendarPage />);
});
await flushAsyncWork();

const createButton = Array.from(container.querySelectorAll("button")).find((node) => node.textContent?.includes("새 일정 intent 점검"));
await act(async () => {
Expand Down
83 changes: 81 additions & 2 deletions frontend/src/components/CalendarLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import { useCallback, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { ChevronLeft, ChevronRight, Settings, Plus, Users, Video, Paperclip, Clock, CalendarDays, X } from 'lucide-react';

import { apiClient } from '@/lib/api-client';
Expand All @@ -16,6 +16,17 @@ type CalendarWritebackIntentResponse = {
audit_event: string;
};

type CalendarWritebackSource = {
source_id: string;
provider: string;
protocol: 'caldav' | 'carddav' | 'webdav' | 'local';
owner_id: string;
organization_id: string | null;
capabilities: string[];
writeback_enabled: boolean;
etag: string | null;
};

type WritebackStatus = 'idle' | 'loading' | 'success' | 'no_source' | 'conflict' | 'auth' | 'error';

function getApiErrorStatus(error: unknown) {
Expand All @@ -29,8 +40,43 @@ export function CalendarLayout() {
const [viewMode, setViewMode] = useState<'월간 캘린더' | '주간 캘린더' | '일정 상세' | '회의 조율' | '일정 후보'>('월간 캘린더');
const [writebackStatus, setWritebackStatus] = useState<WritebackStatus>('idle');
const [writebackResult, setWritebackResult] = useState<CalendarWritebackIntentResponse | null>(null);
const [writebackSources, setWritebackSources] = useState<CalendarWritebackSource[]>([]);
const [sourceLoadStatus, setSourceLoadStatus] = useState<'loading' | 'ready' | 'error'>('loading');

useEffect(() => {
let isMounted = true;
void apiClient.get<CalendarWritebackSource[]>('/api/calendar/writeback-sources')
.then((sources) => {
if (!isMounted) return;
setWritebackSources(sources);
setSourceLoadStatus('ready');
})
.catch(() => {
if (!isMounted) return;
setWritebackSources([]);
setSourceLoadStatus('error');
});

return () => {
isMounted = false;
};
}, []);

const selectedWritebackSource = useMemo(
() => writebackSources.find((source) => (
source.writeback_enabled
&& source.protocol !== 'local'
&& source.capabilities.includes('write')
)) ?? null,
[writebackSources],
);

const requestWritebackIntent = useCallback(async (action: 'create' | 'update') => {
if (sourceLoadStatus === 'ready' && selectedWritebackSource === null) {
setWritebackResult(null);
setWritebackStatus('no_source');
return;
}
setWritebackStatus('loading');
setWritebackResult(null);
try {
Expand All @@ -39,6 +85,7 @@ export function CalendarLayout() {
summary: action === 'create'
? 'Naruon 일정 후보 writeback intent 점검'
: 'Naruon 기존 일정 ETag/If-Match 충돌 점검',
...(selectedWritebackSource ? { target_source_id: selectedWritebackSource.source_id } : {}),
});
setWritebackResult(result);
setWritebackStatus('success');
Expand All @@ -54,7 +101,7 @@ export function CalendarLayout() {
setWritebackStatus('error');
}
}
}, []);
}, [selectedWritebackSource, sourceLoadStatus]);

const isWritebackLoading = writebackStatus === 'loading';

Expand Down Expand Up @@ -153,6 +200,38 @@ export function CalendarLayout() {
</div>
</div>

<div className="mt-4 grid gap-3 md:grid-cols-2">
{writebackSources.map((source) => (
<article
key={source.source_id}
className="rounded-xl border border-border bg-background/70 p-3"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="font-mono text-xs font-bold text-primary">{source.source_id}</p>
<p className="mt-1 break-words text-sm font-bold">{source.provider}</p>
</div>
<span className={`rounded-full px-2 py-1 text-xs font-black ${source.writeback_enabled ? 'bg-green-100 text-green-700' : 'bg-secondary text-muted-foreground'}`}>
{source.writeback_enabled ? 'write' : 'read_only'}
</span>
</div>
<p className="mt-2 text-xs font-semibold text-muted-foreground">
{source.protocol} · {source.capabilities.join(', ')}
</p>
</article>
))}
{sourceLoadStatus === 'loading' && (
<p className="rounded-xl border border-border bg-background/70 p-3 text-sm font-bold text-primary">
CalDAV source registry 확인 중입니다.
</p>
)}
{sourceLoadStatus === 'error' && (
<p className="rounded-xl border border-border bg-background/70 p-3 text-sm font-bold text-amber-700">
signed session으로 CalDAV source registry를 확인할 수 없습니다.
</p>
)}
</div>

<div role="status" aria-live="polite" className="mt-4 rounded-xl border border-border bg-background/70 p-4 text-sm">
{writebackStatus === 'idle' && (
<p className="text-muted-foreground">아직 provider write는 실행하지 않았습니다. intent 점검으로 원본 source와 충돌 조건만 확인합니다.</p>
Expand Down
20 changes: 17 additions & 3 deletions frontend/tests/e2e/dashboard-branding.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,20 +471,27 @@ test('renders calendar writeback intent status without direct provider writes',
}, expectedNaruonToken);

await page.goto('/calendar');
await expect(page.getByText('Customer CalDAV').first()).toBeVisible();
const desktopWritebackRequest = page.waitForRequest((request) => {
const url = new URL(request.url());
return url.pathname === '/api/calendar/writeback-intent' && request.method() === 'POST';
});
await page.getByRole('button', { name: '새 일정 intent 점검' }).click();
const desktopRequestHeaders = (await desktopWritebackRequest).headers();
const desktopWritebackCall = await desktopWritebackRequest;
const desktopRequestHeaders = desktopWritebackCall.headers();
expect(desktopRequestHeaders.authorization).toBe(`Bearer ${expectedNaruonToken}`);
expect(desktopWritebackCall.postDataJSON()).toEqual({
action: 'create',
summary: 'Naruon 일정 후보 writeback intent 점검',
target_source_id: 'caldav-primary',
});
for (const headerName of publicIdentityHeaders) {
expect(desktopRequestHeaders[headerName]).toBeUndefined();
}

await expect(page.getByText('customer_owned')).toBeVisible();
await expect(page.getByText('caldav', { exact: true })).toBeVisible();
await expect(page.getByText('caldav-primary')).toBeVisible();
await expect(page.getByRole('status').getByText('caldav-primary')).toBeVisible();
await expect(page.getByText('calendar.writeback_intent.created')).toBeVisible();
await expect(page.getByText('동기화 완료')).toHaveCount(0);
const desktopOverflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
Expand All @@ -494,13 +501,20 @@ test('renders calendar writeback intent status without direct provider writes',
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('/calendar');
await expect(page.getByRole('heading', { name: '일정 관리' })).toBeVisible();
await expect(page.getByText('caldav-primary').first()).toBeVisible();
const mobileWritebackRequest = page.waitForRequest((request) => {
const url = new URL(request.url());
return url.pathname === '/api/calendar/writeback-intent' && request.method() === 'POST';
});
await page.getByRole('button', { name: '새 일정 intent 점검' }).click();
const mobileRequestHeaders = (await mobileWritebackRequest).headers();
const mobileWritebackCall = await mobileWritebackRequest;
const mobileRequestHeaders = mobileWritebackCall.headers();
expect(mobileRequestHeaders.authorization).toBe(`Bearer ${expectedNaruonToken}`);
expect(mobileWritebackCall.postDataJSON()).toEqual({
action: 'create',
summary: 'Naruon 일정 후보 writeback intent 점검',
target_source_id: 'caldav-primary',
});
for (const headerName of publicIdentityHeaders) {
expect(mobileRequestHeaders[headerName]).toBeUndefined();
}
Expand Down
Loading
Loading