Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 29 additions & 11 deletions cloudflare_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,18 @@ async def repository_access(repo, request, identity, allow_private):
return token if metadata['private'] else None, metadata['private']


async def web_repository_access(repo, request, identity, allow_private):
token = identity.token if identity else getattr(environment(request), 'GITHUB_TOKEN', None)
metadata = await public_repo_exists(repo, token, allow_private=allow_private)
if metadata['private'] and not identity:
raise HTTPException(401, 'Connect your GitHub identity or supply its bearer credential for private analysis.')
raw_id = metadata.get('id')
repository_id = raw_id if (identity and type(raw_id) is int and raw_id >= 1) else None
canonical_repo = parse_repo(metadata.get('full_name') or repo) if repository_id is not None else repo
# Anonymous content reads cannot cross a later public-to-private transition.
return canonical_repo, (token if metadata['private'] else None), metadata['private'], repository_id


async def mcp_repository_access(repo, token, allow_private):
metadata = await public_repo_exists(repo, token, allow_private=allow_private)
repository_id = metadata.get('id')
Expand Down Expand Up @@ -452,7 +464,8 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False):
repo, private, repository_id = await mcp_repository_access(repo, identity.token, req.allow_private)
token = identity.token if private else None
else:
token, private = await repository_access(repo, request, identity, req.allow_private)
repo, token, private, repository_id = await web_repository_access(repo, request, identity, req.allow_private)
use_graphql = full_dashboard or (identity is not None and repository_id is not None)
gemini_override = None if full_dashboard else request.headers.get("X-Gemini-Api-Key")
jev_override = None if full_dashboard else request.headers.get("X-TypeSafe-Api-Key")
linear_override = None if full_dashboard else (request.headers.get("X-Linear-Api-Key") or "").strip() or None
Expand Down Expand Up @@ -493,14 +506,15 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False):
getattr(env, "ANALYTICS_CACHE", None)
if env and not caller_keys and not private and not is_linear and not connected_linear else None
)
cache_key = public_analysis_key(repo, full_dashboard)
cache_key = public_analysis_key(repo, full_dashboard, graphql=use_graphql)
if cache and not req.force_refresh:
saved = await cache.get(cache_key)
if saved:
cached = json.loads(saved)
if not full_dashboard:
return cached
if cached.get('repository_id') == repository_id and cached.get('analysis_id'):
if not use_graphql or cached.get('repository_id') == repository_id:
return cached
elif cached.get('repository_id') == repository_id and cached.get('analysis_id'):
snapshot = await cache.get(public_dashboard_snapshot_key(repo, cached['analysis_id']))
if snapshot:
return json.loads(snapshot)
Expand All @@ -509,7 +523,7 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False):
if is_linear:
github_coro = (
collect_dashboard_data(repo, identity.token, private, repository_id, include_issues=False)
if full_dashboard else collect_public_data(repo, token, include_issues=False)
if use_graphql else collect_public_data(repo, token, include_issues=False)
)
gh_task = asyncio.create_task(github_coro)
lin_task = asyncio.create_task(collect_linear_issues(linear_team_url, linear_key, repo=repo))
Expand All @@ -523,7 +537,7 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False):
raw["issues"] = linear_issues
else:
raw = (await collect_dashboard_data(repo, identity.token, private, repository_id)
if full_dashboard else await collect_public_data(repo, token))
if use_graphql else await collect_public_data(repo, token))
pr_bodies = [
pr.get("body")
for group in ("recent_prs", "open_prs")
Expand Down Expand Up @@ -576,11 +590,12 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False):
jev_key = jev_override or getattr(env, "TYPESAFE_API_KEY", None)
metrics['repository_visibility'] = 'private' if private else 'public'
options = {'allow_private': True} if private else {}
if use_graphql:
metrics['dashboard_source'] = 'github_graphql'
metrics['repository_id'] = repository_id
if full_dashboard:
if not private:
options['load_sources'] = partial(public_value_sources, repo, identity.token, repository_id)
metrics['dashboard_source'] = 'github_graphql'
metrics['repository_id'] = repository_id
metrics['analysis_id'] = secrets.token_urlsafe(24)
if not metrics.get('recent_stats', {}).get('total'):
metrics['p50_sle'] = metrics['p85_sle'] = None
Expand Down Expand Up @@ -621,8 +636,8 @@ def public_dashboard_snapshot_key(repo, analysis_id):
return f'{public_analysis_key(repo, True)}:{analysis_id}'


def public_analysis_key(repo, full_dashboard):
namespace = 'dashboard:v1:' if full_dashboard else ''
def public_analysis_key(repo, full_dashboard, *, graphql=False):
namespace = 'dashboard:v1:' if full_dashboard else ('graphql:v1:' if graphql else '')
return f'{METRICS_CACHE_PREFIX}{namespace}{repo.lower()}'


Expand Down Expand Up @@ -751,8 +766,11 @@ async def chat_for_identity(req, request, identity, *, full_dashboard=False):
saved = await cache.get(private_analysis_key(repo, identity, req.analysis_id, True))
else:
cache_key = (private_analysis_key(repo, identity, req.analysis_id) if identity and req.analysis_id
else session_analysis_key(repo, request, req.analysis_id) if req.analysis_id else public_analysis_key(repo, False))
else session_analysis_key(repo, request, req.analysis_id) if req.analysis_id
else public_analysis_key(repo, False, graphql=bool(identity)))
saved = await cache.get(cache_key)
if not saved and identity and not req.analysis_id:
saved = await cache.get(public_analysis_key(repo, False))
if not saved and identity and req.analysis_id and request.cookies.get(SESSION_COOKIE):
try:
await signed_in_user(request)
Expand Down
118 changes: 99 additions & 19 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,11 @@ <h3>Flowy AI Coach</h3>
if (setupHadFocus) document.getElementById('chat-input').focus();

// Welcome message in chat
addChatMessage('assistant', `🎉 **Repository loaded: \`${data.repo}\`**\n\nAsk me about cycle time, aging work, or throughput. Review timing and batch size are not yet available from this hosted data source.`);
const hasRichData = data.dashboard_source === 'github_graphql' || data.pr_size_scatter_points?.some(point => point.x > 0);
const sourceNote = hasRichData
? 'Ask me about cycle time, PR size correlation, aging work, or throughput.'
: 'Ask me about cycle time, aging work, or throughput. Sign in with GitHub to include PR size and review timing.';
addChatMessage('assistant', `🎉 **Repository loaded: \`${data.repo}\`**\n\n${sourceNote}`);

} catch(e) {
if (savedRepository && response && ![401, 403, 409].includes(response.status) && !repoInput.value) {
Expand Down Expand Up @@ -1595,29 +1599,101 @@ <h3>Flowy AI Coach</h3>
if (hasAging) {
if (ageTitle) ageTitle.textContent = 'Work Item Aging by Status';
const annotations = {};
if (aging.p50_days != null) {
annotations.p50line = {
type:'line', yMin:aging.p50_days, yMax:aging.p50_days,
borderColor:'rgba(6,182,212,.7)', borderWidth:1.5, borderDash:[5,4],
label:{content:`P50: ${aging.p50_days.toFixed(1)}d`, display:true, position:'end', color:'#67e8f9', font:{size:11}}
};
}
if (aging.p85_days != null) {
annotations.p85line = {
type:'line', yMin:aging.p85_days, yMax:aging.p85_days,
borderColor:'rgba(245,158,11,.8)', borderWidth:2,
label:{content:`P85: ${aging.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fcd34d', font:{size:11}}
};
const stageStats = new Map(
(aging.stage_percentiles || [])
.filter(sp => sp && sp.stage)
.map(sp => [sp.stage, sp])
);
const hasStagePercentiles = Array.from(stageStats.values()).some(sp => sp.p50_days != null || sp.p85_days != null);
const maxItemY = Math.max(0, ...aging.items.map(item => Number(item.age_days) || 0));
const maxP85 = Math.max(
0,
aging.p85_days || 0,
...Array.from(stageStats.values()).map(sp => Number(sp.p85_days) || 0)
);
const chartTop = Math.ceil(Math.max(maxItemY, maxP85, 1) * 1.15);

if (hasStagePercentiles) {
aging.stages.forEach((stage, idx) => {
const sp = stageStats.get(stage);
if (!sp || sp.p50_days == null || sp.p85_days == null) return;
const xMin = idx - 0.44;
const xMax = idx + 0.44;
annotations[`band_green_${idx}`] = {
type:'box', xMin, xMax, yMin:0, yMax:sp.p50_days,
backgroundColor:'rgba(16,185,129,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw',
};
annotations[`band_yellow_${idx}`] = {
type:'box', xMin, xMax, yMin:sp.p50_days, yMax:sp.p85_days,
backgroundColor:'rgba(245,158,11,.18)', borderWidth:0, drawTime:'beforeDatasetsDraw',
};
annotations[`band_red_${idx}`] = {
type:'box', xMin, xMax, yMin:sp.p85_days, yMax:chartTop,
backgroundColor:'rgba(244,63,94,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw',
};
annotations[`p50_line_${idx}`] = {
type:'line', xMin, xMax, yMin:sp.p50_days, yMax:sp.p50_days,
borderColor:'rgba(16,185,129,.85)', borderWidth:1.5, borderDash:[4,3],
label:{content:`P50 ${sp.p50_days.toFixed(1)}d`, display:true, position:sp.p50_days === sp.p85_days ? 'start' : 'end', color:'#6ee7b7', backgroundColor:'rgba(15,23,42,.75)', font:{size:10}, padding:2}
};
annotations[`p85_line_${idx}`] = {
type:'line', xMin, xMax, yMin:sp.p85_days, yMax:sp.p85_days,
borderColor:'rgba(244,63,94,.9)', borderWidth:2,
label:{content:`P85 ${sp.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fda4af', backgroundColor:'rgba(15,23,42,.75)', font:{size:10}, padding:2}
};
});
} else {
if (aging.p50_days != null) {
annotations.band_green_global = {
type:'box', yMin:0, yMax:aging.p50_days,
backgroundColor:'rgba(16,185,129,.14)', borderWidth:0, drawTime:'beforeDatasetsDraw',
};
annotations.p50line = {
type:'line', yMin:aging.p50_days, yMax:aging.p50_days,
borderColor:'rgba(16,185,129,.85)', borderWidth:1.5, borderDash:[5,4],
label:{content:`P50: ${aging.p50_days.toFixed(1)}d`, display:true, position:'end', color:'#6ee7b7', font:{size:11}}
};
}
if (aging.p85_days != null) {
if (aging.p50_days != null) {
annotations.band_yellow_global = {
type:'box', yMin:aging.p50_days, yMax:aging.p85_days,
backgroundColor:'rgba(245,158,11,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw',
};
}
annotations.band_red_global = {
type:'box', yMin:aging.p85_days, yMax:chartTop,
backgroundColor:'rgba(244,63,94,.14)', borderWidth:0, drawTime:'beforeDatasetsDraw',
};
annotations.p85line = {
type:'line', yMin:aging.p85_days, yMax:aging.p85_days,
borderColor:'rgba(244,63,94,.9)', borderWidth:2,
label:{content:`P85: ${aging.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fda4af', font:{size:11}}
};
}
}

const pointColors = aging.items.map(item => {
const sp = stageStats.get(item.stage);
const p50 = hasStagePercentiles ? sp?.p50_days : aging.p50_days;
const p85 = hasStagePercentiles ? sp?.p85_days : aging.p85_days;
if (p50 == null && p85 == null) return 'rgba(148,163,184,.95)';
if (p85 != null && item.age_days > p85) return 'rgba(244,63,94,.95)';
if (p50 != null && item.age_days > p50) return 'rgba(245,158,11,.95)';
return 'rgba(16,185,129,.95)';
});

mkChart('chart-issue-age', {
type: 'scatter',
data: {
labels: aging.stages,
datasets: [{
label: 'Open issues',
data: aging.items.map(item => ({x: item.stage, y: item.age_days, identifier: item.identifier, title: item.title})),
backgroundColor: 'rgba(245,158,11,.8)',
pointRadius: 5, pointHoverRadius: 9,
backgroundColor: pointColors,
borderColor: '#f8fafc',
borderWidth: 1.25,
pointRadius: 5.5, pointHoverRadius: 9,
}]
},
options: {
Expand All @@ -1629,14 +1705,18 @@ <h3>Flowy AI Coach</h3>
callbacks:{
label: ctx => {
const d = ctx.raw;
return [`${d.identifier}: ${(d.title || '').slice(0, 50)}`, `${d.x} · ${d.y?.toFixed(1)} days`];
const sp = stageStats.get(d.x);
const pace = sp && sp.p50_days != null && sp.p85_days != null
? ` (stage P50 ${sp.p50_days.toFixed(1)}d · P85 ${sp.p85_days.toFixed(1)}d, n=${sp.n})`
: '';
return [`${d.identifier}: ${(d.title || '').slice(0, 50)}`, `${d.x} · ${d.y?.toFixed(1)} days${pace}`];
}
}
}
},
scales:{
x:{ type:'category', labels: aging.stages, grid:{color:'rgba(255,255,255,.04)'} },
y:{ grid:{color:'rgba(255,255,255,.04)'}, title:{display:true, text:'Age (days)', color:'#64748b'}, beginAtZero:true }
x:{ type:'category', labels: aging.stages, offset:true, grid:{color:'rgba(255,255,255,.04)'} },
y:{ grid:{color:'rgba(255,255,255,.04)'}, title:{display:true, text:'Age since active start (days)', color:'#64748b'}, beginAtZero:true, max:chartTop }
}
}
});
Expand Down
Loading
Loading