"""Physical-input responsiveness during the real 2.29 MB Monaco script.
Never creates a model, evaluates guest JS, substitutes a host browser or pauses
the VM during a timing span. A successful run must observe UI acknowledgements
between the corresponding script BEGIN and END, then verify the real model.
"""
import hashlib
import json
import re
import time
from pathlib import Path
from PIL import Image
from NativeCSharpEvidence import CSHARP_PROOF, csharp_frame_stats, verify_readback, website_palette
CORE_BEGIN = 'XFE_BROWSER_SCRIPT_BEGIN|0.52.2/Core/EditorCore.js|'
CORE_END = 'XFE_BROWSER_SCRIPT_END|0.52.2/Core/EditorCore.js|'
MODEL = re.compile(r'XFE_MONACO_VALUE_BEGIN\r?\n(.*?)\r?\nXFE_MONACO_VALUE_END', re.S)
EXPECTED = ('using System;\nnamespace XFEstudio;\npublic sealed class Preview\n{\n'
' public string Message { get; set; } = "Hello XFESystem";\n'
' public static int Run(int value)\n {\n'
' if (value > 0) return Math.Max(value, 42);\n'
' Console.WriteLine("Ready");\n return 0;\n }\n}')
def run_editor_responsiveness(qmp, read_log, wait_log, screenshot, width, height, scale, pointer):
result = {'Kind': 'NativeCSharpEditorDuringMonacoInitialization', 'Passed': False,
'GpuExecutionClaimed': False, 'HostJavaScriptInjection': False,
'Input': 'QMP physical keyboard/mouse, actual file and official Monaco',
'MaximumShortcutResponseSeconds': 1.0, 'Samples': []}
folder = None
def move(x, y):
target = [round(x * scale), round(y * scale)]
while pointer != target:
dx = max(-80, min(80, target[0] - pointer[0]))
dy = max(-80, min(80, target[1] - pointer[1]))
qmp('input-send-event', {'events': [{'type': 'rel', 'data': {'axis': 'x', 'value': dx}},
{'type': 'rel', 'data': {'axis': 'y', 'value': dy}}]})
pointer[0] += dx; pointer[1] += dy
time.sleep(.012)
def button(down):
qmp('input-send-event', {'events': [{'type': 'btn', 'data': {'down': down, 'button': 'left'}}]})
def click(x, y):
move(x, y); button(True); time.sleep(.06); button(False)
def safe():
log = read_log()
assert not any(marker in log for marker in ('CPU EXCEPTION:', '[FAILFAST]', '*** UNHANDLED EXCEPTION')), log[-4000:]
return log
def shortcut(code, expected, after, timeout=90):
started = time.monotonic()
qmp('human-monitor-command', {'command-line': 'sendkey ' + code})
wait_log(expected, after, timeout)
ended = time.monotonic()
log = safe()
acknowledgement = log.index(expected, after)
script_end = log.find(CORE_END, result['CoreScriptBeginSerialOffset'])
sample = {'Shortcut': code, 'HostInputToAcknowledgementSeconds': ended - started,
'AcknowledgementSerialOffset': acknowledgement,
'AcknowledgedBeforeCoreScriptEnd': script_end < 0 or acknowledgement < script_end,
'UnderOneSecond': ended - started < 1.0}
result['Samples'].append(sample)
return sample
try:
start = len(read_log()); click(60, 120)
wait_log('XFE_DESKTOP_ACTIVE|Files', start, 30)
folder = Path(screenshot('EditorResponsiveness-Files')).parent
start = len(read_log()); opened = time.monotonic(); click(220, 286)
# Serial writes can be observed halfway through a numeric field. A
# prefix match or splitlines() at EOF would silently truncate Frequency.
source_pattern = re.compile(r'^XFE_EDITOR_BACKGROUND\|SourcePresented\|Window\|2\|[^\r\n]+\r?\n', re.M)
deadline = time.monotonic() + 90
source_match = None
while time.monotonic() < deadline:
source_match = source_pattern.search(safe()[start:])
if source_match:
break
time.sleep(.005)
assert source_match, 'No complete source-presentation serial record'
observed = time.monotonic() - opened
source_line = source_match.group(0).rstrip('\r\n')
parts = source_line.split('|')
source_proof = dict(zip(parts[2::2], parts[3::2]))
fingerprint = 14695981039346656037
for value in EXPECTED.encode('utf-16-le'):
fingerprint = ((fingerprint ^ value) * 1099511628211) & ((1 << 64) - 1)
assert source_proof['FingerprintAlgorithm'] == 'UTF16LE-FNV1a64'
assert source_proof['SourceFingerprint'] == f'{fingerprint:016x}'
assert int(source_proof['SourceCharacters']) == len(EXPECTED)
assert int(source_proof['VisibleNonEmptyLines']) >= 10
source_frame = Path(screenshot('EditorResponsiveness-FirstSource'))
source_bands = []
with Image.open(source_frame) as image:
for row in (0, 4, 7):
x = int(source_proof['TextX']); y = int(source_proof['TextY']) + row * 20
line = EXPECTED.split('\n')[row]
bounds = tuple(round(value * scale) for value in (x, y, x + min(len(line) * 8, 740), y + 20))
band = image.crop(bounds).convert('RGB')
ink, columns = 0, set()
for yy in range(band.height):
for xx in range(band.width):
red, green, blue = band.getpixel((xx, yy))
if .2126 * red + .7152 * green + .0722 * blue >= 78:
ink += 1; columns.add(xx)
sample = {'SourceLine': row + 1, 'Text': line, 'NativeBounds': list(bounds), 'InkPixels': ink,
'InkColumns': len(columns), 'InkFraction': ink / max(1, band.width * band.height)}
assert ink >= 30 * scale * scale and len(columns) >= 24 * scale and .015 <= sample['InkFraction'] <= .65, sample
source_bands.append(sample)
elapsed = int(source_proof['ElapsedTicks']) / int(source_proof['Frequency'])
result['FirstSourcePresentation'] = {'NativeQueueToPresentedSeconds': elapsed,
'HostOpenToMarkerSeconds': observed, 'UnderOneSecond': elapsed < 1 and observed < 1,
'Proof': source_proof, 'Path': str(source_frame), 'Sha256': hashlib.sha256(source_frame.read_bytes()).hexdigest(),
'ActualGlyphBands': source_bands, 'Meaning': 'Real editable source first frame; full Monaco readiness is measured separately.'}
wait_log(CORE_BEGIN, start, 90)
script_begin = read_log().index(CORE_BEGIN, start)
result['CoreScriptBeginSerialOffset'] = script_begin
result['ClickToCoreScriptBeginSeconds'] = time.monotonic() - opened
# Send only after the largest original editor script has really begun.
before = len(read_log())
hidden = shortcut('meta_l-d', 'XFE_DESKTOP_FLAGS|0|0|Active|0', before)
result['HiddenFrame'] = str(screenshot('EditorResponsiveness-Hidden'))
# Acknowledge at least the hide operation during execution; restoration
# is also timed, even if a fast machine has already finished the script.
before = len(read_log())
shortcut('meta_l-d', 'XFE_DESKTOP_FLAGS|0|0|Active|2', before)
assert hidden['AcknowledgedBeforeCoreScriptEnd'], 'Win+D was queued until the actual Monaco script finished'
assert all(sample['UnderOneSecond'] for sample in result['Samples']), result['Samples']
workers = list(re.finditer(r'XFE_EDITOR_BACKGROUND\|WorkBegin\|Window\|2\|Generation\|(\d+)\|UiThread\|(\d+)\|Thread\|(\d+)\|', read_log()[start:]))
assert workers, 'No actual editor background worker began'
generation, ui_thread, worker_thread = map(int, workers[-1].groups())
assert ui_thread > 0 and worker_thread > 0 and ui_thread != worker_thread, ('Monaco did not run on a distinct scheduled thread', ui_thread, worker_thread)
result['ActualWorker'] = {'Generation': generation, 'UiThread': ui_thread, 'WorkerThread': worker_thread}
# Exercise the handoff/first UI font-layout period too. Moving only the
# script parse off-thread must not hide a later desktop stall.
wait_log('XFE_EDITOR_BACKGROUND|Prepared|Window|2|', start, 120)
wait_log('XFE_EDITOR_BACKGROUND|Ready|Window|2|', start, 120)
before = len(read_log())
handoff_hide = shortcut('meta_l-d', 'XFE_DESKTOP_FLAGS|0|0|Active|0', before)
before = len(read_log())
handoff_restore = shortcut('meta_l-d', 'XFE_DESKTOP_FLAGS|0|0|Active|2', before)
result['HandoffShortcuts'] = [handoff_hide, handoff_restore]
assert handoff_hide['UnderOneSecond'] and handoff_restore['UnderOneSecond'], result['HandoffShortcuts']
deadline = time.monotonic() + 120
proof = None
palette = website_palette()
last_error = 'No actual C# model'
while time.monotonic() < deadline:
log = safe()[start:]
for match in reversed(list(CSHARP_PROOF.finditer(log))):
candidate = json.loads(match.group(1))
if candidate.get('Language') != 'csharp' or candidate.get('ModelValue') != EXPECTED:
continue
try:
checked = verify_readback(candidate, palette)
proof = candidate
result['WebsiteCSharpSpanVerification'] = checked
except (AssertionError, KeyError, ValueError) as error:
last_error = str(error)
break
if proof:
break
time.sleep(.05)
assert proof, last_error
assert ('XFE_EDITOR_BACKGROUND|Ready|Window|2|Generation|' + str(generation) + '|') in read_log()[start:], 'The completed page was not handed back to the UI'
assert any(match.group(1).replace('\r', '') == EXPECTED for match in MODEL.finditer(read_log()[start:])), 'Actual Monaco getValue did not match the file'
result['ClickToMonacoReadySeconds'] = time.monotonic() - opened
result['ActualModelSha256'] = hashlib.sha256(EXPECTED.encode()).hexdigest()
result['ActualMonacoReadback'] = proof
# Geometry comes from the actual acknowledged editor window.
rows = list(re.finditer(r'XFE_WINDOW_STATE\|2\|Editor\|(-?\d+)\|(-?\d+)\|(\d+)\|(\d+)\|0\|', read_log()[start:]))
assert rows, 'Missing real editor geometry'
x, y, w, h = (int(value) for value in rows[-1].groups())
viewport = (x + 2, y + 67, w - 4, h - 96)
move(width / scale - 140, height / scale - 100)
deadline = time.monotonic() + 45
while True:
frame = Path(screenshot('EditorResponsiveness-Ready'))
with Image.open(frame) as pixels:
ink = csharp_frame_stats(pixels, viewport, scale, EXPECTED)
if ink['Passed'] or time.monotonic() >= deadline:
break
time.sleep(.15)
assert ink['Passed'], ink
result['ActualFramebuffer'] = {'Path': str(frame), 'Sha256': hashlib.sha256(frame.read_bytes()).hexdigest(), **ink}
# Keep the real focused editor alive through continued timer/layout/GC
# activity, rather than closing immediately after its first good frame.
stability_start = len(read_log()); stability_clock = time.monotonic()
stability_deadline = stability_clock + 30
while time.monotonic() < stability_deadline:
safe()
time.sleep(.05)
samples = []
for match in re.finditer(r'^XFE_RENDER_STATS\|[^\r\n]+\r?\n', read_log()[stability_start:], re.M):
fields = match.group(0).strip().split('|')
values = dict(zip(fields[2::2], fields[3::2]))
if 'RawFreePages' in values and 'RawTotalPages' in values:
samples.append({'Timestamp': int(fields[1]), 'FreePages': int(values['RawFreePages']), 'TotalPages': int(values['RawTotalPages'])})
assert len(samples) >= 10, 'No continuing native UI/raw-memory heartbeat during editor stability observation'
result['FocusedEditorObservation'] = {'Seconds': time.monotonic() - stability_clock, 'RawPageSamples': samples,
'MinimumRawFreePages': min(sample['FreePages'] for sample in samples), 'NoGuestHaltObserved': True,
'Meaning': 'Bounded observation of the real editor; not an unlimited memory/leak or isolation guarantee.'}
before = len(read_log()); qmp('human-monitor-command', {'command-line': 'sendkey ctrl-s'})
wait_log('XFE_DESKTOP_SAVED|X:\\Users\\Default\\Documents\\ZCSharp.cs|' + str(len(EXPECTED)), before, 30)
result['SavePreservedSource'] = True
before = len(read_log()); qmp('human-monitor-command', {'command-line': 'sendkey alt-f4'})
wait_log('XFE_DESKTOP_ACTIVE|Files', before, 30)
before = len(read_log()); click(220, 286)
wait_log('XFE_EDITOR_BACKGROUND|WorkBegin|Window|3|', before, 90)
close_start = len(read_log()); close_time = time.monotonic()
qmp('human-monitor-command', {'command-line': 'sendkey alt-f4'})
wait_log('XFE_DESKTOP_ACTIVE|Files', close_start, 30)
close_elapsed = time.monotonic() - close_time
wait_log('XFE_EDITOR_BACKGROUND|Cancelled|Window|3|', before, 90)
assert 'XFE_EDITOR_BACKGROUND|Ready|Window|3|' not in read_log()[before:], 'A closed editor accepted a stale worker result'
assert close_elapsed < 1, ('Closing during actual editor preparation stalled the desktop', close_elapsed)
result['CloseDuringPreparation'] = {'InputToAcknowledgementSeconds': close_elapsed, 'CancelledWorkerObserved': True,
'NoReadyAfterClose': True, 'Passed': True}
assert result['FirstSourcePresentation']['UnderOneSecond'], result['FirstSourcePresentation']
result['Passed'] = True
return result
except Exception as error:
result['Failure'] = str(error)
raise
finally:
if folder:
(folder / 'EditorResponsiveness.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
"""Physical-input responsiveness during the real 2.29 MB Monaco script.
Never creates a model, evaluates guest JS, substitutes a host browser or pauses
the VM during a timing span. A successful run must observe UI acknowledgements
between the corresponding script BEGIN and END, then verify the real model.
"""
import hashlib
import json
import re
import time
from pathlib import Path
from PIL import Image
from NativeCSharpEvidence import CSHARP_PROOF, csharp_frame_stats, verify_readback, website_palette
CORE_BEGIN = 'XFE_BROWSER_SCRIPT_BEGIN|0.52.2/Core/EditorCore.js|'
CORE_END = 'XFE_BROWSER_SCRIPT_END|0.52.2/Core/EditorCore.js|'
MODEL = re.compile(r'XFE_MONACO_VALUE_BEGIN\r?\n(.*?)\r?\nXFE_MONACO_VALUE_END', re.S)
EXPECTED = ('using System;\nnamespace XFEstudio;\npublic sealed class Preview\n{\n'
' public string Message { get; set; } = "Hello XFESystem";\n'
' public static int Run(int value)\n {\n'
' if (value > 0) return Math.Max(value, 42);\n'
' Console.WriteLine("Ready");\n return 0;\n }\n}')
def run_editor_responsiveness(qmp, read_log, wait_log, screenshot, width, height, scale, pointer):
result = {'Kind': 'NativeCSharpEditorDuringMonacoInitialization', 'Passed': False,
'GpuExecutionClaimed': False, 'HostJavaScriptInjection': False,
'Input': 'QMP physical keyboard/mouse, actual file and official Monaco',
'MaximumShortcutResponseSeconds': 1.0, 'Samples': []}
folder = None
def move(x, y):
target = [round(x * scale), round(y * scale)]
while pointer != target:
dx = max(-80, min(80, target[0] - pointer[0]))
dy = max(-80, min(80, target[1] - pointer[1]))
qmp('input-send-event', {'events': [{'type': 'rel', 'data': {'axis': 'x', 'value': dx}},
{'type': 'rel', 'data': {'axis': 'y', 'value': dy}}]})
pointer[0] += dx; pointer[1] += dy
time.sleep(.012)
def button(down):
qmp('input-send-event', {'events': [{'type': 'btn', 'data': {'down': down, 'button': 'left'}}]})
def click(x, y):
move(x, y); button(True); time.sleep(.06); button(False)
def safe():
log = read_log()
assert not any(marker in log for marker in ('CPU EXCEPTION:', '[FAILFAST]', '*** UNHANDLED EXCEPTION')), log[-4000:]
return log
def shortcut(code, expected, after, timeout=90):
started = time.monotonic()
qmp('human-monitor-command', {'command-line': 'sendkey ' + code})
wait_log(expected, after, timeout)
ended = time.monotonic()
log = safe()
acknowledgement = log.index(expected, after)
script_end = log.find(CORE_END, result['CoreScriptBeginSerialOffset'])
sample = {'Shortcut': code, 'HostInputToAcknowledgementSeconds': ended - started,
'AcknowledgementSerialOffset': acknowledgement,
'AcknowledgedBeforeCoreScriptEnd': script_end < 0 or acknowledgement < script_end,
'UnderOneSecond': ended - started < 1.0}
result['Samples'].append(sample)
return sample
try:
start = len(read_log()); click(60, 120)
wait_log('XFE_DESKTOP_ACTIVE|Files', start, 30)
folder = Path(screenshot('EditorResponsiveness-Files')).parent
start = len(read_log()); opened = time.monotonic(); click(220, 286)
# Serial writes can be observed halfway through a numeric field. A
# prefix match or splitlines() at EOF would silently truncate Frequency.
source_pattern = re.compile(r'^XFE_EDITOR_BACKGROUND\|SourcePresented\|Window\|2\|[^\r\n]+\r?\n', re.M)
deadline = time.monotonic() + 90
source_match = None
while time.monotonic() < deadline:
source_match = source_pattern.search(safe()[start:])
if source_match:
break
time.sleep(.005)
assert source_match, 'No complete source-presentation serial record'
observed = time.monotonic() - opened
source_line = source_match.group(0).rstrip('\r\n')
parts = source_line.split('|')
source_proof = dict(zip(parts[2::2], parts[3::2]))
fingerprint = 14695981039346656037
for value in EXPECTED.encode('utf-16-le'):
fingerprint = ((fingerprint ^ value) * 1099511628211) & ((1 << 64) - 1)
assert source_proof['FingerprintAlgorithm'] == 'UTF16LE-FNV1a64'
assert source_proof['SourceFingerprint'] == f'{fingerprint:016x}'
assert int(source_proof['SourceCharacters']) == len(EXPECTED)
assert int(source_proof['VisibleNonEmptyLines']) >= 10
source_frame = Path(screenshot('EditorResponsiveness-FirstSource'))
source_bands = []
with Image.open(source_frame) as image:
for row in (0, 4, 7):
x = int(source_proof['TextX']); y = int(source_proof['TextY']) + row * 20
line = EXPECTED.split('\n')[row]
bounds = tuple(round(value * scale) for value in (x, y, x + min(len(line) * 8, 740), y + 20))
band = image.crop(bounds).convert('RGB')
ink, columns = 0, set()
for yy in range(band.height):
for xx in range(band.width):
red, green, blue = band.getpixel((xx, yy))
if .2126 * red + .7152 * green + .0722 * blue >= 78:
ink += 1; columns.add(xx)
sample = {'SourceLine': row + 1, 'Text': line, 'NativeBounds': list(bounds), 'InkPixels': ink,
'InkColumns': len(columns), 'InkFraction': ink / max(1, band.width * band.height)}
assert ink >= 30 * scale * scale and len(columns) >= 24 * scale and .015 <= sample['InkFraction'] <= .65, sample
source_bands.append(sample)
elapsed = int(source_proof['ElapsedTicks']) / int(source_proof['Frequency'])
result['FirstSourcePresentation'] = {'NativeQueueToPresentedSeconds': elapsed,
'HostOpenToMarkerSeconds': observed, 'UnderOneSecond': elapsed < 1 and observed < 1,
'Proof': source_proof, 'Path': str(source_frame), 'Sha256': hashlib.sha256(source_frame.read_bytes()).hexdigest(),
'ActualGlyphBands': source_bands, 'Meaning': 'Real editable source first frame; full Monaco readiness is measured separately.'}
wait_log(CORE_BEGIN, start, 90)
script_begin = read_log().index(CORE_BEGIN, start)
result['CoreScriptBeginSerialOffset'] = script_begin
result['ClickToCoreScriptBeginSeconds'] = time.monotonic() - opened
# Send only after the largest original editor script has really begun.
before = len(read_log())
hidden = shortcut('meta_l-d', 'XFE_DESKTOP_FLAGS|0|0|Active|0', before)
result['HiddenFrame'] = str(screenshot('EditorResponsiveness-Hidden'))
# Acknowledge at least the hide operation during execution; restoration
# is also timed, even if a fast machine has already finished the script.
before = len(read_log())
shortcut('meta_l-d', 'XFE_DESKTOP_FLAGS|0|0|Active|2', before)
assert hidden['AcknowledgedBeforeCoreScriptEnd'], 'Win+D was queued until the actual Monaco script finished'
assert all(sample['UnderOneSecond'] for sample in result['Samples']), result['Samples']
workers = list(re.finditer(r'XFE_EDITOR_BACKGROUND\|WorkBegin\|Window\|2\|Generation\|(\d+)\|UiThread\|(\d+)\|Thread\|(\d+)\|', read_log()[start:]))
assert workers, 'No actual editor background worker began'
generation, ui_thread, worker_thread = map(int, workers[-1].groups())
assert ui_thread > 0 and worker_thread > 0 and ui_thread != worker_thread, ('Monaco did not run on a distinct scheduled thread', ui_thread, worker_thread)
result['ActualWorker'] = {'Generation': generation, 'UiThread': ui_thread, 'WorkerThread': worker_thread}
# Exercise the handoff/first UI font-layout period too. Moving only the
# script parse off-thread must not hide a later desktop stall.
wait_log('XFE_EDITOR_BACKGROUND|Prepared|Window|2|', start, 120)
wait_log('XFE_EDITOR_BACKGROUND|Ready|Window|2|', start, 120)
before = len(read_log())
handoff_hide = shortcut('meta_l-d', 'XFE_DESKTOP_FLAGS|0|0|Active|0', before)
before = len(read_log())
handoff_restore = shortcut('meta_l-d', 'XFE_DESKTOP_FLAGS|0|0|Active|2', before)
result['HandoffShortcuts'] = [handoff_hide, handoff_restore]
assert handoff_hide['UnderOneSecond'] and handoff_restore['UnderOneSecond'], result['HandoffShortcuts']
deadline = time.monotonic() + 120
proof = None
palette = website_palette()
last_error = 'No actual C# model'
while time.monotonic() < deadline:
log = safe()[start:]
for match in reversed(list(CSHARP_PROOF.finditer(log))):
candidate = json.loads(match.group(1))
if candidate.get('Language') != 'csharp' or candidate.get('ModelValue') != EXPECTED:
continue
try:
checked = verify_readback(candidate, palette)
proof = candidate
result['WebsiteCSharpSpanVerification'] = checked
except (AssertionError, KeyError, ValueError) as error:
last_error = str(error)
break
if proof:
break
time.sleep(.05)
assert proof, last_error
assert ('XFE_EDITOR_BACKGROUND|Ready|Window|2|Generation|' + str(generation) + '|') in read_log()[start:], 'The completed page was not handed back to the UI'
assert any(match.group(1).replace('\r', '') == EXPECTED for match in MODEL.finditer(read_log()[start:])), 'Actual Monaco getValue did not match the file'
result['ClickToMonacoReadySeconds'] = time.monotonic() - opened
result['ActualModelSha256'] = hashlib.sha256(EXPECTED.encode()).hexdigest()
result['ActualMonacoReadback'] = proof
# Geometry comes from the actual acknowledged editor window.
rows = list(re.finditer(r'XFE_WINDOW_STATE\|2\|Editor\|(-?\d+)\|(-?\d+)\|(\d+)\|(\d+)\|0\|', read_log()[start:]))
assert rows, 'Missing real editor geometry'
x, y, w, h = (int(value) for value in rows[-1].groups())
viewport = (x + 2, y + 67, w - 4, h - 96)
move(width / scale - 140, height / scale - 100)
deadline = time.monotonic() + 45
while True:
frame = Path(screenshot('EditorResponsiveness-Ready'))
with Image.open(frame) as pixels:
ink = csharp_frame_stats(pixels, viewport, scale, EXPECTED)
if ink['Passed'] or time.monotonic() >= deadline:
break
time.sleep(.15)
assert ink['Passed'], ink
result['ActualFramebuffer'] = {'Path': str(frame), 'Sha256': hashlib.sha256(frame.read_bytes()).hexdigest(), **ink}
# Keep the real focused editor alive through continued timer/layout/GC
# activity, rather than closing immediately after its first good frame.
stability_start = len(read_log()); stability_clock = time.monotonic()
stability_deadline = stability_clock + 30
while time.monotonic() < stability_deadline:
safe()
time.sleep(.05)
samples = []
for match in re.finditer(r'^XFE_RENDER_STATS\|[^\r\n]+\r?\n', read_log()[stability_start:], re.M):
fields = match.group(0).strip().split('|')
values = dict(zip(fields[2::2], fields[3::2]))
if 'RawFreePages' in values and 'RawTotalPages' in values:
samples.append({'Timestamp': int(fields[1]), 'FreePages': int(values['RawFreePages']), 'TotalPages': int(values['RawTotalPages'])})
assert len(samples) >= 10, 'No continuing native UI/raw-memory heartbeat during editor stability observation'
result['FocusedEditorObservation'] = {'Seconds': time.monotonic() - stability_clock, 'RawPageSamples': samples,
'MinimumRawFreePages': min(sample['FreePages'] for sample in samples), 'NoGuestHaltObserved': True,
'Meaning': 'Bounded observation of the real editor; not an unlimited memory/leak or isolation guarantee.'}
before = len(read_log()); qmp('human-monitor-command', {'command-line': 'sendkey ctrl-s'})
wait_log('XFE_DESKTOP_SAVED|X:\\Users\\Default\\Documents\\ZCSharp.cs|' + str(len(EXPECTED)), before, 30)
result['SavePreservedSource'] = True
before = len(read_log()); qmp('human-monitor-command', {'command-line': 'sendkey alt-f4'})
wait_log('XFE_DESKTOP_ACTIVE|Files', before, 30)
before = len(read_log()); click(220, 286)
wait_log('XFE_EDITOR_BACKGROUND|WorkBegin|Window|3|', before, 90)
close_start = len(read_log()); close_time = time.monotonic()
qmp('human-monitor-command', {'command-line': 'sendkey alt-f4'})
wait_log('XFE_DESKTOP_ACTIVE|Files', close_start, 30)
close_elapsed = time.monotonic() - close_time
wait_log('XFE_EDITOR_BACKGROUND|Cancelled|Window|3|', before, 90)
assert 'XFE_EDITOR_BACKGROUND|Ready|Window|3|' not in read_log()[before:], 'A closed editor accepted a stale worker result'
assert close_elapsed < 1, ('Closing during actual editor preparation stalled the desktop', close_elapsed)
result['CloseDuringPreparation'] = {'InputToAcknowledgementSeconds': close_elapsed, 'CancelledWorkerObserved': True,
'NoReadyAfterClose': True, 'Passed': True}
assert result['FirstSourcePresentation']['UnderOneSecond'], result['FirstSourcePresentation']
result['Passed'] = True
return result
except Exception as error:
result['Failure'] = str(error)
raise
finally:
if folder:
(folder / 'EditorResponsiveness.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')