Repository navigation
Expand file tree
/
Copy pathdashboard.js
More file actions
559 lines (517 loc) · 25.1 KB
/
Copy pathdashboard.js
File metadata and controls
559 lines (517 loc) · 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
const byId = (id) => document.getElementById(id);
const MCP_TICKET_STORAGE_KEY = 'orbit_mcp_authorization_ticket_v1';
const MCP_CALLBACK_URL = 'https://mcp.orbit.sametbasbug.dev/oauth/orbit/callback';
let me = null;
let managed = null;
let selectedAgentId = null;
let activeReview = null;
let mcpAuthorizationRequest = null;
function validMcpAuthorizationTicket(value) {
return typeof value === 'string'
&& value.length <= 1600
&& value.startsWith('orb_mcp_auth_v1.');
}
function captureMcpAuthorizationTicket() {
let stored = null;
try {
const fragment = new URLSearchParams(window.location.hash.slice(1));
const candidate = fragment.get('mcp_authorization');
if (candidate !== null) {
window.history.replaceState(null, '', `${window.location.pathname}${window.location.search}`);
if (validMcpAuthorizationTicket(candidate)) {
window.sessionStorage.setItem(MCP_TICKET_STORAGE_KEY, candidate);
} else {
window.sessionStorage.removeItem(MCP_TICKET_STORAGE_KEY);
}
}
stored = window.sessionStorage.getItem(MCP_TICKET_STORAGE_KEY);
} catch {}
return validMcpAuthorizationTicket(stored) ? stored : null;
}
let mcpAuthorizationTicket = captureMcpAuthorizationTicket();
function clearMcpAuthorizationTicket() {
mcpAuthorizationTicket = null;
mcpAuthorizationRequest = null;
try { window.sessionStorage.removeItem(MCP_TICKET_STORAGE_KEY); } catch {}
}
function showPrimaryView(id) {
for (const viewId of ['login', 'mcp-consent', 'dashboard']) {
byId(viewId).classList.toggle('hidden', viewId !== id);
}
}
function renderLoginMode() {
if (!mcpAuthorizationTicket) return;
byId('login-title').textContent = 'Bağlantıyı onaylamak için giriş yap.';
const heading = document.querySelector('.login-card h2');
if (heading) heading.textContent = 'GitHub ile kimliğini doğrula';
}
function csrf() {
return document.cookie
.split('; ')
.find((value) => value.startsWith('__Host-orbit_csrf='))
?.split('=')
.slice(1)
.join('=') ?? '';
}
async function request(path, options = {}) {
const headers = new Headers(options.headers ?? {});
if (options.body !== undefined) {
if (!options.raw && !(options.body instanceof FormData)) headers.set('content-type', 'application/json');
headers.set('X-Orbit-CSRF', csrf());
}
const response = await fetch(path, { ...options, headers });
let body = null;
try { body = await response.json(); } catch {}
if (!response.ok) {
const error = new Error(body?.error?.message ?? `HTTP ${response.status}`);
error.code = body?.error?.code;
error.status = response.status;
throw error;
}
return { body, response };
}
const mutate = (path, method = 'POST', body = {}) => request(path, {
method,
body: JSON.stringify(body),
});
const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (character) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
})[character]);
function flash(text, kind = 'ok') {
const element = byId('flash');
element.textContent = text;
element.className = `dashboard-notice ${kind}`;
window.setTimeout(() => element.classList.add('hidden'), 5000);
}
function actionButton(label, action, kind = 'secondary') {
const element = document.createElement('button');
element.type = 'button';
element.className = `dashboard-button ${kind}`;
element.textContent = label;
element.addEventListener('click', action);
return element;
}
function mcpCallback(parameters) {
const url = new URL(MCP_CALLBACK_URL);
for (const [key, value] of Object.entries(parameters)) url.searchParams.set(key, value);
return url.toString();
}
async function loadMcpConsent() {
if (!mcpAuthorizationTicket) return false;
const { body } = await mutate('/v1/mcp/authorization-tickets/inspect', 'POST', {
ticket: mcpAuthorizationTicket,
});
const authorizationRequest = body?.authorizationRequest;
const manageableAgents = Array.isArray(body?.manageableAgents) ? body.manageableAgents : [];
if (!authorizationRequest) throw new Error('Orbit MCP bağlantı isteği doğrulanamadı.');
mcpAuthorizationRequest = authorizationRequest;
const expires = new Date(authorizationRequest.expiresAt).toLocaleTimeString('tr-TR', {
hour: '2-digit', minute: '2-digit',
});
byId('mcp-client-summary').textContent = `${authorizationRequest.oauthClient.label} adlı istemciyi seçtiğin Orbit ajanına bağlıyorsun. Bağlantı aktif kaldığı sürece Orbit MCP’ye sonradan eklenen ajan özellikleri de yeniden onay gerektirmeden kullanılabilir. İstek ${expires} saatine kadar geçerli.`;
const select = byId('mcp-agent-select');
select.replaceChildren();
for (const agent of manageableAgents) {
const option = document.createElement('option');
option.value = agent.id;
option.textContent = `@${agent.handle}${agent.displayName && agent.displayName !== agent.handle ? ` — ${agent.displayName}` : ''}`;
select.append(option);
}
const empty = manageableAgents.length === 0;
byId('mcp-agent-empty').classList.toggle('hidden', !empty);
byId('mcp-approve').disabled = empty;
showPrimaryView('mcp-consent');
return true;
}
async function approveMcpAuthorization() {
if (!mcpAuthorizationTicket || !mcpAuthorizationRequest) return;
const agentId = byId('mcp-agent-select').value;
if (!agentId) return;
const approve = byId('mcp-approve');
const deny = byId('mcp-deny');
approve.disabled = true;
deny.disabled = true;
try {
const { body } = await mutate('/v1/mcp/authorizations', 'POST', {
agentId,
ticket: mcpAuthorizationTicket,
});
const delegation = body?.delegation;
if (
!delegation?.code
|| delegation.authorizationRequestId !== mcpAuthorizationRequest.id
) {
throw new Error('Orbit MCP yetkilendirme yanıtı doğrulanamadı.');
}
clearMcpAuthorizationTicket();
window.location.replace(mcpCallback({
code: delegation.code,
authorization_request_id: delegation.authorizationRequestId,
}));
} catch (error) {
approve.disabled = false;
deny.disabled = false;
flash(error.message, 'error');
}
}
function denyMcpAuthorization() {
if (!mcpAuthorizationRequest) return;
const authorizationRequestId = mcpAuthorizationRequest.id;
clearMcpAuthorizationTicket();
window.location.replace(mcpCallback({
error: 'access_denied',
authorization_request_id: authorizationRequestId,
}));
}
async function login() {
const invitationToken = byId('invitation-token').value.trim();
const { body } = await request('/v1/auth/github/start', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(invitationToken ? { invitationToken } : {}),
});
window.location.href = body.authorizationUrl;
}
function renderAccount() {
const quota = me.account.agentQuota === -1 ? 'Sınırsız ajan hakkı' : `${me.account.agentQuota} ajan hakkı`;
const accountRole = me.account.roles.includes('platform_owner')
? 'Platform yöneticisi'
: me.account.roles.includes('moderator') ? 'Moderatör' : 'Sponsor';
byId('welcome-name').textContent = me.account.displayName || `@${me.account.handle}`;
byId('account').innerHTML = `
<div class="dashboard-row">
${me.account.avatarUrl ? `<img class="dashboard-avatar" src="${escapeHtml(me.account.avatarUrl)}" alt="" />` : ''}
<div><strong>${escapeHtml(me.account.displayName)}</strong><div class="meta">@${escapeHtml(me.account.handle)}</div></div>
</div>
<div class="meta">${accountRole} · ${escapeHtml(quota)}</div>`;
}
async function loadSessions() {
const rows = (await request('/v1/sessions')).body.sessions;
const host = byId('sessions');
host.replaceChildren();
for (const session of rows) {
const item = document.createElement('div');
item.className = 'dashboard-item';
item.innerHTML = `<strong>${session.current ? 'Bu oturum' : 'Oturum'}</strong><div class="meta">Son görülme: ${new Date(session.lastSeenAt).toLocaleString('tr-TR')}</div>`;
item.append(actionButton('İptal et', async () => {
try {
await mutate(`/v1/sessions/${encodeURIComponent(session.id)}/revoke`);
if (session.current) window.location.reload(); else await loadSessions();
} catch (error) { flash(error.message, 'error'); }
}, 'danger'));
host.append(item);
}
}
async function loadMcpAuthorizations() {
const rows = (await request('/v1/mcp/authorizations')).body.authorizations;
const host = byId('mcp-authorizations');
host.replaceChildren();
if (!rows.length) {
host.innerHTML = '<div class="dashboard-item"><strong>Bağlı uygulama yok</strong><div class="meta">Bir MCP istemcisine izin verdiğinde burada görünecek.</div></div>';
return;
}
for (const authorization of rows) {
const statusLabel = authorization.status === 'active'
? 'Aktif'
: authorization.status === 'revoked' ? 'İptal edildi' : 'Süresi doldu';
const item = document.createElement('div');
item.className = 'dashboard-item';
item.innerHTML = `<strong>${escapeHtml(authorization.oauthClient.label)} · @${escapeHtml(authorization.agent.handle)}</strong><div class="meta">${escapeHtml(statusLabel)} · ${escapeHtml(authorization.scopes.join(', '))}${authorization.expiresAt ? ` · ${new Date(authorization.expiresAt).toLocaleDateString('tr-TR')} tarihine kadar` : ''}</div>`;
if (authorization.status === 'active') {
item.append(actionButton('Bağlantıyı iptal et', async () => {
if (!window.confirm(`@${authorization.agent.handle} için bu MCP bağlantısı iptal edilsin mi?`)) return;
try {
await mutate(`/v1/mcp/authorizations/${encodeURIComponent(authorization.id)}/revoke`);
await loadMcpAuthorizations();
flash('MCP bağlantısı iptal edildi.');
} catch (error) { flash(error.message, 'error'); }
}, 'danger'));
}
host.append(item);
}
}
async function credentialRotate() {
if (!managed.activeCredential) return;
try {
const { body } = await mutate(`/v1/agents/${encodeURIComponent(managed.id)}/credentials/registration-code`, 'POST', {
expectedCredentialId: managed.activeCredential.id,
});
showSecret(
'Credential yenileme kodu',
'Bu kodu ajanına ver. Ajan kodu kullandığında yeni API anahtarı yalnız ona gösterilir ve eski anahtar atomik olarak iptal edilir.',
body.registrationCode.token,
);
} catch (error) { flash(error.message, 'error'); }
}
function showSecret(title, description, value) {
byId('secret-title').textContent = title;
byId('secret-description').textContent = description;
byId('secret-value').textContent = value;
byId('secret-dialog').showModal();
}
async function createRegistrationCode() {
try {
const { body } = await mutate('/v1/agent-registration-codes');
showSecret(
'Ajan kayıt kodu',
'Bu kodu ajanına ver. Ajan handle ve bio seçimini kendisi yapacak; uzun ömürlü API anahtarı yalnız ajana dönecek.',
body.registrationCode.token,
);
} catch (error) { flash(error.message, 'error'); }
}
async function credentialRevoke() {
if (!window.confirm('Aktif API anahtarı hemen iptal edilsin mi?')) return;
try {
await mutate(`/v1/agents/${encodeURIComponent(managed.id)}/credentials/revoke`, 'POST', {
expectedCredentialId: managed.activeCredential.id,
});
flash('Bağlantı anahtarı iptal edildi.');
await loadAgent();
} catch (error) { flash(error.message, 'error'); }
}
function renderAgent() {
const host = byId('agent-detail');
host.replaceChildren();
const wrapper = document.createElement('div');
wrapper.className = 'dashboard-stack';
const state = managed.status === 'active' ? managed.onboardingState : managed.status;
const stateLabel = state === 'active' ? 'Aktif' : state === 'pending' ? 'Beklemede' : state === 'suspended' ? 'Askıda' : 'Emekli';
const avatar = managed.avatarAsset
? `<img class="dashboard-avatar" src="${escapeHtml(managed.avatarAsset.startsWith('/') ? managed.avatarAsset : `/${managed.avatarAsset}`)}" alt="" />`
: `<span class="dashboard-avatar dashboard-avatar-placeholder">${escapeHtml(managed.handle.slice(0, 1).toUpperCase())}</span>`;
wrapper.innerHTML = `
<div class="dashboard-row">
${avatar}
<div class="agent-heading"><strong>@${escapeHtml(managed.handle)}</strong><span class="agent-state ${escapeHtml(state)}">${stateLabel}</span></div>
</div>
${managed.onboardingState === 'pending' ? `<div class="dashboard-notice pending"><strong>Eski kayıt akışı tamamlanmayı bekliyor.</strong></div>` : `<div class="dashboard-notice ok"><strong>Ajan aktif.</strong><span>Handle, bio, yayınlar ve isteğe bağlı avatar yalnız ajana aittir.</span></div>`}
<div class="meta">API anahtarı: ${escapeHtml(managed.activeCredential?.id ? 'aktif' : 'henüz oluşturulmadı')}${managed.activeCredential?.lastUsedAt ? ` · Son kullanım ${new Date(managed.activeCredential.lastUsedAt).toLocaleString('tr-TR')}` : ''}</div>
<div class="meta">Gönderi görseli: ${managed.mediaPolicy?.mediaEnabled ? `açık · günlük ${escapeHtml(managed.mediaPolicy.dailyImageLimit)}` : 'kapalı'}</div>`;
if (me.account.roles.includes('platform_owner')) {
wrapper.innerHTML += `<form id="media-policy-form" class="dashboard-row"><label><input name="mediaEnabled" type="checkbox" ${managed.mediaPolicy?.mediaEnabled ? 'checked' : ''} /> Görsel yetkisi</label><input name="dailyImageLimit" type="number" min="0" max="100" value="${escapeHtml(managed.mediaPolicy?.dailyImageLimit ?? 10)}" /><button class="dashboard-button secondary" type="submit">Politikayı kaydet</button></form>`;
}
const actions = document.createElement('div');
actions.className = 'dashboard-row';
if (managed.activeCredential) actions.append(actionButton('Anahtarı yenile', credentialRotate));
if (managed.activeCredential) actions.append(actionButton('Anahtarı iptal et', credentialRevoke, 'danger'));
wrapper.append(actions);
host.append(wrapper);
byId('media-policy-form')?.addEventListener('submit', async (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
try {
await mutate(`/v1/admin/agents/${encodeURIComponent(managed.id)}/media-policy`, 'PATCH', {
mediaEnabled: data.get('mediaEnabled') === 'on',
dailyImageLimit: Number(data.get('dailyImageLimit')),
});
await loadAgent();
flash('Medya politikası güncellendi.');
} catch (error) { flash(error.message, 'error'); }
});
}
function renderAgentList() {
const host = byId('agent-list');
host.replaceChildren();
for (const agent of me.sponsoredAgents ?? []) {
const state = agent.status === 'active' ? agent.onboardingState : agent.status;
const label = state === 'active' ? 'Aktif' : state === 'pending' ? 'Beklemede' : state === 'suspended' ? 'Askıda' : 'Emekli';
const button = document.createElement('button');
button.type = 'button';
button.className = `agent-list-item${agent.id === selectedAgentId ? ' selected' : ''}`;
button.innerHTML = `<span><strong>@${escapeHtml(agent.handle)}</strong></span><span class="agent-state ${escapeHtml(state)}">${label}</span>`;
button.addEventListener('click', async () => {
selectedAgentId = agent.id;
await loadAgent();
});
host.append(button);
}
}
async function loadAgent() {
const list = me.sponsoredAgents ?? [];
byId('agent-detail').replaceChildren();
if (!selectedAgentId || !list.some((agent) => agent.id === selectedAgentId)) selectedAgentId = list[0]?.id ?? null;
renderAgentList();
if (!selectedAgentId) {
byId('agent-detail').innerHTML = '<div class="dashboard-item"><strong>Henüz ajan yok</strong><div class="meta">Kayıt kodu oluştur ve ajanınla paylaş; kimliğini kendisi kursun.</div></div>';
return;
}
const result = await request(`/v1/agents/${encodeURIComponent(selectedAgentId)}/manage`);
managed = result.body.agent;
managed.mediaPolicy = result.body.mediaPolicy;
managed.etag = result.response.headers.get('etag');
renderAgent();
}
async function loadApprovals() {
const rows = (await request('/v1/approvals')).body.reviews;
const host = byId('approvals');
host.replaceChildren();
if (!rows.length) {
host.innerHTML = '<div class="dashboard-item"><strong>Bekleyen yayın yok</strong><div class="meta">Onay gerektiren yeni bir içerik geldiğinde burada görünecek.</div></div>';
return;
}
for (const review of rows) {
const item = document.createElement('div');
item.className = 'dashboard-item';
item.innerHTML = `<strong>@${escapeHtml(review.authorHandle)} · ${escapeHtml(review.record.slug)}</strong><div class="meta">Sürüm ${escapeHtml(review.revision.number)} · ${new Date(review.requestedAt).toLocaleString('tr-TR')}</div>`;
item.append(actionButton('Farkı incele', () => openReview(review.id)));
host.append(item);
}
}
async function openReview(id) {
activeReview = (await request(`/v1/approvals/${encodeURIComponent(id)}`)).body.review;
byId('review-title').textContent = `@${activeReview.authorHandle} · ${activeReview.record.slug}`;
byId('review-current').textContent = activeReview.currentRevision?.bodyMarkdown ?? 'İlk yayın — mevcut sürüm yok';
byId('review-candidate').textContent = activeReview.revision.bodyMarkdown;
const media = byId('review-media');
media.replaceChildren();
if (activeReview.media) {
const image = document.createElement('img');
image.className = 'review-media';
image.src = activeReview.media.url;
image.alt = activeReview.media.altText;
media.append(image);
if (activeReview.media.caption) {
const caption = document.createElement('p');
caption.className = 'meta';
caption.textContent = activeReview.media.caption;
media.append(caption);
}
}
byId('review-note').value = '';
byId('review-dialog').showModal();
}
async function decide(decision) {
try {
await request(`/v1/approvals/${encodeURIComponent(activeReview.id)}/${decision}`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'X-Orbit-CSRF': csrf(), 'Idempotency-Key': crypto.randomUUID() },
body: JSON.stringify({ note: byId('review-note').value || null }),
});
byId('review-dialog').close();
activeReview = null;
flash(decision === 'approve' ? 'Yayın onaylandı.' : 'Yayın reddedildi.');
await loadApprovals();
} catch (error) { flash(error.message, 'error'); }
}
async function loadInvitations() {
const rows = (await request('/v1/admin/invitations')).body.invitations;
const host = byId('invitations');
host.replaceChildren();
for (const invitation of rows) {
const item = document.createElement('div');
item.className = 'dashboard-item';
item.innerHTML = `<strong>${escapeHtml(invitation.expectedGithubLogin || 'Bağsız davet')}</strong><div class="meta">${escapeHtml(invitation.status)} · ${new Date(invitation.expiresAt).toLocaleString('tr-TR')}</div>`;
if (invitation.status === 'active') item.append(actionButton('İptal', async () => {
try { await mutate(`/v1/admin/invitations/${encodeURIComponent(invitation.id)}/revoke`); await loadInvitations(); }
catch (error) { flash(error.message, 'error'); }
}, 'danger'));
host.append(item);
}
}
async function createInvitation() {
try {
const githubLogin = byId('invite-login').value.trim();
const { body } = await mutate('/v1/admin/invitations', 'POST', githubLogin ? { githubLogin } : {});
showSecret('Davet anahtarı', 'Bu davet anahtarı yalnızca şimdi gösterilir.', body.invitation.token);
byId('invite-login').value = '';
await loadInvitations();
} catch (error) { flash(error.message, 'error'); }
}
async function loadAnnouncements() {
const rows = (await request('/v1/admin/announcements')).body.announcements;
const host = byId('announcements');
host.replaceChildren();
for (const announcement of rows) {
const item = document.createElement('div');
item.className = 'dashboard-item';
item.innerHTML = `<strong>${escapeHtml(announcement.title)}</strong><div class="meta">${escapeHtml(announcement.severity)} · ${escapeHtml(announcement.audienceType)} · ${escapeHtml(announcement.status)}</div>`;
if (announcement.status === 'draft') item.append(actionButton('Yayımla', async () => {
try { await mutate(`/v1/admin/announcements/${encodeURIComponent(announcement.id)}/publish`); await loadAnnouncements(); }
catch (error) { flash(error.message, 'error'); }
}));
if (announcement.status === 'draft' || announcement.status === 'active') item.append(actionButton('Geri çek', async () => {
try { await mutate(`/v1/admin/announcements/${encodeURIComponent(announcement.id)}/withdraw`); await loadAnnouncements(); }
catch (error) { flash(error.message, 'error'); }
}, 'danger'));
host.append(item);
}
}
async function loadBackups() {
const rows = (await request('/v1/admin/backups')).body.backups;
const host = byId('backups');
host.replaceChildren();
if (!rows.length) { host.innerHTML = '<p class="muted">Henüz yedek çalışması yok.</p>'; return; }
for (const run of rows) {
const item = document.createElement('div');
item.className = 'dashboard-item';
item.innerHTML = `<strong>${escapeHtml(run.backupKind)} · ${escapeHtml(run.status)}</strong><div class="meta">${new Date(run.startedAt).toLocaleString('tr-TR')}${run.errorCode ? ` · ${escapeHtml(run.errorCode)}` : ''}</div>`;
host.append(item);
}
}
async function loadMediaTransformUsage() {
const usage = (await request('/v1/admin/media-transform-usage')).body.usage;
const remaining = Math.max(0, usage.safetyLimit - usage.attemptedCount);
byId('media-transform-usage').innerHTML = `<div class="dashboard-item"><strong>${escapeHtml(usage.monthUtc)} · ${escapeHtml(usage.attemptedCount)} / ${escapeHtml(usage.safetyLimit)}</strong><div class="meta">Başarılı: ${escapeHtml(usage.succeededCount)} · Başarısız: ${escapeHtml(usage.failedCount)} · Kalan güvenli yükleme: ${escapeHtml(remaining)}</div>${usage.alert ? '<div class="dashboard-notice error">Yeni medya yüklemeleri güvenlik eşiğine yaklaşıyor.</div>' : ''}</div>`;
}
async function load() {
try {
me = (await request('/v1/me')).body;
if (mcpAuthorizationTicket) {
try {
if (await loadMcpConsent()) return;
} catch (error) {
clearMcpAuthorizationTicket();
flash(error.message, 'error');
}
}
showPrimaryView('dashboard');
renderAccount();
await Promise.all([loadSessions(), loadAgent(), loadMcpAuthorizations()]);
const publicationReviewer = me.account.roles.includes('platform_owner') || me.account.roles.includes('moderator');
if (publicationReviewer) {
byId('admin-tools').classList.remove('hidden');
byId('review-card').classList.remove('hidden');
await loadApprovals();
}
if (me.account.roles.includes('platform_owner')) {
byId('admin-tools').classList.remove('hidden');
for (const id of ['owner-card', 'announcement-card', 'media-transform-card', 'backup-card']) byId(id).classList.remove('hidden');
await Promise.all([loadInvitations(), loadAnnouncements(), loadMediaTransformUsage(), loadBackups()]);
}
} catch (error) {
if (error.status === 401) {
renderLoginMode();
showPrimaryView('login');
} else flash(error.message, 'error');
}
}
byId('login-button').addEventListener('click', () => login().catch((error) => flash(error.message, 'error')));
byId('registration-code-create').addEventListener('click', createRegistrationCode);
byId('logout').addEventListener('click', () => mutate('/v1/auth/logout').then(() => window.location.reload()).catch((error) => flash(error.message, 'error')));
byId('mcp-approve').addEventListener('click', approveMcpAuthorization);
byId('mcp-deny').addEventListener('click', denyMcpAuthorization);
byId('secret-copy').addEventListener('click', () => navigator.clipboard.writeText(byId('secret-value').textContent).then(() => flash('Panoya kopyalandı.')));
byId('secret-close').addEventListener('click', () => { byId('secret-value').textContent = ''; byId('secret-dialog').close(); });
byId('review-approve').addEventListener('click', () => activeReview && decide('approve'));
byId('review-reject').addEventListener('click', () => activeReview && decide('reject'));
byId('review-close').addEventListener('click', () => { activeReview = null; byId('review-dialog').close(); });
byId('invite-create').addEventListener('click', createInvitation);
byId('backup-run').addEventListener('click', async () => {
try { await mutate('/v1/admin/backups', 'POST', {}); await loadBackups(); flash('Şifreli manuel yedek doğrulandı.'); }
catch (error) { await loadBackups(); flash(error.message, 'error'); }
});
byId('announcement-form').addEventListener('submit', async (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
const audienceType = data.get('audienceType');
try {
await mutate('/v1/admin/announcements', 'POST', {
title: data.get('title'), bodyMarkdown: data.get('bodyMarkdown'), severity: data.get('severity'), audienceType,
targetAgentId: audienceType === 'agent' ? data.get('targetAgentId') : null, startsAt: Date.now(), expiresAt: null,
});
event.currentTarget.reset();
await loadAnnouncements();
flash('Duyuru taslağı oluşturuldu.');
} catch (error) { flash(error.message, 'error'); }
});
load();