from pathlib import Path
from uuid import uuid4
from io import BytesIO
from base64 import b64encode
from html import escape
from hashlib import sha256
import json
from PIL import Image
from nbinlineai.browser_receipt import MediaClip
from nbinlineai.tools import (setup_share, start_share, capture_screen,
start_recording, stop_share, annotate_image, release_media,
attach_media, operation_status)
report_folder = Path.cwd() / f'screen-bug-report-{uuid4().hex[:10]}'
report_folder.mkdir()
def done(receipt, label):
print(label, receipt.status, receipt.operation_id)
if receipt.status != 'completed':
raise RuntimeError(f'{label} is not complete; inspect again after the browser finishes: {receipt.error}')
return receipt.resultApplication: evidence-backed screen bug report
Application: evidence-backed screen bug report
This notebook captures a screen still and a bounded video of a bug, marks the still, and writes a self-contained HTML bug report with reproduction notes. A later AI question can inspect the marked still only after you explicitly confirm its attachment. The model does not receive the screen recording or a transcript; its tool result contains descriptors, not pixels. Keep private windows out of view. Run in nbinlineai JupyterLab with a live Python kernel. A configured model is needed for the optional AI review and may incur charges.
Browser capture calls return mutable receipts immediately. Run their separate inspection cells after the visible operation finishes. No cell blocks or loops waiting for the browser. save_to=None avoids server-relative generated paths; the report is written by Python to a unique owned folder under the kernel working directory. That folder is a local output location, not an assumption about Jupyter’s server root.
Published nbinlineai 0.1.18 includes these media APIs, which shipped in 0.1.16. Install or upgrade nbinlineai in the JupyterLab server environment. Restart JupyterLab, reload the browser, then restart the selected Python kernel and rerun imports. Use your notebook’s selected image-capable connection for image questions.
Saved worked run: The published results use a disposable synthetic search-demo canvas in an isolated headless browser. No laptop screen, physical camera or microphone was accessed. The screenshot and video were genuinely captured from that canvas using the notebook tools, and the AI responses came from the configured live ChatGPT connection. They illustrate the workflow; they do not establish a real product defect. When you rerun this notebook normally, select your own intended surface.
Record the reproduction facts
Edit these example fields to describe a real issue before capturing. Keep sensitive data out of the selected screen surface. Recording is eight seconds and may stop sooner if you end sharing. The report does not infer what the bug is from video.
bug_title = 'Search demo: empty result panel'
environment = 'Disposable 1000x600 synthetic canvas; isolated Chromium background run'
reproduction_steps = [
'Open the disposable search-demo fixture.',
'Use its illustrated sample notebook search term.',
'Inspect the illustrated empty result panel after the Search action.',
]
expected = 'The illustrative search should show results or a clear empty-state message.'
actual = 'The fixture depicts an empty result panel; no actual product defect was reproduced.'
impact = 'Demonstrates collecting and reviewing an evidence-backed bug report.'Capture the symptom
Arrange the shared surface so the issue is visible. Take the still, then perform the reproduction during the eight-second video. This path records video without display audio. The two captured media descriptors are references; the original direct receipts later hold a Pillow image and a MediaClip. A status snapshot would contain only metadata.
still_receipt = capture_screen(source_id=screen_source_id, save_to=None, max_size=1280)
still_receiptBrowserReceipt(operation_id=None, status='running')
still = done(still_receipt, 'screen still')
assert isinstance(still, Image.Image)
print('Still dimensions:', still.size, 'managed ID:', still_receipt.media['media_id'])
display(still)screen still completed N3jpphrI6kPKFA0dldKxMXm4WZ-y9DdG
Still dimensions: (1000, 600) managed ID: LnJFDbbT0PZAjrzOqGYC0LrGtyCyyDwZ
video_receipt = start_recording(screen_source_id, save_to=None, duration=8)
video_receipt # Reproduce the issue on the shared surface now.BrowserReceipt(operation_id=None, status='running')
video = done(video_receipt, 'screen recording')
assert isinstance(video, MediaClip) and video.mime_type.startswith('video/')
print('Video:', video.mime_type, len(video.data), 'bytes', video.duration_seconds, 'seconds')screen recording completed _0jKP3nL2vv73yaD1yrL363ftyveKKdh
Video: video/webm;codecs=vp9 50344 bytes 8 seconds
Mark the issue on a derivative still
Review the displayed still above. Edit target_fraction so its (left, top, width, height) fractions surround the actual symptom, measured against that still. The example selects its center region. The code computes bounded pixel coordinates and creates a new PNG; it does not alter the source. Do not use redaction as a substitute for excluding private content before screen sharing.
target_fraction = (0.03, 0.40, 0.85, 0.43) # Saved fixture: surround the illustrated symptom and empty result panel.
left, top, width_fraction, height_fraction = target_fraction
assert 0 <= left < 1 and 0 <= top < 1 and 0 < width_fraction <= 1 and 0 < height_fraction <= 1
assert left + width_fraction <= 1 and top + height_fraction <= 1
w, h = still.size
x, y = round(left * w), round(top * h)
box_w, box_h = max(1, round(width_fraction * w)), max(1, round(height_fraction * h))
box_w, box_h = min(box_w, w - x), min(box_h, h - y)
assert box_w > 0 and box_h > 0
annotations = [
{'type': 'rectangle', 'x': x, 'y': y, 'width': box_w, 'height': box_h,
'color': '#ff3b30', 'line_width': 5},
{'type': 'text', 'x': 8, 'y': 8, 'text': 'Reported symptom',
'color': '#ff3b30', 'font_size': 20},
]
print('Marking pixel box:', (x, y, box_w, box_h))Marking pixel box: (30, 240, 850, 258)
annotated_receipt = annotate_image({'media_id': still_receipt.media['media_id']}, annotations, save_to=None)
annotated_receiptBrowserReceipt(operation_id=None, status='running')
annotated_still = done(annotated_receipt, 'annotated still')
assert isinstance(annotated_still, Image.Image)
annotated_ref = {'media_id': annotated_receipt.media['media_id']}
print('Derivative:', annotated_still.size, annotated_receipt.media['sha256'])
display(annotated_still)annotated still completed onG_GXV5H4PI79Tg1lU5SwpIekmh0Dfk
Derivative: (1000, 600) 6c6ca53429565f0d2d550603d38a88317b938d6e13366f3cca5bb68c81dc8c32
Export the real report
The HTML embeds both stills and the actual video bytes. It also lists the typed reproduction steps, expected and actual behavior, and SHA-256 hashes, so a reviewer can compare the evidence files. The report contains no model-generated claim. Open the final HTML locally and check the video plays in a browser that supports the captured MIME type.
def png_bytes(image):
buf = BytesIO()
image.save(buf, format='PNG')
return buf.getvalue()
original_png = png_bytes(still)
marked_png = png_bytes(annotated_still)
(report_folder / 'original.png').write_bytes(original_png)
(report_folder / 'marked.png').write_bytes(marked_png)
video_ext = {'video/webm': '.webm', 'video/mp4': '.mp4'}.get(video.mime_type.split(';', 1)[0])
if video_ext is None:
raise ValueError(f'Unsupported video MIME for a portable copy: {video.mime_type}')
(report_folder / f'recording{video_ext}').write_bytes(video.data)
manifest = {
'title': bug_title, 'environment': environment, 'steps': reproduction_steps,
'expected': expected, 'actual': actual, 'impact': impact,
'evidence': {
'original_png': {'sha256': sha256(original_png).hexdigest(), 'bytes': len(original_png)},
'marked_png': {'sha256': sha256(marked_png).hexdigest(), 'bytes': len(marked_png)},
'recording': {'sha256': sha256(video.data).hexdigest(), 'bytes': len(video.data),
'mime_type': video.mime_type, 'duration_seconds': video.duration_seconds},
},
}
(report_folder / 'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
uri = lambda raw, mime: f'data:{mime};base64,{b64encode(raw).decode("ascii")}'
safe = lambda value: escape(str(value), quote=True)
step_items = ''.join(f'<li>{safe(item)}</li>' for item in reproduction_steps)
style = '<style>body{max-width:950px;margin:auto;padding:2rem;font:18px system-ui;line-height:1.5;color:#182b3d}img,video{display:block;max-width:100%;margin:1rem 0}section{padding:1rem 0;border-top:1px solid #aaa}code{overflow-wrap:anywhere}small{color:#456}@media print{video{display:none}}</style>'
html = ('<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
'<title>'+safe(bug_title)+'</title>'+style+'<main><h1>'+safe(bug_title)+'</h1>'
'<p><strong>Environment:</strong> '+safe(environment)+'</p><p><strong>Impact:</strong> '+safe(impact)+'</p>'
'<section><h2>Reproduce</h2><ol>'+step_items+'</ol><p><strong>Expected:</strong> '+safe(expected)+'</p>'
'<p><strong>Actual:</strong> '+safe(actual)+'</p></section>'
'<section><h2>Marked still</h2><img alt="Marked screenshot" src="'+uri(marked_png,'image/png')+'"></section>'
'<section><h2>Original still</h2><img alt="Original screenshot" src="'+uri(original_png,'image/png')+'"></section>'
'<section><h2>Screen recording</h2><video controls playsinline src="'+uri(video.data,video.mime_type)+'"></video>'
'<p><small>Captured video; no transcription or automatic interpretation.</small></p></section>'
'<section><h2>Evidence hashes</h2><p>Original PNG: <code>'+manifest['evidence']['original_png']['sha256']+'</code><br>'
'Marked PNG: <code>'+manifest['evidence']['marked_png']['sha256']+'</code><br>'
'Recording: <code>'+manifest['evidence']['recording']['sha256']+'</code></p></section></main></html>')
report_path = report_folder / 'bug-report.html'
report_path.write_text(html, encoding='utf-8')
print('Portable report:', report_path, 'size:', report_path.stat().st_size, 'bytes')Portable report: [temporary local path] size: 159010 bytes
Optional AI review of the marked still
The following AI tool conversation offers attach_media and operation_status. Its first question asks for an attachment to the stable target question ID. Review the confirmation preview and click Attach image only if you want the model to see those still-image pixels. A call does not run the target question. The status question checks confirmation; run the target question only afterward. Its image attachment is independent of the exported report.
The video cannot be attached for model viewing here, and the model cannot infer it from video_receipt.media.
The $ reference is used in the attachment question itself, because only a current question can look up live Python values. The two unique declared tools are well below the 20-reference limit.
Call &attach_media with media from $annotated_ref, question_cell_id="bug-ai-review", and detail="auto". Report the immediate attachment operation ID and state only. Ask me to inspect the preview and explicitly click Attach image; do not run the review question or claim confirmation yet.
Attachment operation xX-eaZRGeEkssvVumbHqeDyK4PDTHhRd is waiting_for_user. Please inspect the preview and explicitly click Attach image.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
| Tool | Result state | Submitted arguments | Observed result |
|---|---|---|---|
attach_media |
receipt accepted | {“media”:{“media_id”:“HrZm7OJFPsILgkCEQeRYUN8gpfYFV3vP”},“question_cell_id”:“bug-ai-review”,“detail”:“auto”} | {“operation_id”:“xX-eaZRGeEkssvVumbHqeDyK4PDTHhRd”,“status”:“waiting_for_user”} |
After I click Attach image, call &operation_status with the exact attachment operation ID from the previous answer. Report the lookup state and target state, and say whether the target confirmed question_cell_id="bug-ai-review". If it is still waiting, stop and retry later.
Lookup state: completed. Target state: confirmed (question_cell_id="bug-ai-review").
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
| Tool | Result state | Submitted arguments | Observed result |
|---|---|---|---|
operation_status |
completed | {“operation_id”:“xX-eaZRGeEkssvVumbHqeDyK4PDTHhRd”} | {“operation_id”:“xX-eaZRGeEkssvVumbHqeDyK4PDTHhRd”,“status”:“completed”,“result”:{“confirmed”:true,“question_cell_id”:“bug-ai-review”,“image_sha256”:“6c6ca53429565f0d2d550603d38a88317b938d6e13366f3cca5bb68c81dc8c32”,“detail”:“auto”}} |
Inspect only the attached marked still. Suggest a concise bug-report title and up to three visible observations. Distinguish visible evidence from the typed steps and expected behavior above. You cannot inspect the screen recording or hear audio here; say so if asked. Do not invent a reproduction outcome.
Suggested title: Synthetic search demo shows an empty result panel
Visible in the marked still:
- The search field contains “sample notebook,” beside a Search button.
- The outlined result panel is blank.
- On-screen text says “Search clicked” and labels the fixture illustrative; the still alone does not verify that a search ran.
The reproduction steps and expected behavior are typed notes, not independently established by this image.
Clean up managed browser media
After confirming the optional image question and checking the exported report, release only this notebook’s three managed image/video IDs. The HTML, manifest and Python files remain in report_folder. Remove the image attachment with its question UI before release if you intend to rerun the model review later.
release_receipts = [release_media(r.media['media_id']) for r in
(still_receipt, video_receipt, annotated_receipt) if isinstance(r.media, dict) and r.media.get('media_id')]for receipt in release_receipts:
print('Release:', receipt.status, receipt.error)
print('Report kept:', report_path)Release: completed None
Release: completed None
Release: completed None
Report kept: [temporary local path]